Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/hybrid-v4-pure/server/content.ts
Original file line number Diff line number Diff line change
@@ -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({
Expand Down
10 changes: 7 additions & 3 deletions migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |

## `<ContentRenderer>` is now `<ContentDocument>`

Expand All @@ -45,7 +45,7 @@ Compared to v3's `<ContentRenderer>`:

```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'

Expand All @@ -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.
Expand Down Expand Up @@ -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'

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
55 changes: 43 additions & 12 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -86,7 +86,8 @@ export default defineNuxtModule<ModuleOptions>({

// 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')
Expand All @@ -112,11 +113,19 @@ export default defineNuxtModule<ModuleOptions>({
/**
* 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' : '')) } })

/**
Expand Down Expand Up @@ -218,7 +227,7 @@ export default defineNuxtModule<ModuleOptions>({
/**
* Types
*/
setupTypes(content, nuxt, contentCollections, readContent, options.compatibilityVersion === 3)
setupTypes(content, nuxt, contentCollections, readContent, options.compatibilityVersion === 3, live)

/**
* Media, skipped in prepare
Expand Down Expand Up @@ -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 })

Expand All @@ -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,
)
}
Expand Down Expand Up @@ -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<string> {
async function generateContentTypes(content: ContentSurface, collections: ResolvedContentCollections, readContent: ContentReader | undefined, v3: boolean, live: boolean): Promise<string> {
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 {
Expand Down Expand Up @@ -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<ContentSurface | undefined> {
// 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, {
Expand All @@ -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),
Expand All @@ -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!)
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/client-content/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
59 changes: 59 additions & 0 deletions src/runtime/server/commits.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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 }
}
19 changes: 16 additions & 3 deletions src/runtime/server/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any>`: a hub over a mutable instance array isn't assignable to the
Expand All @@ -27,6 +31,8 @@ interface NuxtContentOptions extends Omit<ContentOptions, 'source' | 'plugins'>
* @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) {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, ContentSource> }): ContentHub<any>
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.
Expand All @@ -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
}
7 changes: 6 additions & 1 deletion src/runtime/server/internal/api.ts
Original file line number Diff line number Diff line change
@@ -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)
})
Loading
Loading