diff --git a/examples/hybrid-v4-pure/server/content.ts b/examples/hybrid-v4-pure/server/content.ts index ddb409880..c3d7c3af5 100644 --- a/examples/hybrid-v4-pure/server/content.ts +++ b/examples/hybrid-v4-pure/server/content.ts @@ -1,4 +1,4 @@ -import { createNuxtContent } from '@nuxt/content/content' +import { createNuxtContent } from '@nuxt/content/server' import fs from 'comark-content/sources/fs' export const content = createNuxtContent({ diff --git a/migration.md b/migration.md index 108fefdc9..0f5f723fb 100644 --- a/migration.md +++ b/migration.md @@ -22,7 +22,7 @@ Nuxt Content 4 is built on [comark-content](https://content.comark.dev). Several | `server/cms.ts` | `server/content.ts` | | `export const cms` | `export const content` | | auto-imported `cms` | auto-imported `content` | -| `@nuxt/content/cms` | `@nuxt/content/content` | +| `@nuxt/content/cms` | `@nuxt/content/server` | ## `` is now `` @@ -45,7 +45,7 @@ Compared to v3's ``: ```ts // server/content.ts -import { createNuxtContent } from '@nuxt/content/content' +import { createNuxtContent } from '@nuxt/content/server' import fs from 'comark-content/sources/fs' import media from 'comark-content/plugins/media' @@ -67,6 +67,10 @@ export const content = createNuxtContent({ }) ``` +### v3 server composables + +`queryCollection`, `queryCollectionNavigation`, `queryCollectionItemSurroundings` and `queryCollectionSearchSections` are auto-imported while `content.compatibilityVersion` is `3`. To import them by hand, use `@nuxt/content/v3/server`: `@nuxt/content/server` now exports `createNuxtContent()`. + ### Sources provided by a layer A layer's `server/content.ts` is used when the project has none: the project's file comes first, then each layer's by priority. Without any `server/content.ts`, the v3 `content.config.ts` files of every layer are merged as before. With `content.compatibilityVersion: 4`, `content.config.ts` files are ignored, with a warning. @@ -128,7 +132,7 @@ To change their options, register your own plugin with the same name under `mark ```ts // server/content.ts -import { createNuxtContent } from '@nuxt/content/content' +import { createNuxtContent } from '@nuxt/content/server' import fs from 'comark-content/sources/fs' import toc from 'comark/plugins/toc' diff --git a/package.json b/package.json index ae03da6c4..c2e02205f 100644 --- a/package.json +++ b/package.json @@ -23,11 +23,11 @@ "import": "./dist/module.mjs" }, "./v3": "./dist/runtime/v3/index.js", - "./content": "./dist/runtime/server/content.js", + "./v3/server": "./dist/runtime/v3/composables.server.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" + "./server": "./dist/runtime/server/content.js" }, "main": "./dist/module.mjs", "typesVersions": { diff --git a/src/module.ts b/src/module.ts index fb77e66fd..f3231f9f8 100644 --- a/src/module.ts +++ b/src/module.ts @@ -1,6 +1,6 @@ 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 type { CacheArtifact, ContentSource, JsonSchema, Manifest, AnyComarkContent, ContentHub, ParsedSnapshot, TypegenFieldContext } from 'comark-content' 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' @@ -86,7 +86,8 @@ export default defineNuxtModule({ // Point the entries' imports at the runtime: the package exports target `dist/runtime/*.js`, which a stubbed build doesn't emit. nuxt.options.nitro.alias = defu(nuxt.options.nitro.alias, { - '@nuxt/content/content': resolve('./runtime/server/content'), + '@nuxt/content/server': resolve('./runtime/server/content'), + '@nuxt/content/v3/server': resolve('./runtime/v3/composables.server'), }) nuxt.options.alias['@nuxt/content/app'] = resolve('./runtime/client-content/app') nuxt.options.alias['@nuxt/content/worker'] = resolve('./runtime/client-content/worker') @@ -112,11 +113,19 @@ export default defineNuxtModule({ /** * Server */ - const content = await setupContent(serverContentPath, nuxt, options, contentCollections, highlight, toc, anchorLinks, !!(appContentPath || workerPath)) + const { content, live } = await setupContent(serverContentPath, nuxt, options, contentCollections, highlight, toc, anchorLinks, !!(appContentPath || workerPath)) + // Hybrid mode and `app/content.ts` read the build snapshot, which a live server moves past. + if (live && (options.mode === 'hybrid' || appContentPath)) { + throw new Error(options.mode === 'hybrid' + ? 'A `live` content needs `content.mode: \'server-only\'`: in hybrid mode, the browser reads the snapshot written at build.' + : 'A `live` content can\'t be used with `app/content.ts`: its browser instance reads the snapshot written at build.') + } // 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 + // Skip a live content: its documents are only known at runtime. + const readContent = content && !live && !nuxt.options.dev && !nuxt.options._prepare ? createContentReader(content) : undefined addServerImports({ name: 'content', from: serverContentPath }) + addServerImports(['resolveContent', 'revalidateContent'].map(name => ({ name, from: resolve('./runtime/server/live') }))) addServerHandler({ route: '/__nuxt_content/**', handler: { nuxt: resolve('./runtime/server/internal/api' + (nuxt.options.dev ? '.dev' : '')) } }) /** @@ -218,7 +227,7 @@ export default defineNuxtModule({ /** * Types */ - setupTypes(content, nuxt, contentCollections, readContent, options.compatibilityVersion === 3) + setupTypes(content, nuxt, contentCollections, readContent, options.compatibilityVersion === 3, live) /** * Media, skipped in prepare @@ -307,7 +316,7 @@ function setupHighlight(highlight: ResolvedHighlightOptions | false, nuxt: Nuxt) } } -async function setupTypes(content: ContentSurface | undefined, nuxt: Nuxt, collections: ResolvedContentCollections, readContent: ContentReader | undefined, v3: boolean) { +async function setupTypes(content: ContentSurface | undefined, nuxt: Nuxt, collections: ResolvedContentCollections, readContent: ContentReader | undefined, v3: boolean, live: boolean) { const importMetaTypes = addTypeTemplate({ filename: 'content/import-meta.d.ts', getContents: importMetaTypesTemplate }) const highlightTypes = addTypeTemplate({ filename: 'content/highlight.d.ts', getContents: highlightTypesTemplate }) @@ -327,7 +336,7 @@ async function setupTypes(content: ContentSurface | undefined, nuxt: Nuxt, colle nitroTypeIncludes.push( addTypeTemplate({ filename: 'content/types.d.ts', - getContents: () => generateContentTypes(content, collections, readContent, v3), + getContents: () => generateContentTypes(content, collections, readContent, v3, live), }).dst, ) } @@ -357,13 +366,19 @@ function withV3FieldTypes(hooks: AnyComarkContent['hooks']): AnyComarkContent['h /** * Generate the `ContentRegistry` augmentation. * An unreadable source, such as a layer's missing `content/`, falls back to its declared schema instead of dropping every type. + * A live content is typed from its declared schemas, so `nuxi prepare` needs no network. */ -async function generateContentTypes(content: ContentSurface, collections: ResolvedContentCollections, readContent: ContentReader | undefined, v3: boolean): Promise { +async function generateContentTypes(content: ContentSurface, collections: ResolvedContentCollections, readContent: ContentReader | undefined, v3: boolean, live: boolean): Promise { const reads = await readContent?.() const instances = await Promise.all(resolveInstances(content).map(async (instance) => { let manifest: Manifest try { - if (reads) { + if (live) { + // No declared schema means no generated type. + const schema = (instance.getSource() as { schema?: JsonSchema } | undefined)?.schema + manifest = { sources: [instance.name], items: {}, time: 0, schemas: schema ? { [instance.name]: schema } : {} } + } + else if (reads) { manifest = (await reads.get(instance.name)!).manifest } else { @@ -516,7 +531,10 @@ async function cloneSurface( }) } -async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOptions, collections: ResolvedContentCollections, highlight: ResolvedHighlightOptions | false, toc: ResolvedTocOptions, anchorLinks: string[], publicSnapshots: boolean): Promise { +// Marks a content created with a `live` option. +const LIVE = Symbol.for('nuxt-content:live') + +async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOptions, collections: ResolvedContentCollections, highlight: ResolvedHighlightOptions | false, toc: ResolvedTocOptions, anchorLinks: string[], publicSnapshots: boolean): Promise<{ content: ContentSurface, live: boolean }> { const { resolve } = createResolver(import.meta.url) const imported = await importContent(nuxt.options.rootDir, contentPath, { @@ -530,6 +548,7 @@ async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOpti // A separate surface, so the dev plugins and `basePath` don't mutate the instance Nitro imports. // `createNuxtContent()` already installed the v3 plugins with a shared database. const alreadyHasV3 = Boolean(imported.content && 'query' in imported.content) + const live = LIVE in imported.content const content = await cloneSurface(imported.content, { basePath: '/__NCDEV__/__nuxt_content', plugins: alreadyHasV3 ? [] : v3ServerPlugins(options.compatibilityVersion === 3), @@ -552,10 +571,22 @@ async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOpti if (!route.route.startsWith('/__nuxt_content')) return // 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)) { + // A live content publishes none: they would stay at the build's commit. + if (options.mode === 'server-only' && !(publicSnapshots && browserArtifact && !live)) { route.skip = true } + if (route.error) { + // Ship no snapshot for a live source the build couldn't read. + if (live) { + const name = route.route.match(/\/snapshot\/(.+)\.json$/)?.[1] + if (name) logger.warn(`Could not read \`${name}\` at the commit to serve, no snapshot is shipped for it: a cold start reads its source.`) + route.error = undefined + route.skip = true + } + return + } + await mkdir(dir, { recursive: true }) if (route.route === '/__nuxt_content/manifest.json') { await writeFile(resolve(dir, 'manifest.json'), route.contents!) @@ -590,7 +621,7 @@ async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOpti } } - return content + return { content, live } } function setupMedia(content: ContentWithMedia & MediaMethods, nuxt: Nuxt) { diff --git a/src/runtime/client-content/app.ts b/src/runtime/client-content/app.ts index c4c847181..123638446 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`. + * `createNuxtContent()` from `@nuxt/content/server`, for `compatibilityVersion: 4`. */ export function createNuxtContent(options: NuxtAppContentOptions = {}): ContentClient { if (import.meta.server) { diff --git a/src/runtime/server/commits.ts b/src/runtime/server/commits.ts new file mode 100644 index 000000000..0b090f836 --- /dev/null +++ b/src/runtime/server/commits.ts @@ -0,0 +1,59 @@ +// No Nuxt import, so this file can move to comark-content. +import type { Manifest } from 'comark-content' +import type { ForgeSource } from 'comark-content/sources/forge' +import type { RepoRef } from 'forges' + +/** + * Return a `live.ref` function: the last commit that touched `path` on `ref`. + * Takes the options of `forge()`. + * + * @example + * ```ts + * const docs = { provider: github(), repo: 'acme/docs', ref: 'main', path: 'content' } + * createNuxtContent({ mode: 'server-only', source: forge(docs), live: { ref: lastCommit(docs) } }) + * ``` + */ +export function lastCommit(options: ForgeSource): () => Promise { + const { provider, ref } = options + const path = (options.path ?? '').replace(/^\/+|\/+$/g, '') + const repo = typeof options.repo === 'string' ? toRepoRef(provider, options.repo) : options.repo + return async () => { + const { items } = await provider.commits.list(repo, { ref, path: path || undefined, perPage: 1 }).page() + const commit = items[0] + if (!commit) { + throw new Error(`lastCommit: no commit touches \`${path || '/'}\` on \`${ref ?? 'the default branch'}\` of \`${repo.owner}/${repo.name}\`.`) + } + return commit.sha + } +} + +// Parse `owner/name` as `forge()` does, nested GitLab groups included. +function toRepoRef(provider: ForgeSource['provider'], slug: string): RepoRef { + const parts = slug.replace(/^\/+|\/+$/g, '').split('/') + if (parts.length < 2) throw new Error(`lastCommit: repo must be "owner/name", got "${slug}".`) + return { forge: provider.forge, instance: provider.instance, owner: parts.slice(0, -1).join('/'), name: parts.at(-1)! } +} + +/** What changed in a source between two commits. */ +export interface CommitComparison { + /** Paths of documents added or whose source changed. */ + changed: string[] + /** Paths of documents that no longer exist. */ + removed: string[] + /** Whether a path was added or removed, or a listing field changed. */ + navigation: boolean +} + +/** Compare the manifests of a source at two commits. Without `before`, every document changed. */ +export function compareManifests(before: Manifest | undefined, after: Manifest): CommitComparison { + const documents = (manifest: Manifest | undefined) => new Map(Object.values(manifest?.items ?? {}) + .filter(item => item.meta.kind === 'document') + .map(item => [item.path, item])) + const from = documents(before) + const to = documents(after) + // Count a document without a hash as changed. + const changed = [...to].filter(([path, item]) => !item.meta.hash || from.get(path)?.meta.hash !== item.meta.hash).map(([path]) => path).sort() + const removed = [...from.keys()].filter(path => !to.has(path)).sort() + const navigation = !before || removed.length > 0 || [...to].some(([path, item]) => !from.has(path) || JSON.stringify(from.get(path)!.data) !== JSON.stringify(item.data)) + return { changed, removed, navigation } +} diff --git a/src/runtime/server/content.ts b/src/runtime/server/content.ts index cd8acc85a..360d1de0b 100644 --- a/src/runtime/server/content.ts +++ b/src/runtime/server/content.ts @@ -7,6 +7,10 @@ import headingLinks from 'comark/plugins/heading-links' import { v3ServerPlugins } from '../v3/content-plugins.server' import externalLinks from 'comark/plugins/external-links' import { highlight } from '#content/highlight' +import { setupLive, type LiveOptions } from './live' + +export { lastCommit } from './commits' +export { resolveContent, revalidateContent, type ContentRevalidation, type LiveOptions, type LiveRef } from './live' export type ContentInstance = AnyComarkContent // `ContentHub`: a hub over a mutable instance array isn't assignable to the @@ -27,6 +31,8 @@ interface NuxtContentOptions extends Omit * @default 'default' */ name?: string + /** Serve the content at a commit chosen at runtime. Needs `server-only` mode and sources with `withRef()`, such as `forge()`. */ + live?: LiveOptions } function snapshotLoaders(name: string) { @@ -72,7 +78,7 @@ function createInstance( options: NuxtContentOptions, sharedPlugins: ContentOptions['plugins'], ) { - const { mode: _mode, sources: _sources, source: _source, name: _name, plugins: _plugins, ...rest } = options + const { mode: _mode, sources: _sources, source: _source, name: _name, plugins: _plugins, live: _live, ...rest } = options return comarkContent(name, { ...rest, @@ -115,6 +121,8 @@ function withDefaultPlugins(markdown: ContentOptions['markdown']): ContentOption * instances composed with `contentHub()`. Production cold starts hydrate from * the prerendered snapshot via `withSnapshot()`. */ +export function createNuxtContent(options: NuxtContentOptions & { sources: Record }): ContentHub +export function createNuxtContent(options: NuxtContentOptions & { source: ContentSource, sources?: undefined }): ContentInstance export function createNuxtContent(options: NuxtContentOptions): ContentSurface { // One shared plugin set (and therefore one SQLite database) across every // instance so hub FTS ranks correctly. @@ -124,12 +132,17 @@ export function createNuxtContent(options: NuxtContentOptions): ContentSurface { const instances = Object.entries(options.sources).map(([name, source]) => createInstance(name, source, options, sharedPlugins), ) - return contentHub(instances, { basePath: '/__nuxt_content' }) + return withLive(contentHub(instances, { basePath: '/__nuxt_content' }), options) } if (!options.source) { throw new Error('createNuxtContent: pass `source` or `sources`.') } - return createInstance(options.name ?? 'default', options.source, options, sharedPlugins) + return withLive(createInstance(options.name ?? 'default', options.source, options, sharedPlugins), options) +} + +function withLive(content: ContentSurface, { live, cache }: NuxtContentOptions): ContentSurface { + if (live) setupLive(content, live, { cache, loadManifest: name => snapshotLoaders(name).loadManifest() }) + return content } diff --git a/src/runtime/server/internal/api.ts b/src/runtime/server/internal/api.ts index d92802061..7c7b0d8a7 100644 --- a/src/runtime/server/internal/api.ts +++ b/src/runtime/server/internal/api.ts @@ -1,6 +1,11 @@ import { defineEventHandler } from 'nuxt/server' import { content } from '#imports' import type { ContentSurface } from '../content' +import { resolveContentFor } from '../live' // Nitro resolves `content` to the server surface; the shared `#imports` typing is the app client. -export default defineEventHandler(event => (content as unknown as ContentSurface).handler(event.req)) +export default defineEventHandler(async (event) => { + // Source of the build snapshot route being prerendered. + const source = import.meta.prerender ? event.url.pathname.match(/^\/__nuxt_content\/(?:manifest|snapshot)\/([^/.]+)(?:\.json)?$/)?.[1] : undefined + return (await resolveContentFor(content as unknown as ContentSurface, source)).handler(event.req) +}) diff --git a/src/runtime/server/live.ts b/src/runtime/server/live.ts new file mode 100644 index 000000000..472a02010 --- /dev/null +++ b/src/runtime/server/live.ts @@ -0,0 +1,253 @@ +import { contentHub, readArtifact, type AnyComarkContent, type CacheArtifact, type CacheDriver, type CacheOptions, type ContentHub, type Manifest } from 'comark-content' +import { compareManifests, type CommitComparison } from './commits' + +type ContentInstance = AnyComarkContent +type ContentSurface = ContentInstance | ContentHub + +/** Return the commit to serve. */ +export type LiveRef = () => string | Promise + +export interface LiveOptions { + /** One function for every source, or one per source name. */ + ref: LiveRef | Record + /** Seconds the stored commits are served before the functions are called again. Without it, every request calls them. */ + maxAge?: number +} + +/** What changed in a source, from `revalidateContent()`. */ +export interface ContentRevalidation extends CommitComparison { + /** Commit served before, `null` when none was stored. */ + from: string | null + /** Commit served from now on. */ + to: string +} + +/** Commit of each source, by source name. */ +type Commits = Record + +interface StoredCommits { + /** When the functions were called, in milliseconds. */ + time: number + commits: Commits +} + +interface AskedCommits extends StoredCommits { + /** Functions that failed, with the sources they pin. */ + failed: { names: string[], error: Error }[] +} + +interface LiveState { + /** Each `live.ref` function, with the sources it pins. */ + refs: { ref: LiveRef, names: string[] }[] + maxAge?: number + /** Call in progress, shared by the requests waiting for it. */ + asking?: Promise + /** Sources whose function failed on the last call. */ + failing: Set + /** Whether the app passes a `cache.driver`. */ + sharedCache: boolean + /** The app's `cache.driver`, or this server's memory. */ + driver: Pick + /** Commit the build snapshot of a source is stamped with. */ + buildCommit: (name: string) => Promise + /** Pinned instances of each source: the served one, then the one before. */ + pinned: Map + /** Hub of the served instances. */ + hub?: ContentHub +} + +// Shared with the module, which imports its own copy of this file. +const LIVE = Symbol.for('nuxt-content:live') +// Instance names have no `-`, so the key can't collide with theirs. +const COMMITS_KEY = 'live-commits' + +const isHub = (content: ContentSurface): content is ContentHub => Array.isArray((content as ContentHub).names) +const liveState = (content: ContentSurface) => (content as { [LIVE]?: LiveState })[LIVE] +const sourceNames = (content: ContentSurface): string[] => isHub(content) ? [...content.names] : [content.name] + +/** Validate `live` and attach its state to `content`. */ +export function setupLive(content: ContentSurface, options: LiveOptions, { cache, loadManifest }: { + cache: CacheOptions | false | undefined + /** Load the manifest of a source's build snapshot. */ + loadManifest: (name: string) => Promise +}) { + const instances: ContentInstance[] = isHub(content) ? [...content.instances] : [content] + const names = instances.map(instance => instance.name) + // `fs()` and `unstorage()` have no `withRef()`. + const unpinnable = instances.filter(instance => typeof instance.getSource()?.withRef !== 'function').map(instance => instance.name) + if (unpinnable.length) { + throw new Error(`createNuxtContent: \`live\` needs sources that can be pinned to a commit, such as \`forge()\` or a source with \`withRef()\`. ${unpinnable.map(name => `\`${name}\``).join(', ')} can't.`) + } + const { ref } = options + const missing = typeof ref === 'function' ? [] : names.filter(name => typeof ref?.[name] !== 'function') + if (!ref || missing.length) { + throw new Error(`createNuxtContent: \`live.ref\` needs a function returning the commit to serve${missing.length ? `, and has none for ${missing.map(name => `\`${name}\``).join(', ')}` : ''}.`) + } + const refs = typeof ref === 'function' ? [{ ref, names }] : names.map(name => ({ ref: ref[name]!, names: [name] })) + let memory: string | undefined + // Keep the build's commits out of the driver the servers read. + const driver = (!import.meta.prerender && cache && cache.driver) || { getItem: () => memory, setItem: (_key: string, value: string) => void (memory = value) } + const buildCommits = new Map>() + const buildCommit = (name: string) => buildCommits.get(name) ?? buildCommits.set(name, loadManifest(name) + .then(async artifact => artifact ? (await readArtifact(artifact)).ref : undefined) + .catch(() => undefined)).get(name)! + Object.defineProperty(content, LIVE, { value: { refs, maxAge: options.maxAge, failing: new Set(), sharedCache: Boolean(cache && cache.driver), driver, buildCommit, pinned: new Map() } satisfies LiveState }) +} + +/** Return the content pinned to the commits being served. A content that isn't live, or any content in dev, is returned as is. */ +export function resolveContent(content: T): Promise { + return resolveContentFor(content) +} + +/** + * `resolveContent()` for the module's handler, where a build snapshot route only needs the commit of `source`. + * @internal + */ +export async function resolveContentFor(content: T, source?: string): Promise { + const state = liveState(content) + if (!state || import.meta.dev) return content + return contentAt(content, state, await servedCommits(content, state, source)) as T +} + +/** Return the stored commits, or call the functions once they're older than `maxAge`. */ +async function servedCommits(content: ContentSurface, state: LiveState, source?: string): Promise { + let asked: AskedCommits + if (import.meta.prerender) { + // Call once per build, so every snapshot is stamped from the same call. + asked = await (state.asking ||= askCommits(state, undefined)) + } + else { + const stored = await readCommits(state) + if (stored && state.maxAge && Date.now() - stored.time < state.maxAge * 1000 && sourceNames(content).every(name => stored.commits[name])) { + return stored.commits + } + // Share the call with the requests arriving meanwhile. + asked = await (state.asking ||= askCommits(state, stored).finally(() => state.asking = undefined)) + } + const { commits, failed } = asked + const failing = new Set(failed.flatMap(({ names }) => names)) + for (const { names, error } of failed) { + const missing = names.filter(name => !commits[name] && (!source || name === source)) + if (missing.length) throw new Error(`[@nuxt/content] The \`live.ref\` function of \`${missing.join('`, `')}\` failed, and no commit is stored to serve instead: ${error.message}`, { cause: error }) + // Warn once per outage. + if (names.some(name => commits[name] && !state.failing.has(name))) console.warn(`[@nuxt/content] The \`live.ref\` function of \`${names.join('`, `')}\` failed, serving \`${commits[names[0]!]}\`:`, error.message) + } + state.failing = failing + return commits +} + +/** + * Call every `live.ref` function, store the commits and return what changed. + * Returns one result for a `source`, or one per source whose commit moved for `sources`. + * Throws when a function failed, after storing the commits of the others. + */ +export async function revalidateContent(content: ContentInstance): Promise +export async function revalidateContent(content: ContentHub): Promise> +export async function revalidateContent(content: ContentSurface): Promise> +export async function revalidateContent(content: ContentSurface): Promise> { + const state = liveState(content) + if (!state) throw new Error('revalidateContent: this content has no `live` option.') + if (import.meta.dev) throw new Error('revalidateContent: in dev, a live content is read from its source as it is. There is no commit to move.') + + const stored = await readCommits(state) + const { commits, failed } = await askCommits(state, stored) + if (failed.length) { + throw new Error(`revalidateContent: the \`live.ref\` function of ${failed.map(({ names }) => names.map(name => `\`${name}\``).join(', ')).join(', ')} failed: ${failed.map(({ error }) => error.message).join(' ')}`, { cause: failed[0]!.error }) + } + const next = contentAt(content, state, commits) + + const results: Record = {} + await Promise.all(sourceNames(content).map(async (name) => { + const from = stored?.commits[name] ?? null + const to = commits[name]! + if (from === to && isHub(content)) return + const instance = isHub(next) ? next.from(name) : next + const before = from && from !== to ? await manifestAt(isHub(content) ? content.from(name) : content, state, from) : undefined + results[name] = { from, to, ...(from === to ? { changed: [], removed: [], navigation: false } : compareManifests(before, await instance.manifest())) } + })) + return isHub(content) ? results : results[content.name]! +} + +async function readCommits(state: LiveState): Promise { + try { + const value = await state.driver.getItem(COMMITS_KEY, {}) + // Drivers return the stored string, or parsed JSON. + const stored = (typeof value === 'string' ? JSON.parse(value) : value) as StoredCommits | null | undefined + return stored && typeof stored.time === 'number' && stored.commits ? stored : undefined + } + catch { + // Treat an unreadable entry as missing. + return undefined + } +} + +/** Call every `live.ref` function and store the commits. A failed source keeps its stored commit, or its build snapshot's. */ +async function askCommits(state: LiveState, stored: StoredCommits | undefined): Promise { + const time = Date.now() + const commits: Commits = {} + const failed: AskedCommits['failed'] = [] + await Promise.all(state.refs.map(async ({ ref, names }) => { + try { + const commit = await ref() + if (typeof commit !== 'string' || !commit) throw new Error('`live.ref` returned no commit.') + for (const name of names) commits[name] = commit + } + catch (error) { + failed.push({ names, error: error as Error }) + for (const name of names) { + const commit = stored?.commits[name] ?? await state.buildCommit(name) + if (commit) commits[name] = commit + } + } + })) + // Keep the commits of a call that started later, such as a webhook's. + const latest = await readCommits(state) + if (latest && latest.time > time) return { ...latest, failed: [] } + await state.driver.setItem?.(COMMITS_KEY, JSON.stringify({ time, commits } satisfies StoredCommits), {}) + return { time, commits, failed } +} + +/** Pin each source of `content` to its commit. */ +function contentAt(content: ContentSurface, state: LiveState, commits: Commits): ContentSurface { + if (!isHub(content)) return instanceAt(content, state, commits[content.name]!) + // A source without a commit stays unpinned, which only happens on a build snapshot route of another source. + const instances = content.names.map((name: string) => commits[name] ? instanceAt(content.from(name), state, commits[name]) : content.from(name)) + // Reuse the hub while no instance changed. + if (!state.hub || instances.some((instance, index) => instance !== state.hub!.instances[index])) { + state.hub = contentHub(instances, { basePath: content.basePath }) + } + return state.hub +} + +/** Return the instance of a source at `commit`. Keeps the previous one for requests in flight and releases older ones. */ +function instanceAt(instance: ContentInstance, state: LiveState, commit: string): ContentInstance { + const [current, previous] = state.pinned.get(instance.name) ?? [] + if (current?.ref === commit) return current + // Reuse the previous instance when going back to its commit. + const next = previous?.ref === commit ? previous : instance.withRef(commit) + state.pinned.set(instance.name, current ? [next, current] : [next]) + if (previous && previous !== next) { + release(previous, state).catch(error => console.warn(`[@nuxt/content] Could not release \`${instance.name}\` at \`${previous.ref}\`:`, (error as Error).message)) + } + return next +} + +/** Dispose an instance, and delete what it stored unless other servers share the driver. */ +async function release(instance: ContentInstance, state: LiveState) { + if (state.sharedCache) await instance.dispose() + else await instance.clean() +} + +/** Return the manifest of a source at a commit served before. */ +async function manifestAt(instance: ContentInstance, state: LiveState, commit: string) { + const pinned = state.pinned.get(instance.name)?.find(({ ref }) => ref === commit) + if (pinned) return await pinned.manifest() + // Served by another server: read it from the shared driver. + const other = instance.withRef(commit) + try { + return await other.manifest() + } + finally { + await other.dispose() + } +} diff --git a/src/utils/config.ts b/src/utils/config.ts index 101b4e896..a6b8efaef 100644 --- a/src/utils/config.ts +++ b/src/utils/config.ts @@ -19,7 +19,7 @@ export type ImportContentOptions = { toc?: ResolvedTocOptions /** Heading tags resolved from `content.renderer.anchorLinks`. */ anchorLinks?: string[] - /** This module's `@nuxt/content/content` entry, so it resolves without going through `dist` (stubbed builds). */ + /** This module's `@nuxt/content/server` entry, so it resolves without going through `dist` (stubbed builds). */ contentEntryPath?: string } @@ -31,7 +31,7 @@ function createContentJiti(rootDir: string, options: ImportContentOptions) { fsCache: false, alias: { ...(options.highlightPath ? { '#content/highlight': options.highlightPath } : {}), - ...(options.contentEntryPath ? { '@nuxt/content/content': options.contentEntryPath } : {}), + ...(options.contentEntryPath ? { '@nuxt/content/server': options.contentEntryPath } : {}), }, transform: (opts) => { const source = opts.source diff --git a/test/fixtures/app-content/server/content.ts b/test/fixtures/app-content/server/content.ts index 870d5a739..0835b3cbf 100644 --- a/test/fixtures/app-content/server/content.ts +++ b/test/fixtures/app-content/server/content.ts @@ -1,4 +1,4 @@ -import { createNuxtContent } from '@nuxt/content/content' +import { createNuxtContent } from '@nuxt/content/server' import fs from 'comark-content/sources/fs' export const content = createNuxtContent({ diff --git a/test/fixtures/layer-sources/docs-layer/server/content.ts b/test/fixtures/layer-sources/docs-layer/server/content.ts index 44fc050cf..dbfa6093f 100644 --- a/test/fixtures/layer-sources/docs-layer/server/content.ts +++ b/test/fixtures/layer-sources/docs-layer/server/content.ts @@ -1,7 +1,7 @@ import { existsSync } from 'node:fs' import { join } from 'node:path' import type { JsonSchema } from 'comark-content' -import { createNuxtContent } from '@nuxt/content/content' +import { createNuxtContent } from '@nuxt/content/server' import fs from 'comark-content/sources/fs' import json from 'comark-content/plugins/json' import yaml from 'comark-content/plugins/yaml' diff --git a/test/fixtures/layer-sources/server/api/sources.get.ts b/test/fixtures/layer-sources/server/api/sources.get.ts index 5d3c07120..34e0424d5 100644 --- a/test/fixtures/layer-sources/server/api/sources.get.ts +++ b/test/fixtures/layer-sources/server/api/sources.get.ts @@ -1,4 +1,5 @@ // Served by the deployed function, which evaluates the layer's `server/content.ts` again without `content/`. +// `resolveContent()` returns a content that isn't live as is. export default defineEventHandler(async () => { - return (await content.list()).map((file: { path: string }) => file.path).sort() + return (await (await resolveContent(content)).list()).map((file: { path: string }) => file.path).sort() }) diff --git a/test/fixtures/live-fixture.ts b/test/fixtures/live-fixture.ts new file mode 100644 index 000000000..ed06b6d2c --- /dev/null +++ b/test/fixtures/live-fixture.ts @@ -0,0 +1,42 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll } from 'vitest' +import { useTestContext } from '@nuxt/test-utils/e2e' +import { startVercelFunction } from './vercel-function' + +export const liveFixtureDir = fileURLToPath(new URL('./live', import.meta.url)) + +export type LiveServer = Awaited> + +export const tmpDir = () => mkdtempSync(join(tmpdir(), 'nuxt-content-live-')) + +/** Start servers of the built `live` fixture, each with its own forge. Servers given the same `LIVE_CACHE_DIR` share a cache driver. */ +export function useLiveServers(defaults: Record = {}) { + const servers: LiveServer[] = [] + afterAll(() => { + for (const server of servers) server.stop() + }) + return async (env: Record = {}) => { + const server = await startVercelFunction(useTestContext().nuxt!.options.nitro.output!.dir!, { LIVE_CACHE_DIR: tmpDir(), LIVE_FORGE: 'online', ...defaults, ...env }) + servers.push(server) + return server + } +} + +export async function json(server: LiveServer, path: string, init?: RequestInit) { + const response = await fetch(server.url + path, { ...init, signal: AbortSignal.timeout(15_000) }) + if (!response.ok) throw new Error(`${path}: ${response.status} ${await response.text()}`) + return await response.json() as T +} + +/** Return the first heading of the document at `path`. */ +export const title = async (server: LiveServer, path: string) => JSON.stringify(await json(server, `/__nuxt_content/get${path}`)).match(/(?:Home|Docs) at \w+/)?.[0] + +/** Move the head of `repo`, then call `revalidateContent()` unless `revalidate` is false. */ +export const push = >(server: LiveServer, repo: string, head: string, revalidate = true) => + json(server, '/api/push', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ repo, head, revalidate }) }) + +/** Set how the server's forge answers and return what was asked of it. */ +export const forge = (server: LiveServer, query = '') => json<{ asked: string[] }>(server, `/api/forge?${query}`) diff --git a/test/fixtures/live/app/app.vue b/test/fixtures/live/app/app.vue new file mode 100644 index 000000000..017358ca2 --- /dev/null +++ b/test/fixtures/live/app/app.vue @@ -0,0 +1,11 @@ + + + diff --git a/test/fixtures/live/app/components/LiveAlert.vue b/test/fixtures/live/app/components/LiveAlert.vue new file mode 100644 index 000000000..15a1cfa4d --- /dev/null +++ b/test/fixtures/live/app/components/LiveAlert.vue @@ -0,0 +1,5 @@ + diff --git a/test/fixtures/live/app/content.worker.ts b/test/fixtures/live/app/content.worker.ts new file mode 100644 index 000000000..96f13b9d3 --- /dev/null +++ b/test/fixtures/live/app/content.worker.ts @@ -0,0 +1,5 @@ +import { createNuxtContentWorker, sqliteFullTextSearch, sqliteWasm } from '@nuxt/content/worker' + +export default createNuxtContentWorker({ + plugins: [sqliteFullTextSearch({ database: sqliteWasm() })], +}) diff --git a/test/fixtures/live/nuxt.config.ts b/test/fixtures/live/nuxt.config.ts new file mode 100644 index 000000000..d268dc506 --- /dev/null +++ b/test/fixtures/live/nuxt.config.ts @@ -0,0 +1,19 @@ +import MyModule from '../../../src/module' + +export default defineNuxtConfig({ + 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: { + // Vercel Build Output: public files go to the CDN, everything else to one function. + preset: 'vercel', + // As for an installed module: Nitro doesn't auto-import in files under `node_modules`. + imports: { exclude: [/\/src\/runtime\//] }, + }, +}) diff --git a/test/fixtures/live/package.json b/test/fixtures/live/package.json new file mode 100644 index 000000000..5aec8a72c --- /dev/null +++ b/test/fixtures/live/package.json @@ -0,0 +1,5 @@ +{ + "private": true, + "name": "live", + "type": "module" +} diff --git a/test/fixtures/live/server/api/forge.ts b/test/fixtures/live/server/api/forge.ts new file mode 100644 index 000000000..537b328e5 --- /dev/null +++ b/test/fixtures/live/server/api/forge.ts @@ -0,0 +1,12 @@ +import { defineEventHandler, getQuery } from 'nuxt/server' +import { forgeState } from '../forge' + +// Set how the forge answers and return what was asked of it since the last `?reset`. +export default defineEventHandler((event) => { + const query = getQuery(event) + if (query.online !== undefined) forgeState.online = query.online === 'true' + if (query.down !== undefined) forgeState.down = String(query.down) + if (query.slow !== undefined) forgeState.slow = Number(query.slow) + if (query.reset !== undefined) forgeState.asked.length = 0 + return forgeState +}) diff --git a/test/fixtures/live/server/api/push.post.ts b/test/fixtures/live/server/api/push.post.ts new file mode 100644 index 000000000..569dbd7ff --- /dev/null +++ b/test/fixtures/live/server/api/push.post.ts @@ -0,0 +1,17 @@ +import { defineEventHandler, readBody, setResponseStatus } from 'nuxt/server' +import { content } from '../content' +import { heads } from '../forge' + +// Move the head of `repo` and revalidate, as a push webhook does. +export default defineEventHandler(async (event) => { + const { repo, head, revalidate = true } = await readBody<{ repo: string, head: string, revalidate?: boolean }>(event) + heads[repo] = head + if (!revalidate) return {} + try { + return await revalidateContent(content) + } + catch (error) { + setResponseStatus(event, 500) + return { error: (error as Error).message } + } +}) diff --git a/test/fixtures/live/server/api/served.ts b/test/fixtures/live/server/api/served.ts new file mode 100644 index 000000000..e86abefd3 --- /dev/null +++ b/test/fixtures/live/server/api/served.ts @@ -0,0 +1,15 @@ +import { defineEventHandler } from 'nuxt/server' +import type { AnyComarkContent } from 'comark-content' +import { content } from '../content' + +const served: Record = {} + +// Return every instance each source was served from, with its status now. +export default defineEventHandler(async () => { + const resolved = await resolveContent(content) + for (const instance of 'instances' in resolved ? resolved.instances as AnyComarkContent[] : [resolved]) { + const instances = served[instance.name] ||= [] + if (!instances.includes(instance)) instances.push(instance) + } + return Object.fromEntries(Object.entries(served).map(([name, instances]) => [name, instances.map(({ ref, status }) => ({ ref, status }))])) +}) diff --git a/test/fixtures/live/server/cache.ts b/test/fixtures/live/server/cache.ts new file mode 100644 index 000000000..736eb50ad --- /dev/null +++ b/test/fixtures/live/server/cache.ts @@ -0,0 +1,22 @@ +import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import type { CacheDriver } from 'comark-content' + +/** Cache driver storing one file per key in `dir`, so servers can share it. */ +export function fileDriver(dir: string): CacheDriver { + mkdirSync(dir, { recursive: true }) + const file = (key: string) => join(dir, encodeURIComponent(key)) + return { + getItem: (key) => { + try { + return readFileSync(file(key), 'utf8') + } + catch { + return null + } + }, + setItem: (key, value) => writeFileSync(file(key), value), + removeItem: key => rmSync(file(key), { force: true }), + getKeys: base => readdirSync(dir).map(decodeURIComponent).filter(key => key.startsWith(base)), + } +} diff --git a/test/fixtures/live/server/content.ts b/test/fixtures/live/server/content.ts new file mode 100644 index 000000000..53f1548c6 --- /dev/null +++ b/test/fixtures/live/server/content.ts @@ -0,0 +1,53 @@ +import { createNuxtContent, lastCommit } from '@nuxt/content/server' +import forge from 'comark-content/sources/forge' +import fs from 'comark-content/sources/fs' +import { fileDriver } from './cache' +import { head, provider } from './forge' + +const site = { provider, repo: 'acme/site', ref: 'main', path: 'content' } +const docs = { provider, repo: 'acme/docs', ref: 'main', path: 'docs' } +const docsSource = forge({ ...docs, prefix: '/docs', schema: { type: 'object', properties: { title: { type: 'string' }, badge: { type: 'string' } } } }) +const cache = process.env.LIVE_CACHE_DIR ? { driver: fileDriver(process.env.LIVE_CACHE_DIR) } : undefined + +// One per build of the fixture, picked with `LIVE_FORM`. +const forms = { + // One function per source, in two repositories. + sources: () => createNuxtContent({ + mode: 'server-only', + sources: { site: forge(site), docs: docsSource }, + cache, + live: { + ref: { + site: head('acme/site'), + docs: lastCommit({ ...docs, path: process.env.LIVE_LAST_COMMIT_PATH || docs.path }), + }, + maxAge: Number(process.env.LIVE_MAX_AGE || 3600), + }, + }), + // One source, no cache driver, no `maxAge`. + source: () => createNuxtContent({ + mode: 'server-only', + source: docsSource, + live: { ref: lastCommit(docs) }, + }), + // One function for two sources of one repository. + shared: () => createNuxtContent({ + mode: 'server-only', + sources: { docs_en: docsSource, docs_fr: forge({ ...docs, path: 'fr', prefix: '/fr' }) }, + cache, + live: { ref: head('acme/docs'), maxAge: 3600 }, + }), + // Rejected at setup. + unpinnable: () => createNuxtContent({ + mode: 'server-only', + sources: { site: fs('content', { cwd: import.meta.rootDir }), docs: docsSource }, + live: { ref: head('acme/docs') }, + }), + missing: () => createNuxtContent({ + mode: 'server-only', + sources: { site: forge(site), docs: docsSource }, + live: { ref: { docs: lastCommit(docs) } }, + }), +} + +export const content = forms[(process.env.LIVE_FORM || 'sources') as keyof typeof forms]() diff --git a/test/fixtures/live/server/forge.ts b/test/fixtures/live/server/forge.ts new file mode 100644 index 000000000..dc779df39 --- /dev/null +++ b/test/fixtures/live/server/forge.ts @@ -0,0 +1,110 @@ +import { createHash } from 'node:crypto' +import { fake } from 'forges/fake' + +const guide = '# Guide\n\nRead it first.\n\nWritten at d1.' +const alert = '# New\n\n::live-alert\nOnly since d3.\n::' +const fr = '# Docs en français' + +/** Files of each commit, by repository. `c2` changes no content. */ +const commits: Record>> = { + 'acme/site': { + s1: { 'content/index.md': '# Home at s1', 'content/about.md': '# About' }, + s2: { 'content/index.md': '# Home at s2', 'content/about.md': '# About' }, + s3: { 'content/index.md': '# Home at s3', 'content/about.md': '# About' }, + }, + 'acme/docs': { + d1: { 'docs/index.md': '# Docs at d1', 'docs/guide.md': guide, 'docs/old.md': '# Old', 'fr/index.md': fr, 'README.md': 'v1' }, + c2: { 'docs/index.md': '# Docs at d1', 'docs/guide.md': guide, 'docs/old.md': '# Old', 'fr/index.md': fr, 'README.md': 'v2' }, + d3: { 'docs/index.md': '# Docs at d3', 'docs/guide.md': guide, 'docs/new.md': alert, 'fr/index.md': fr, 'README.md': 'v2' }, + d4: { 'docs/index.md': '# Docs at d3', 'docs/guide.md': guide.replace('at d1', 'at d4'), 'docs/new.md': alert, 'fr/index.md': fr, 'README.md': 'v2' }, + }, +} + +/** Head commit of each repository, moved by `/api/push`. */ +export const heads: Record = { 'acme/site': 's1', 'acme/docs': process.env.LIVE_DOCS_HEAD || 'd1' } + +/** What was asked of the forge and how it answers, read and set by `/api/forge`. */ +export const forgeState = { + /** One entry per request, such as `tree acme/docs@d1`, `commits acme/docs:docs` or `head acme/site`. */ + asked: [] as string[], + online: process.env.LIVE_FORGE !== 'offline', + /** Repository whose `live.ref` function fails. */ + down: process.env.LIVE_DOWN || '', + /** Milliseconds `head()` takes. */ + slow: 0, +} +// Expose the copies the module imports, to check it asks nothing of the forge. +if (import.meta.prerender === undefined) { + ((globalThis as { __liveModuleForge?: typeof forgeState[] }).__liveModuleForge ||= []).push(forgeState) +} + +const fakeForge = fake({ + seed: { + repos: Object.keys(commits).map(repo => ({ repo })), + files: Object.entries(commits).flatMap(([repo, shas]) => Object.entries(shas).flatMap(([ref, files]) => + Object.entries(files).map(([path, content]) => ({ repo, ref, path, content })))), + }, +}) + +const slug = (repo: { owner: string, name: string }) => `${repo.owner}/${repo.name}` +/** Resolve a ref to a commit, a branch being at its head. */ +const commitOf = (repo: string, ref: string) => commits[repo]![ref] ? ref : heads[repo]! +const offline = () => new Error('The forge is offline.') +const gitBlobId = (content: string) => createHash('sha1').update(`blob ${Buffer.byteLength(content)}\0${content}`).digest('hex') + +/** Fake forge that answers as GitHub where `forges/fake` differs: blob IDs in trees, and `commits.list()` on a directory. */ +export const provider = new Proxy(fakeForge, { + get: (target, key) => { + if (key === 'contents') { + return { + ...target.contents, + getFile: async (repo: any, path: string, options: any) => { + forgeState.asked.push(`file ${slug(repo)}@${options.ref}:${path}`) + if (!forgeState.online) throw offline() + return target.contents.getFile(repo, path, { ...options, ref: commitOf(slug(repo), options.ref) }) + }, + tree: (repo: any, options: any) => { + forgeState.asked.push(`tree ${slug(repo)}@${options.ref}`) + const files = commits[slug(repo)]![commitOf(slug(repo), options.ref)]! + const entries = Object.entries(files) + .filter(([path]) => !options.path || path.startsWith(`${options.path}/`)) + .map(([path, content]) => ({ path, type: 'file', sha: gitBlobId(content) })) + return Object.assign((async function* () { + if (!forgeState.online) throw offline() + yield* entries + })(), { warnings: [] }) + }, + } + } + if (key === 'commits') { + return { + list: (repo: any, query: { ref?: string, path?: string }) => ({ + page: async () => { + forgeState.asked.push(`commits ${slug(repo)}:${query.path}`) + if (!forgeState.online || forgeState.down === slug(repo)) throw offline() + // Commits of the branch, newest first. + const shas = Object.keys(commits[slug(repo)]!) + const history = shas.slice(0, shas.indexOf(heads[slug(repo)]!) + 1).reverse() + const files = (sha: string) => JSON.stringify(Object.entries(commits[slug(repo)]![sha] ?? {}).filter(([path]) => !query.path || path.startsWith(`${query.path}/`))) + // Keep the commits whose files under `path` differ from their parent's. + const touching = history.filter((sha, index) => files(sha) !== files(history[index + 1] ?? '')) + return { items: touching.map(sha => ({ sha })) } + }, + }), + } + } + return Reflect.get(target, key) + }, +}) + +/** Return a `live.ref` function: the head of `repo`. */ +export function head(repo: string) { + return async () => { + forgeState.asked.push(`head ${repo}`) + if (!forgeState.online || forgeState.down === repo) throw offline() + // Read the head before the delay, as a forge answers. + const commit = heads[repo]! + if (forgeState.slow) await new Promise(resolve => setTimeout(resolve, forgeState.slow)) + return commit + } +} diff --git a/test/fixtures/v3-page-defaults/server/api/pages.ts b/test/fixtures/v3-page-defaults/server/api/pages.ts index d3df2225a..3ded7a346 100644 --- a/test/fixtures/v3-page-defaults/server/api/pages.ts +++ b/test/fixtures/v3-page-defaults/server/api/pages.ts @@ -1,3 +1,5 @@ +import { queryCollection } from '@nuxt/content/v3/server' + // What v3 pages expose for `useSeoMeta(page.seo)` and listings. export default defineEventHandler(async (event) => { const pages = await queryCollection(event, 'content').all() diff --git a/test/fixtures/vercel-function.ts b/test/fixtures/vercel-function.ts new file mode 100644 index 000000000..c658bef38 --- /dev/null +++ b/test/fixtures/vercel-function.ts @@ -0,0 +1,28 @@ +import { spawn } from 'node:child_process' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' + +/** Start the Vercel function of the build in `outputDir` alone, without its static files. */ +export async function startVercelFunction(outputDir: string, env: Record = {}) { + const entry = join(outputDir, 'functions/__fallback.func/index.mjs') + const fn = spawn(process.execPath, ['--input-type=module', '-e', ` + import { createServer } from 'node:http' + const { default: handler } = await import(${JSON.stringify(pathToFileURL(entry).href)}) + const server = createServer(handler).listen(0, () => console.log('port=' + server.address().port)) + `], { env: { ...process.env, ...env } }) + let output = '' + fn.stderr!.on('data', data => output += data) + const port = await new Promise((resolve, reject) => { + fn.stdout!.on('data', (data) => { + output += data + const match = String(data).match(/port=(\d+)/) + if (match) resolve(match[1]!) + }) + fn.once('exit', code => reject(new Error(`The Vercel function exited with code ${code}: ${output}`))) + }) + return { + url: `http://localhost:${port}`, + output: () => output, + stop: () => fn.kill(), + } +} diff --git a/test/fixtures/worker-search/server/content.ts b/test/fixtures/worker-search/server/content.ts index 806c701a6..136dc37cd 100644 --- a/test/fixtures/worker-search/server/content.ts +++ b/test/fixtures/worker-search/server/content.ts @@ -1,4 +1,4 @@ -import { createNuxtContent } from '@nuxt/content/content' +import { createNuxtContent } from '@nuxt/content/server' import fs from 'comark-content/sources/fs' export const content = createNuxtContent({ diff --git a/test/live-dev.test.ts b/test/live-dev.test.ts new file mode 100644 index 000000000..4b7ab3443 --- /dev/null +++ b/test/live-dev.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest' +import { setup, $fetch, fetch } from '@nuxt/test-utils/e2e' +import { liveFixtureDir } from './fixtures/live-fixture' + +describe('live content in dev', async () => { + await setup({ + rootDir: liveFixtureDir, + dev: true, + }) + + it('reads the sources as they are, without calling `live.ref`', { timeout: 30_000 }, async () => { + expect(JSON.stringify(await $fetch('/__nuxt_content/get/docs'))).toContain('Docs at d1') + expect(await $fetch('/api/served')).toEqual({ + site: [{ status: expect.any(String) }], + docs: [{ status: expect.any(String) }], + }) + expect((await $fetch<{ asked: string[] }>('/api/forge')).asked.filter(request => /^(?:head|commits) /.test(request))).toEqual([]) + }) + + it('fails `revalidateContent()`: there is no commit to move', { timeout: 30_000 }, async () => { + const response = await fetch('/api/push', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ repo: 'acme/docs', head: 'd3' }) }) + expect(response.status).toBe(500) + expect((await response.json()).error).toMatch(/^revalidateContent: in dev/) + }) +}) diff --git a/test/live-forms.test.ts b/test/live-forms.test.ts new file mode 100644 index 000000000..30574fcbd --- /dev/null +++ b/test/live-forms.test.ts @@ -0,0 +1,74 @@ +import { afterAll, beforeAll, describe, it, expect } from 'vitest' +import { setup } from '@nuxt/test-utils/e2e' +import { forge, json, liveFixtureDir, push, title, tmpDir, useLiveServers } from './fixtures/live-fixture' + +/** Set the variables the fixture reads while it's built. */ +function buildEnv(env: Record) { + beforeAll(() => { + Object.assign(process.env, env) + }) + afterAll(() => { + for (const name of Object.keys(env)) Reflect.deleteProperty(process.env, name) + }) +} + +describe('live content, with one source', async () => { + buildEnv({ LIVE_FORM: 'source' }) + await setup({ rootDir: liveFixtureDir, server: false }) + const start = useLiveServers({ LIVE_FORM: 'source', LIVE_CACHE_DIR: '' }) + + it('returns the result of its source from `revalidateContent()`', { timeout: 20_000 }, async () => { + const server = await start() + expect(await title(server, '/docs')).toBe('Docs at d1') + expect(await push(server, 'acme/docs', 'c2')).toEqual({ from: 'd1', to: 'd1', changed: [], removed: [], navigation: false }) + expect(await push(server, 'acme/docs', 'd3')).toEqual({ from: 'd1', to: 'd3', changed: ['/docs', '/docs/new'], removed: ['/docs/old'], navigation: true }) + }) + + it('calls the function on every request without `live.maxAge`', { timeout: 20_000 }, async () => { + const server = await start() + expect(await title(server, '/docs')).toBe('Docs at d1') + await push(server, 'acme/docs', 'd3', false) + expect(await title(server, '/docs')).toBe('Docs at d3') + }) +}) + +describe('live content, with one function for the sources of a repository', async () => { + const LIVE_CACHE_DIR = tmpDir() + buildEnv({ LIVE_FORM: 'shared', LIVE_CACHE_DIR }) + await setup({ rootDir: liveFixtureDir, server: false }) + const start = useLiveServers({ LIVE_FORM: 'shared' }) + + it('leaves the commits to serve to the servers: the build stores none', { timeout: 20_000 }, async () => { + const server = await start({ LIVE_CACHE_DIR, LIVE_DOCS_HEAD: 'd3' }) + expect(await title(server, '/docs')).toBe('Docs at d3') + }) + + it('pins every source to the commit of the function, and reports each of them', { timeout: 20_000 }, async () => { + const server = await start() + expect(await title(server, '/docs')).toBe('Docs at d1') + await forge(server, 'reset') + expect(await push(server, 'acme/docs', 'd3')).toEqual({ + docs_en: { from: 'd1', to: 'd3', changed: ['/docs', '/docs/new'], removed: ['/docs/old'], navigation: true }, + docs_fr: { from: 'd1', to: 'd3', changed: [], removed: [], navigation: false }, + }) + expect((await forge(server)).asked.filter(request => request.startsWith('head '))).toEqual(['head acme/docs']) + expect(JSON.stringify(await json(server, '/__nuxt_content/get/fr'))).toContain('Docs en français') + }) +}) + +describe('live content, built while a `live.ref` function fails', async () => { + buildEnv({ LIVE_DOWN: 'acme/site' }) + await setup({ rootDir: liveFixtureDir, server: false }) + const start = useLiveServers({ LIVE_DOWN: '' }) + + it('ships no snapshot for that source, which a cold start reads from the forge', { timeout: 20_000 }, async () => { + const server = await start() + expect(await title(server, '/')).toBe('Home at s1') + expect(await title(server, '/docs')).toBe('Docs at d1') + expect((await forge(server)).asked.filter(request => /^(?:tree|file) /.test(request)).sort()).toEqual([ + 'file acme/site@s1:content/about.md', + 'file acme/site@s1:content/index.md', + 'tree acme/site@s1', + ]) + }) +}) diff --git a/test/live-setup.test.ts b/test/live-setup.test.ts new file mode 100644 index 000000000..92e9d1742 --- /dev/null +++ b/test/live-setup.test.ts @@ -0,0 +1,30 @@ +import { fileURLToPath } from 'node:url' +import { afterEach, describe, it, expect } from 'vitest' +import { loadNuxt } from '@nuxt/kit' + +const rootDir = fileURLToPath(new URL('./fixtures/live', import.meta.url)) + +describe('setup of a live content', () => { + afterEach(() => { + delete process.env.LIVE_FORM + }) + + it('fails in hybrid mode: the browser would read the snapshot written at build', async () => { + await expect(loadNuxt({ cwd: rootDir, overrides: { content: { mode: 'hybrid' } } })).rejects.toThrow(/`live`.*`content\.mode: 'server-only'`/) + }) + + it('fails with `app/content.ts`: its browser instance would read the snapshot written at build', async () => { + const layer = fileURLToPath(new URL('./fixtures/app-content/base-layer', import.meta.url)) + await expect(loadNuxt({ cwd: rootDir, overrides: { extends: [layer] } })).rejects.toThrow(/`live`.*`app\/content\.ts`/) + }) + + it('fails with a source that can\'t be pinned to a commit', async () => { + process.env.LIVE_FORM = 'unpinnable' + await expect(loadNuxt({ cwd: rootDir })).rejects.toThrow(/`live`.*pinned to a commit.*`site`/) + }) + + it('fails when a source has no `live.ref` function', async () => { + process.env.LIVE_FORM = 'missing' + await expect(loadNuxt({ cwd: rootDir })).rejects.toThrow(/`live\.ref`.*`site`/) + }) +}) diff --git a/test/live.test.ts b/test/live.test.ts new file mode 100644 index 000000000..b1df3d56d --- /dev/null +++ b/test/live.test.ts @@ -0,0 +1,186 @@ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, it, expect } from 'vitest' +import { setup, useTestContext } from '@nuxt/test-utils/e2e' +import { forge, json, liveFixtureDir, push, title, tmpDir, useLiveServers } from './fixtures/live-fixture' + +describe('live content, with a source per repository', async () => { + await setup({ + rootDir: liveFixtureDir, + server: false, + }) + const start = useLiveServers() + + it('serves each source at the commit its `live.ref` function returns', { timeout: 20_000 }, async () => { + const server = await start() + expect(await title(server, '/')).toBe('Home at s1') + expect(await title(server, '/docs')).toBe('Docs at d1') + }) + + it('moves a pushed source to its new commit, and reports what changed in it', { timeout: 20_000 }, async () => { + const server = await start() + expect(await title(server, '/docs')).toBe('Docs at d1') + await forge(server, 'reset') + // `d3` changes the docs home, adds a page and deletes one. + expect(await push(server, 'acme/docs', 'd3')).toEqual({ + docs: { from: 'd1', to: 'd3', changed: ['/docs', '/docs/new'], removed: ['/docs/old'], navigation: true }, + }) + expect(await title(server, '/docs')).toBe('Docs at d3') + expect(await title(server, '/')).toBe('Home at s1') + expect((await forge(server)).asked.filter(request => request.includes('acme/site'))).toEqual(['head acme/site']) + + // `d4` changes one paragraph of the guide. + expect(await push(server, 'acme/docs', 'd4')).toEqual({ + docs: { from: 'd3', to: 'd4', changed: ['/docs/guide'], removed: [], navigation: false }, + }) + }) + + it('leaves a source at its commit when a push changes none of its files', { timeout: 20_000 }, async () => { + const server = await start() + expect(await title(server, '/docs')).toBe('Docs at d1') + await forge(server, 'reset') + // `c2` only changes the README. + expect(await push(server, 'acme/docs', 'c2')).toEqual({}) + expect((await forge(server)).asked.sort()).toEqual(['commits acme/docs:docs', 'head acme/site']) + }) + + it('fails `lastCommit()` when no commit touches its path', { timeout: 20_000 }, async () => { + const server = await start({ LIVE_LAST_COMMIT_PATH: 'nowhere' }) + await expect(push(server, 'acme/docs', 'd3')).rejects.toThrow(/`docs` failed: lastCommit: no commit touches `nowhere` on `main` of `acme\/docs`/) + }) + + it('reports every document as changed for a source with no stored commit', { timeout: 20_000 }, async () => { + const server = await start() + expect(await push(server, 'acme/site', 's2')).toEqual({ + site: { from: null, to: 's2', changed: ['/', '/about'], removed: [], navigation: true }, + docs: { from: null, to: 'd1', changed: ['/docs', '/docs/guide', '/docs/old'], removed: [], navigation: true }, + }) + }) + + it('moves the sources whose function answered when another fails in `revalidateContent()`, which then throws', { timeout: 20_000 }, async () => { + const server = await start() + expect(await title(server, '/')).toBe('Home at s1') + await push(server, 'acme/site', 's2', false) + await forge(server, 'down=acme/site') + await expect(push(server, 'acme/docs', 'd3')).rejects.toThrow(/500 .*`site`/) + expect(await title(server, '/docs')).toBe('Docs at d3') + expect(await title(server, '/')).toBe('Home at s1') + }) + + it('serves the stored commits for `live.maxAge`, then asks the functions again', { timeout: 20_000 }, async () => { + const server = await start({ LIVE_MAX_AGE: '1' }) + expect(await title(server, '/docs')).toBe('Docs at d1') + // Push without a webhook. + await push(server, 'acme/docs', 'd3', false) + await forge(server, 'reset') + expect(await title(server, '/docs')).toBe('Docs at d1') + expect((await forge(server)).asked).toEqual([]) + + await new Promise(resolve => setTimeout(resolve, 1100)) + expect(await title(server, '/docs')).toBe('Docs at d3') + }) + + it('keeps a source at its stored commit when its function fails on a request, while the others move', { timeout: 20_000 }, async () => { + const server = await start({ LIVE_MAX_AGE: '1' }) + await push(server, 'acme/site', 's2') + await push(server, 'acme/site', 's3', false) + await push(server, 'acme/docs', 'd3', false) + await forge(server, 'down=acme/site') + + await new Promise(resolve => setTimeout(resolve, 1100)) + expect(await title(server, '/docs')).toBe('Docs at d3') + expect(await title(server, '/')).toBe('Home at s2') + + await forge(server, 'down=') + await new Promise(resolve => setTimeout(resolve, 1100)) + expect(await title(server, '/')).toBe('Home at s3') + }) + + it('serves a cold start from the build snapshot, at its commit, when the forge is down', { timeout: 20_000 }, async () => { + const server = await start({ LIVE_FORGE: 'offline' }) + expect(await title(server, '/')).toBe('Home at s1') + expect(await title(server, '/docs')).toBe('Docs at d1') + expect(JSON.stringify(await json(server, '/__nuxt_content/get/docs/guide'))).toContain('Read it first.') + expect((await forge(server)).asked.filter(request => /^(?:tree|file) /.test(request))).toEqual([]) + }) + + it('serves on every server the commits one of them stored in the shared cache driver', { timeout: 20_000 }, async () => { + const LIVE_CACHE_DIR = tmpDir() + const first = await start({ LIVE_CACHE_DIR }) + const second = await start({ LIVE_CACHE_DIR }) + expect(await title(first, '/docs')).toBe('Docs at d1') + expect(await title(second, '/docs')).toBe('Docs at d1') + expect((await forge(second)).asked).toEqual([]) + + await push(first, 'acme/docs', 'd3') + expect(await title(second, '/docs')).toBe('Docs at d3') + expect((await forge(second)).asked.filter(request => /^(?:head|commits) /.test(request))).toEqual([]) + }) + + it('reads only the files that changed since the build on a cold start at a newer commit', { timeout: 20_000 }, async () => { + const server = await start() + await push(server, 'acme/docs', 'd3', false) + expect(await title(server, '/docs')).toBe('Docs at d3') + expect(JSON.stringify(await json(server, '/__nuxt_content/get/docs/guide'))).toContain('Read it first.') + expect((await forge(server)).asked.filter(request => request.startsWith('file acme/docs')).sort()).toEqual([ + 'file acme/docs@d3:docs/index.md', + 'file acme/docs@d3:docs/new.md', + ]) + }) + + it('calls the functions once for the requests that arrive while they run', { timeout: 20_000 }, async () => { + const server = await start() + await forge(server, 'slow=300') + expect(await Promise.all([title(server, '/'), title(server, '/docs'), title(server, '/')])).toEqual(['Home at s1', 'Docs at d1', 'Home at s1']) + expect((await forge(server)).asked.filter(request => request.startsWith('head '))).toEqual(['head acme/site']) + }) + + it('keeps the content of the current and the previous commit of a source, and releases older ones', { timeout: 20_000 }, async () => { + const server = await start() + const served = () => json>(server, '/api/served') + await served() + for (const head of ['d3', 'd4']) { + await push(server, 'acme/docs', head) + await served() + } + const kept = (ref: string) => expect.objectContaining({ ref, status: expect.not.stringMatching('disposed') }) + await expect.poll(served).toEqual({ + docs: [{ ref: 'd1', status: 'disposed' }, kept('d3'), kept('d4')], + site: [kept('s1')], + }) + }) + + it('doesn\'t go back to the commit a call that started before a push returns after it', { timeout: 20_000 }, async () => { + const server = await start() + // Starts before the push and gets `s1` 400ms later. + await forge(server, 'slow=400') + const inFlight = title(server, '/') + await new Promise(resolve => setTimeout(resolve, 100)) + await forge(server, 'slow=0') + await push(server, 'acme/site', 's2') + expect(await title(server, '/')).toBe('Home at s2') + await inFlight + expect(await title(server, '/')).toBe('Home at s2') + }) + + it('renders a page pushed after the build with the components it uses', { timeout: 20_000 }, async () => { + const server = await start() + await push(server, 'acme/docs', 'd3') + const html = await fetch(`${server.url}/docs/new`).then(response => response.text()) + expect(html).toMatch(/
]*>.*Only since d3\./s) + }) + + it('generates the types from the declared schemas, without asking the forge', () => { + const types = readFileSync(join(useTestContext().nuxt!.options.buildDir, 'content/types.d.ts'), 'utf8') + expect(types).toMatch(/interface DocsData \{[^}]*badge\?: string/) + const copies = (globalThis as { __liveModuleForge?: { asked: string[] }[] }).__liveModuleForge! + expect(copies.length).toBeGreaterThan(0) + expect(copies.flatMap(copy => copy.asked)).toEqual([]) + }) + + it('publishes no static snapshot', () => { + const outputDir = useTestContext().nuxt!.options.nitro.output!.dir! + expect(existsSync(join(outputDir, 'static'))).toBe(true) + expect(existsSync(join(outputDir, 'static/__nuxt_content'))).toBe(false) + }) +})