diff --git a/app/composables/useDocsContent.ts b/app/composables/useDocsContent.ts index c33bb58..f3f8a60 100644 --- a/app/composables/useDocsContent.ts +++ b/app/composables/useDocsContent.ts @@ -1,13 +1,9 @@ -import { createContentClient } from 'comark-content/client' +import { createContentClient, type ContentClient } from 'comark-content/client' import type { ActiveContent, ContentMode } from '../types/content' import { withLeadingSlash } from 'ufo' -export const prodContent = createContentClient({ - basePath: '/api/content', - fetch: $fetch, -}) - -const clients = new Map() +// Production reads Nuxt Content's own client, on `/__nuxt_content`. Previews have one client each. +const clients = new Map>() function getClient(basePath: string) { let client = clients.get(basePath) @@ -54,7 +50,7 @@ export function useDocsContent(): ComputedRef { ref, routeBase, path, - client: mode === 'prod' ? prodContent : getClient(apiBase), + client: mode === 'prod' ? content : getClient(apiBase), apiBase } }) diff --git a/app/composables/useSearch.ts b/app/composables/useSearch.ts index a0f0d27..881c056 100644 --- a/app/composables/useSearch.ts +++ b/app/composables/useSearch.ts @@ -1,92 +1,39 @@ import type { SearchOptions, SearchResult } from 'comark-content' -type SearchStatus = 'idle' | 'loading' | 'ready' | 'error' - -const status = ref('idle') - -/** - * Hydration logging switch: `?debug=search` - */ -function searchDebug(): boolean { - if (!import.meta.client) return false - return new URLSearchParams(location.search).get('debug') === 'search' -} - /** - * Client-side full-text search over the active route's content (sqlite-wasm FTS5) - * Hydrated from the per-commit snapshot artifacts. + * Full-text search over the active route's content, in Nuxt Content's worker (sqlite-wasm FTS5). + * Loaded from the per-commit snapshot of the commit the route serves. */ export function useSearch() { const content = useDocsContent() const sha = inject>('sha', ref(null)) - /** What to hydrate from, or `null` when this route has nothing searchable (yet). */ - const target = computed(() => { - const isPreview = content.value.mode !== 'prod' - if (sha.value) return { - sha: sha.value, - isPreview, - apiBase: `/api/content/blob/${sha.value}` - } - - // Prod in dev mode - if (!isPreview && import.meta.dev) return { - sha: null, - isPreview, - apiBase: '/api/content' - } - - return null - }) - - /** - * Load the database for the current target. - * No-ops if the target is unchanged. - */ - async function warmup(): Promise { - // Not resolved yet — the `watch` below re-runs this once `sha` lands. - if (sha.value === undefined) return - - const current = target.value - - if (!current) { - if (content.value.mode === 'prod' && !import.meta.dev) { - console.error('[search] prod route resolved no commit pin — search hidden') - } - return - } + // The URL never changes for a commit, so the CDN keeps it. A new commit starts a new worker. + const worker = useNuxtContentWorker({ basePath: () => (sha.value ? `/api/content/blob/${sha.value}` : undefined) }) - status.value = 'loading' - try { - const debug = searchDebug() - if (debug) console.info(`[search] warmup from ${current.apiBase} (sha ${current.sha ?? 'unpinned'})`) + // Production in dev has no commit: the worker reads the dev server, which follows the working tree. + const searchable = computed(() => Boolean(sha.value) || (import.meta.dev && content.value.mode === 'prod')) - await warmupSearch({ - apiBase: current.apiBase, - sha: current.sha, - isPreview: current.isPreview, - origin: location.origin, - debug, - }) - status.value = 'ready' - } catch (error) { - status.value = 'error' - console.error('[search] could not load the search database', error) - } + function warmup() { + if (searchable.value) worker.warmup().catch((error) => console.error('[search] could not load the search database', error)) } if (import.meta.client) { onNuxtReady(warmup) - watch(() => target.value && `${target.value.isPreview}:${target.value.sha}`, warmup) + watch(searchable, warmup) } async function search(query: string, opts?: SearchOptions): Promise { - return prefixSearchResults(await searchContent(query, opts), content.value.routeBase) + if (!searchable.value) return [] + return prefixSearchResults( + await worker.search(query, { limit: 25, snippet: { columns: ['content'] }, ...opts }), + content.value.routeBase, + ) } return { search, - status: readonly(status), + status: worker.status, warmup, } } diff --git a/app/content.worker.ts b/app/content.worker.ts new file mode 100644 index 0000000..0f73b7a --- /dev/null +++ b/app/content.worker.ts @@ -0,0 +1,6 @@ +import { createNuxtContentWorker, sqliteFullTextSearch, sqliteWasm } from '@nuxt/content/worker' + +// Only evaluated in the search worker, so sqlite-wasm stays out of the pages' bundle. +export default createNuxtContentWorker({ + plugins: [sqliteFullTextSearch({ database: sqliteWasm() })], +}) diff --git a/app/workers/internal/search-logger.ts b/app/workers/internal/search-logger.ts deleted file mode 100644 index 312f99f..0000000 --- a/app/workers/internal/search-logger.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Logging for the search worker. - * - * Triggered by `?debug=search` param. - */ -import type { ContentFile, Logger, RelationalDatabase } from 'comark-content/runtime' - -const PREFIX = '[search:worker]' - -let debug = false - -/** Called on every `warmup`; once on, it stays on for the life of the worker. */ -export function setDebug(value: boolean): void { - debug = debug || value -} - -export function isDebug(): boolean { - return debug -} - -export function log(...args: unknown[]): void { - if (debug) console.info(PREFIX, ...args) -} - -/** Milliseconds since `from`, for log lines. */ -export function since(from: number): string { - return `${(performance.now() - from).toFixed(1)}ms` -} - -/** - * Warn and error are deliberately ungated: the FTS plugin reports a missing snapshot through this - * channel, and that failure is otherwise indistinguishable from "the query matched nothing". - */ -export const logger: Logger = { - debug: (tag, ...args) => log(`${tag}:`, ...args), - info: (tag, ...args) => log(`${tag}:`, ...args), - warn: (tag, ...args) => console.warn(`${PREFIX} ${tag}:`, ...args), - error: (tag, ...args) => console.error(`${PREFIX} ${tag}:`, ...args), -} - -export function describeArtifact(decoded: unknown): string { - const raw = Array.isArray(decoded) ? decoded : (decoded as { items?: unknown } | null)?.items - if (Array.isArray(raw)) { - const items = raw as ContentFile[] - const documents = items.filter((item) => item.meta.kind === 'document') - const withNodes = documents.filter((item) => item.nodes?.length) - return `${items.length} item(s), ${documents.length} document(s), ${withNodes.length} with nodes` - } - return `${raw ? Object.keys(raw as Record).length : 0} manifest item(s)` -} - -/** - * Mirrors the FTS plugin's `ownId` convention - */ -function sourceIdFor(content: { name: string, key: string }): string { - return content.key ? `${content.name}@${content.key}` : content.name -} - -export async function indexedRows(database: RelationalDatabase, content: { name: string, key: string }): Promise { - try { - const rows = await database.all<{ n: number }>('SELECT count(*) as n FROM __fts_search WHERE source = ?', [sourceIdFor(content)]) - return rows?.[0]?.n ?? 'unknown' - } catch (error) { - return `unknown (${error instanceof Error ? error.message : String(error)})` - } -} diff --git a/app/workers/search.ts b/app/workers/search.ts deleted file mode 100644 index 6508475..0000000 --- a/app/workers/search.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Search worker: owns the browser-standalone `comark-content` instance (sqlite-wasm FTS5). - * - * Hydrated from the per-commit snapshot artifacts, every mode's (prod, blob, tree, pr) served from - * its own SHA-pinned `/api/content/blob/` URL. - * - * Instances are cached by SHA: - * - Prod is always kept - * - One preview only is kept, evicted on the next switch - */ -import { comarkContent, DEFAULT_CONTENT_NAME, readArtifact } from 'comark-content/runtime' -import sqliteWasm from 'comark-content/database/sqlite-wasm' -import snapshot from 'comark-content/sources/snapshot' -import sqliteFullTextSearch from 'comark-content/plugins/sqlite-full-text-search' -import { ofetch } from 'ofetch' -import { describeArtifact, indexedRows, isDebug, log, logger, setDebug, since } from './internal/search-logger' -import type { CacheArtifact, SearchOptions, SearchResult } from 'comark-content/runtime' - -export interface SearchTarget { - apiBase: string - sha: string | null - isPreview: boolean - origin: string - debug: boolean -} - -// Shared database for the worker's lifetime -const database = sqliteWasm() - -function createInstance(fetchArtifact: (path: string) => Promise, apiBase: string, sha: string | null) { - const content = comarkContent({ - source: snapshot( - () => fetchArtifact(`${apiBase}/snapshot/${DEFAULT_CONTENT_NAME}.json`), - () => fetchArtifact(`${apiBase}/manifest.json`) - ), - plugins: [sqliteFullTextSearch({ database })], - logger, - }) - - return sha ? content.withRef(sha) : content -} - -type SearchInstance = ReturnType - -/** Whichever instance `searchContent()` should query */ -let active: SearchInstance | undefined - -/** Hydrated instances by key */ -const loaded = new Map() -/** In-flight hydrations, so concurrent warmups for one commit share a single load. */ -const pending = new Map>() - -/** Needed to avoid evicting prod */ -let prodKey: string | undefined -/** Most recently requested key (for eviction) */ -let currentKey = '' - -function hydrate(target: SearchTarget): Promise { - const key = target.sha ?? 'unpinned' // dev mode only - const existing = loaded.get(key) - if (existing) return Promise.resolve(existing) - - let promise = pending.get(key) - if (!promise) { - promise = loadInstance(target) - .then((instance) => { - loaded.set(key, instance) - return instance - }) - // Cleared on failure too, so the next warmup retries instead of re-awaiting this rejection. - .finally(() => pending.delete(key)) - pending.set(key, promise) - } - return promise -} - -/** - * Loads (or reuses) the database for `target`, makes it active, and evicts whatever else is - * cached — keeping prod warm and dropping any preview once navigated away from it. - */ -export async function warmupSearch(target: SearchTarget): Promise { - setDebug(target.debug) - const key = target.sha ?? 'unpinned' - currentKey = key - // Claim prod's key before awaiting, so the eviction below can never clean it. - if (!target.isPreview) prodKey = key - - const instance = await hydrate(target) - if (currentKey !== key) return // a switch occurred, so skip the eviction - - active = instance - for (const [staleKey, stale] of loaded) { - if (staleKey === key || staleKey === prodKey) continue - loaded.delete(staleKey) - void stale.clean().catch((error) => log(`cleanup failed for ${staleKey}`, error)) - } -} - -async function loadInstance(target: SearchTarget): Promise { - const started = performance.now() - try { - const fetchArtifact = async (path: string): Promise => { - const url = new URL(path, target.origin).href - const fetchStarted = performance.now() - try { - const artifact = await ofetch(url) - if (isDebug()) { - let contents: string - try { - contents = describeArtifact(await readArtifact(artifact)) - } catch (error) { - contents = `undecodable: ${error instanceof Error ? error.message : String(error)}` - } - log(`fetched ${path} in ${since(fetchStarted)} — ${artifact?.size ?? 0} bytes, ${contents}`) - } - return artifact - } catch (error) { - log(`failed ${path} after ${since(fetchStarted)}`, error) - throw error - } - } - - const content = createInstance(fetchArtifact, target.apiBase, target.sha) - await content.init() - - const indexStarted = performance.now() - await content.search('') // pulls the snapshot in and builds the FTS index - const rows = await indexedRows(database, content) - log(`index built in ${since(indexStarted)} for ${target.apiBase} — ${rows} row(s)`) - - log(`ready in ${since(started)} (${target.isPreview ? 'preview' : 'prod'} ${target.sha ?? 'unpinned'})`) - return content - } catch (error) { - log(`hydration failed after ${since(started)} for ${target.apiBase}`, error) - throw error - } -} - -/** Empty until hydration lands. */ -export async function searchContent(query: string, opts?: SearchOptions): Promise { - if (!active) { - log(`dropped query "${query}" — no instance yet`) - return [] - } - const queryStarted = performance.now() - const results = await active.search(query, { - limit: 25, - snippet: { columns: ['content'] }, - ...opts, - }) - log(`query "${query}" -> ${results.length} result(s) in ${since(queryStarted)}`) - return results -} diff --git a/docs/cold-page-request.md b/docs/cold-page-request.md index e905e85..9aca0f8 100644 --- a/docs/cold-page-request.md +++ b/docs/cold-page-request.md @@ -7,77 +7,57 @@ sequenceDiagram participant Browser participant Edge as Edge ISR participant SSR as Lambda SSR - participant ContentRoute as /api/content/** - participant Config as Vercel Global Config - participant Refs as Shared ref cache (content:refs:v2) + participant ContentRoute as /__nuxt_content/** + participant Cache as Runtime Cache (content:) participant GH as GitHub - participant Content as shared content + participant Content as live content Browser->>Edge: GET /docs/foo Edge-->>SSR: cache miss → render SSR->>ContentRoute: $fetch (navigation) - ContentRoute->>Content: getProdContent() - Content->>Config: read contentSha (when connected) - alt pin set - Config-->>Content: pinned content sha - else no pin or read failed - Config-->>Content: undefined - Content->>Refs: resolveContentSha(targetBranch, contentDir) - alt cache hit (within 1h fallback TTL) - Refs-->>Content: cached content sha - else cache miss - Refs->>GH: commits?sha=&path= - GH-->>Refs: latest content sha - Refs-->>Content: content sha - end + ContentRoute->>Content: resolveContent(content) + Content->>Cache: read the stored commit + alt stored within maxAge (1h on production, 10 min elsewhere) + Cache-->>Content: content sha + else missing or older + Content->>GH: commits?sha=&path= (lastCommit) + GH-->>Content: latest content sha + Content->>Cache: store it end - Content->>Content: rebuild if content sha advanced - Content->>GH: init partial (~36 files, at ) + Content->>Content: pin to the content sha, if it moved + Content->>GH: list the tree at , read only files the build snapshot lacks ContentRoute-->>SSR: nav tree SSR->>ContentRoute: $fetch (page) - ContentRoute->>Content: getProdContent() (recheck pin; same sha → no rebuild) - Content->>GH: fetch + parse 1 page (at ) + ContentRoute->>Content: resolveContent(content) (same sha → same instance) + Content->>GH: fetch + parse 1 page (at ), unless cached ContentRoute-->>SSR: parsed page SSR-->>Edge: HTML Edge-->>Browser: HTML (cached for next visitor) ``` -**Cost:** with a Global Config pin, a config lookup selects the content SHA. Without a pin, a -shared-cache lookup selects the latest commit touching the content directory. The instance builds -its index from GitHub once per content revision, then parses one page. All reads are pinned to the -immutable ``. Without a Global Config pin, code-only commits do not rebuild the content -instance. +**Cost:** the stored commit is read from the Runtime Cache, so every server serves the same one. GitHub is asked +for the commit only when it is missing or older than `maxAge`. The build snapshot, stamped with the commit the +build resolved, supplies every body whose source hash didn't change. All reads are pinned to the immutable +``, and code-only commits don't move it. -The production branch pointer is shared across *instances* with a one-hour fallback TTL. The push -webhook refreshes it before purging ISR, so normal cold starts don't need to resolve the branch -through GitHub. If a webhook delivery or refresh fails, a request resolves the branch again after -the fallback TTL instead of serving the old SHA indefinitely. +Nuxt Content owns this path (`live` in `server/content.ts`). The layer only passes the cache driver, the +`lastCommit()` function and `maxAge`. -Vercel's Runtime Cache is regional (see the note on `refCacheDriver()` in -`server/utils/cache.ts`). This project runs in one region, so the webhook refresh reaches every -instance's shared cache. Additional regions would self-heal when their fallback TTL expires. +Vercel's Runtime Cache is regional (see the note on `refCacheDriver()` in `server/utils/cache.ts`), and every +preview deployment shares one cache. This project runs in one region, so the webhook reaches every server. +Additional regions would follow within `maxAge`. -Preview deployments, `/tree/:branch`, `/pr/:number`, and preview authorization decisions use a -600-second TTL because production webhooks don't update them. Negative ref lookups use the same TTL, -including for the production branch, so a temporary GitHub 404 cannot remain cached indefinitely. +`/tree/:branch`, `/pr/:number`, and preview authorization decisions use their own pointers in the ref cache, +with a 600-second TTL. A ref that doesn't resolve is cached too, for 600 seconds, but **only** when the caller +asks for it (`resolveContentSha(ref, contentDir, { cacheMisses: true })`). The public `/tree/:branch` route +does, so a nonexistent branch can't be replayed into one GitHub API call per request. -A ref that doesn't resolve is cached too, for 600 seconds, but **only** when the -caller asks for it (`resolveContentSha(ref, contentDir, { cacheMisses: true })`) — the public -`/tree/:branch` route does, so a nonexistent branch can't be replayed into one -GitHub API call per request. The production branch above deliberately does not: -GitHub answers 404 when a token loses access to a private repo, and caching that -would turn an expired token into a site-wide outage for the window rather than one -failed request. - -**On a content push**, `server/api/revalidate.post.ts` forces a fresh `resolveContentSha()` lookup, -which writes the latest branch content SHA into the same shared ref cache before fanning out ISR -purges for the affected pages. Without a Global Config pin, a freshly-purged page's next render sees -the new SHA. With a pin, the next render stays on the pinned SHA, while the refreshed branch pointer -is ready if the pin is removed. If the webhook fails, the production pointer refreshes within one -hour. +**On a content push**, `server/api/revalidate.post.ts` calls `revalidateContent(content)`. It asks GitHub for +the last content commit, stores it, and returns the pages that changed. The webhook then purges those pages, and +every page when the navigation changed. If the webhook fails, production follows within one hour. Parsed manifests and bodies live under a parser-version + content-SHA namespace. Vercel Runtime Cache persists across deployments within an environment, so unrelated deployments can reuse @@ -87,7 +67,7 @@ relevant parser dependencies, or cached derived data changes. **Client-side navigation** fetches `_payload.json` alongside the page, and Vercel's ISR default (`max-age=0, must-revalidate`) means the browser revalidates it on every navigation rather than trusting a stale copy for minutes — the webhook purge above takes effect immediately there too. -For prod pages, `server/middleware/payload-etag.ts` sets a weak `etag` from `resolveProdSha()`, +For prod pages, `server/middleware/payload-etag.ts` sets a weak `etag` from the commit `resolveContent()` serves, so revalidation is a cheap conditional request answered `304` from the edge's ISR entry, not a full re-download. Preview payloads (`/tree/**`, `/blob/**`, `/pr/**`) skip this — they render from their own pinned instance rather than the prod head, and they're low-traffic and `noindex`, so a diff --git a/modules/config/index.ts b/modules/config/index.ts index 6dcab67..07a3a4b 100644 --- a/modules/config/index.ts +++ b/modules/config/index.ts @@ -3,6 +3,7 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs' import { addServerPlugin, createResolver, defineNuxtModule, resolvePath, useLogger } from '@nuxt/kit' import { defu } from 'defu' import type { ModuleOptions as AgentDiscoveryOptions } from 'nuxt-agent-discovery' +import type { BuildContent } from '../../shared/types/build-content' import { getGitBranch, getGitEnv, getGitRoot, getLocalGitInfo } from '../../utils/git' import { getPackageJsonMetadata, inferSiteURL, resolveContentDir } from './utils' @@ -223,7 +224,7 @@ export default defineNuxtModule({ const { resolve } = createResolver(import.meta.url) addServerPlugin(resolve('./runtime/server/plugins/llms')) - // The runtime parser imports the highlighter through this alias, and the snapshot module loads the same file. + // The content parser imports the highlighter through this alias. const highlighter = options.highlighter ? await resolvePath(options.highlighter, { cwd: rootDir }) : resolve('../../utils/highlighter.ts') @@ -234,6 +235,18 @@ export default defineNuxtModule({ ? createHash('sha256').update(readFileSync(highlighter)).digest('hex').slice(0, 8) : '' + // Read by `server/content.ts`, which also runs at build outside Nitro: here, and in the server through `nitro.replace`. + const { docs } = nuxt.options.runtimeConfig + process.env.COMARK_DOCS_CONTENT = JSON.stringify({ + ...docs.github, + contentDir: docs.contentDir, + contentPath: docs.contentPath, + highlighterVersion: docs.highlighterVersion, + } satisfies BuildContent) + nuxt.options.nitro.replace = defu(nuxt.options.nitro.replace, { + 'process.env.COMARK_DOCS_CONTENT': JSON.stringify(process.env.COMARK_DOCS_CONTENT), + }) + // ISR rules here (not `$production`) so they merge cleanly across npm layers; content sections need a redeploy. if (!nuxt.options.dev && options.isr !== false) { const isr = options.isr! diff --git a/modules/config/runtime/server/plugins/llms.ts b/modules/config/runtime/server/plugins/llms.ts index 80596c7..5b8a3cc 100644 --- a/modules/config/runtime/server/plugins/llms.ts +++ b/modules/config/runtime/server/plugins/llms.ts @@ -2,6 +2,7 @@ import type { NavigationItem } from 'comark-content' import type { NitroApp } from 'nitropack/types' import type { LLMsSection } from 'nuxt-llms' import { useAppConfig } from 'nitropack/runtime' +import { content } from '../../../../../server/content' /** * Builds `llms.txt` from the content navigation: one section per top-level directory, in sidebar @@ -22,8 +23,7 @@ export default defineNitroPlugin((nitroApp: NitroApp) => { // A consumer declaring `llms.sections` with `navigation` selectors owns the sections; the bridge // resolves those. Otherwise the intro goes ahead of the "Documentation Sets" entry nuxt-llms seeds. if (!options.sections.some((section) => 'navigation' in section)) { - const content = await getProdContent() - const navigation = await content.navigation() + const navigation = await (await resolveContent(content)).navigation() options.sections.unshift(documentationSection(navigation, siteName)) options.sections.push(...navigationSections(navigation)) } diff --git a/modules/snapshot/index.ts b/modules/snapshot/index.ts deleted file mode 100644 index 334cfcb..0000000 --- a/modules/snapshot/index.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { mkdir, stat } from 'node:fs/promises' -import type { ComarkPlugin } from 'comark' -import { defineNuxtModule, useLogger } from '@nuxt/kit' -import { DEFAULT_CONTENT_NAME } from 'comark-content' -import { writeSnapshots } from 'comark-content/build' -import fs from 'comark-content/sources/fs' -import { createJiti } from 'jiti' -import { join } from 'pathe' -import { createBuildContentInstance } from '../../utils/factory' -import { resolveSnapshotSha } from './utils' - -const logger = useLogger('comark-docs') - -/** Where the snapshot lives in the build, and the server-asset namespace it is read back through. */ -const ASSET_BASE = 'comark-content' - -/** - * Writes a build-time snapshot into the function bundle stamped with the commit it was parsed at. - * A cold start at that commit hydrates from it instead of walking the content repository. - * At a later commit it still supplies every unchanged body. - */ -export default defineNuxtModule({ - meta: { name: 'comark-docs:snapshot' }, - setup(_options, nuxt) { - // Do not run in dev or prepare. - if (nuxt.options.dev || nuxt.options._prepare) return - - const dir = join(nuxt.options.buildDir, ASSET_BASE) - - nuxt.hook('modules:done', async () => { - await mkdir(dir, { recursive: true }) - nuxt.options.nitro.serverAssets = [ - ...(nuxt.options.nitro.serverAssets ?? []), - { baseName: ASSET_BASE, dir }, - ] - }) - - nuxt.hook('build:before', async () => { - const { docs } = nuxt.options.runtimeConfig - const { repoRoot, contentDir, contentPath, github } = docs - - const resolveStart = performance.now() - const sha = await resolveSnapshotSha({ - repoRoot, - contentDir, - repo: `${github.owner}/${github.repo}`, - token: docs.githubToken || process.env.NUXT_DOCS_GITHUB_TOKEN || process.env.GITHUB_TOKEN, - warn: (message) => logger.warn(message), - }) - const resolveMs = Math.round(performance.now() - resolveStart) - if (!sha) { - logger.warn( - 'No commit in this checkout could be confirmed to hold the content being built, ' + - 'so no snapshot is shipped: cold starts will walk the content repository.' - ) - return - } - - try { - // The highlighter the runtime parser imports through `#comark-docs/highlighter`, loaded with Nuxt's - // aliases like the bundle resolves it. jiti also transpiles the layer's own `.ts` in node_modules. - const highlighter = await createJiti(import.meta.url, { alias: nuxt.options.alias }).import( - nuxt.options.alias['#comark-docs/highlighter']!, - { default: true }, - ) - // `withRef` stamps the artifact with the commit. - // At runtime, even with a different commit, we can reuse unchanged bodies. - const content = createBuildContentInstance({ source: fs(contentPath) }, highlighter).withRef(sha) - - const writeStart = performance.now() - await writeSnapshots(content, { dir }) - const writeMs = Math.round(performance.now() - writeStart) - - // Size is the number to watch: the snapshot is inlined into the bundle as a string. - // Every cold start that reads it pays for that. - const { size } = await stat(join(dir, DEFAULT_CONTENT_NAME, 'snapshot.json')) - logger.success( - `Content snapshot ${sha.slice(0, 7)}: ${Math.round(size / 1024)} kB parsed and written in ${writeMs}ms ` + - `(ref resolved in ${resolveMs}ms)` - ) - } catch (error) { - logger.warn('Could not write the content snapshot — cold starts will walk the content repository.', error) - } - }) - }, -}) diff --git a/modules/snapshot/test/snapshot.test.ts b/modules/snapshot/test/snapshot.test.ts deleted file mode 100644 index 65cd868..0000000 --- a/modules/snapshot/test/snapshot.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { resolveSnapshotSha } from '../utils' - -const SHA = (char: string) => char.repeat(40) - -describe('resolveSnapshotSha', () => { - let repo: string - let contentCommit: string - let head: string - - const run = (...args: string[]) => - execFileSync('git', args, { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() - - const write = async (file: string, body: string) => { - await mkdir(dirname(join(repo, file)), { recursive: true }) - await writeFile(join(repo, file), body, 'utf8') - } - - /** Answers the commits query with `sha` per requested ref; `null` means 404. */ - function stubApi(bySha: Record) { - return vi.fn(async (url: string | URL) => { - const ref = new URL(String(url)).searchParams.get('sha') ?? '' - const answer = bySha[ref] - if (answer === undefined || answer === null) return new Response('[]', { status: 404 }) - return new Response(JSON.stringify([{ sha: answer }]), { status: 200 }) - }) - } - - beforeEach(async () => { - repo = await mkdtemp(join(tmpdir(), 'comark-snapshot-sha-')) - run('init', '-q', '-b', 'main') - run('config', 'user.email', 'test@example.com') - run('config', 'user.name', 'Test') - - await write('content/index.md', '# one\n') - run('add', '-A') - run('commit', '-qm', 'add content') - contentCommit = run('rev-parse', 'HEAD') - - // A later commit that leaves `content/` alone, so HEAD is not the last content commit. - await write('src/app.ts', 'export const a = 1\n') - run('add', '-A') - run('commit', '-qm', 'add code') - head = run('rev-parse', 'HEAD') - }) - - afterEach(async () => { - await rm(repo, { recursive: true, force: true }) - vi.unstubAllGlobals() - }) - - const input = () => ({ repoRoot: repo, contentDir: 'content', repo: 'owner/name', token: 'tok' }) - - it('walks from the built commit, not the branch', async () => { - // The distinction that keeps a mid-build push (or a redeploy of an older commit) from labelling - // the snapshot with content it does not hold. - const fetchMock = stubApi({ [head]: contentCommit, main: SHA('f') }) - vi.stubGlobal('fetch', fetchMock) - - expect(await resolveSnapshotSha(input())).toBe(contentCommit) - - const requested = new URL(String(fetchMock.mock.calls[0]![0])).searchParams - expect(requested.get('sha')).toBe(head) - expect(requested.get('path')).toBe('content') - expect(requested.get('per_page')).toBe('1') - }) - - it('falls back to a tree-verified git answer when the API fails', async () => { - vi.stubGlobal('fetch', stubApi({})) - - // Full history here, so git finds the true commit and its content tree matches HEAD's. - expect(await resolveSnapshotSha(input())).toBe(contentCommit) - }) - - it('skips the API when no repository is known', async () => { - const fetchMock = stubApi({ [head]: SHA('c') }) - vi.stubGlobal('fetch', fetchMock) - - expect(await resolveSnapshotSha({ ...input(), repo: '' })).toBe(contentCommit) - expect(fetchMock).not.toHaveBeenCalled() - }) - - it('ships nothing when neither the API nor git can name the content', async () => { - vi.stubGlobal('fetch', stubApi({})) - - expect(await resolveSnapshotSha({ ...input(), contentDir: 'nope' })).toBeUndefined() - }) - - it('warns on the git fallback when the answer is a shallow boundary', async () => { - vi.stubGlobal('fetch', stubApi({})) - const warn = vi.fn() - - // A one-commit repo: its only commit is parentless, which is what a depth-1 clone looks like. - const shallow = await mkdtemp(join(tmpdir(), 'comark-shallow-')) - try { - const at = (...args: string[]) => execFileSync('git', args, { cwd: shallow, stdio: 'ignore' }) - at('init', '-q', '-b', 'main') - at('config', 'user.email', 'test@example.com') - at('config', 'user.name', 'Test') - await mkdir(join(shallow, 'content'), { recursive: true }) - await writeFile(join(shallow, 'content/index.md'), '# one\n', 'utf8') - at('add', '-A') - at('commit', '-qm', 'init') - - expect(await resolveSnapshotSha({ ...input(), repoRoot: shallow, warn })).toMatch(/^[0-9a-f]{40}$/) - expect(warn).toHaveBeenCalledOnce() - expect(warn.mock.calls[0]![0]).toContain('shallow clone boundary') - } finally { - await rm(shallow, { recursive: true, force: true }) - } - }) -}) diff --git a/modules/snapshot/utils.ts b/modules/snapshot/utils.ts deleted file mode 100644 index af03c95..0000000 --- a/modules/snapshot/utils.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { getLastCommit, getTreeSha, hasParent, headCommit } from '../../utils/git' -import { fetchLastContentCommit } from '../../utils/github' - -export interface SnapshotShaInput { - /** Repository root of the checkout being built. */ - repoRoot: string - /** Content directory, relative to the repository root. */ - contentDir: string - /** `owner/name` of the content repository. Empty when the checkout has no usable remote. */ - repo: string - /** GitHub token, if the build has one. Without it only the git fallback runs. */ - token?: string - /** Reported to the caller; defaults to `console.warn`. */ - warn?: (message: string) => void -} - -/** {@link fetchLastContentCommit}, but never throwing: a build-time optimization must not fail a build. */ -async function lastContentCommit( - repo: string, - contentDir: string, - ref: string, - token?: string -): Promise { - try { - const sha = await fetchLastContentCommit({ repo, path: contentDir, ref, token }) - // Validated here rather than in the shared query: this one names a directory in the build. - return sha && /^[0-9a-f]{40}$/.test(sha) ? sha : undefined - } catch { - return undefined - } -} - -/** - * The commit whose `contentDir` holds the content being parsed. - * The only ref the snapshot may be stored under. - * The same one `resolveContentSha()` resolves at runtime. - */ -export async function resolveSnapshotSha(input: SnapshotShaInput): Promise { - const { repoRoot, contentDir, repo, token } = input - const warn = input.warn ?? ((message: string) => console.warn(message)) - - const head = headCommit(repoRoot) - const fromApi = head && repo ? await lastContentCommit(repo, contentDir, head, token) : undefined - if (fromApi) return fromApi - - // No API answer: fall back to git, which needs the tree check to be trustworthy. - const parsed = getTreeSha(repoRoot, 'HEAD', contentDir) - const fromGit = getLastCommit(repoRoot, contentDir) - if (!parsed || !fromGit) return undefined - - if (getTreeSha(repoRoot, fromGit, contentDir) !== parsed) return undefined - - if (!hasParent(repoRoot, fromGit)) { - warn( - `Could not reach the GitHub API, and git labels the snapshot ${fromGit.slice(0, 7)}, ` + - `which has no parent in this checkout — a shallow clone boundary.\n` + - ` The snapshot is safe, but probably will not be looked up under that commit at runtime.` - ) - } - - return fromGit -} diff --git a/nuxt.config.ts b/nuxt.config.ts index a4d0363..77c8afb 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -14,6 +14,7 @@ export default defineNuxtConfig({ // `modules/` dir and dedupes by file path, so the extension is what keeps these from installing twice. resolve('./modules/config/index.ts'), resolve('./modules/css.ts'), + '@nuxt/content', // By path from this layer: a module name in a layer's `modules` resolves from the app, which can hoist other // versions than the ones the layer's components and Nuxt UI's runtime import, and their `#build` templates // then disagree. @nuxt/icon goes first so Nuxt UI finds it installed instead of resolving its own. @@ -27,10 +28,11 @@ export default defineNuxtConfig({ 'nuxt-schema-org', '@nuxtjs/mcp-toolkit', 'nuxt-llms', - 'nuxt-workers', 'nuxt-agent-discovery', ], ignore: ['content/**'], + // `server/content.ts` declares the content, served live at a commit chosen at runtime. + content: { mode: 'server-only', compatibilityVersion: 4 }, components: [ // Markdown components keep the name Markdown addresses them by: `CodeExplorer`, not `ContentCodeExplorer`. // Not global: the pages pass them to `MarkdownDocument` themselves (see `app/utils/content-components.ts`). @@ -89,8 +91,6 @@ export default defineNuxtConfig({ 'comark-docs > ai > @ai-sdk/gateway > @vercel/oidc', 'js-yaml' ], - // Pre-bundling would break the wasm/worker assets sqlite loads relative to its module URL. - exclude: ['@sqlite.org/sqlite-wasm'], }, }, llms: { diff --git a/package.json b/package.json index c773345..c595772 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "@iconify-json/simple-icons": "^1.2.102", "@iconify-json/unjs": "^1.2.4", "@iconify-json/vscode-icons": "^1.2.99", + "@nuxt/content": "^4.0.0", "@nuxt/icon": "^2.6.3", "@nuxt/kit": "^4.7.0", "@nuxt/ui": "^4.13.1", @@ -61,28 +62,25 @@ "@octokit/webhooks-methods": "^6.0.0", "@opentelemetry/api": "^1.10.0", "@resvg/resvg-js": "^2.6.2", - "@sqlite.org/sqlite-wasm": "3.53.4-build2", "@vercel/analytics": "^2.0.1", "@vercel/functions": "^3.11.3", - "@vercel/global-config": "^1.5.1", "@vercel/otel": "^2.3.0", "@vercel/speed-insights": "^2.1.0", "@vueuse/core": "^15.0.0", "ai": "^7.0.173", "beautiful-mermaid": "^1.1.3", "comark": "^0.9.2", - "comark-content": "^0.6.2", + "comark-content": "^0.6.3", "defu": "^6.1.7", "exsolve": "^1.2.0", "forges": "^0.3.2", "jiti": "^2.7.0", "js-yaml": "^5.5.0", - "nuxt-agent-discovery": "^0.8.2", + "nuxt-agent-discovery": "^0.8.3", "nuxt-llms": "^0.3.2", "nuxt-og-image": "^7.0.7", "nuxt-schema-org": "^7.0.1", "nuxt-seo-utils": "^9.0.2", - "nuxt-workers": "^0.1.0", "ofetch": "^1.5.1", "pathe": "^2.0.3", "rangi": "^2.2.0", diff --git a/playground/content/1.getting-started/3.configuration.md b/playground/content/1.getting-started/3.configuration.md index 7e98011..71a8ef8 100644 --- a/playground/content/1.getting-started/3.configuration.md +++ b/playground/content/1.getting-started/3.configuration.md @@ -187,7 +187,6 @@ export default defineAppConfig({ | Variable | Purpose | | --- | --- | | `GITHUB_TOKEN` | GitHub content reads and GraphQL history/RSS. Required in production. | -| `GLOBAL_CONFIG` | Connection string for the optional [`contentSha` production pin](/deployment/vercel#pin-production-content). Vercel creates it when you connect a Global Config store to the project. | | `WEBHOOK_SECRET` | HMAC secret for the GitHub push webhook (`/api/revalidate`). | | `VERCEL_BYPASS_TOKEN` | ISR purge on revalidation. Needed at **build** time too. | | `NUXT_APP_SECRET` | OG image signing, at least 32 characters. Required in production. | diff --git a/playground/content/3.concepts/1.architecture.md b/playground/content/3.concepts/1.architecture.md index e3da0b7..5db9cc4 100644 --- a/playground/content/3.concepts/1.architecture.md +++ b/playground/content/3.concepts/1.architecture.md @@ -21,18 +21,16 @@ In development, none of this applies: content is read straight from your working ## Pinned to a commit -Production doesn't read "whatever is on `main` right now." On each server render, comark-docs first checks a connected Vercel Global Config store for a `contentSha` value. When the value exists, every production content read is pinned to that commit. You can use this override to hold production on a reviewed version or roll content back without changing the production branch. See [Pin production content](/deployment/vercel#pin-production-content) for setup and cache timing. +Production doesn't read "whatever is on `main` right now." The server serves the latest commit **touching the content directory** on the production branch. That commit is stored in the Runtime Cache next to the parsed content, so every server serves the same one. -Without a `contentSha` value, the server resolves the latest commit **touching the content directory** on the production branch. The push webhook refreshes the shared pointer before purging affected pages, and a one-hour fallback TTL bounds staleness if the webhook fails. If Global Config is unavailable, comark-docs also falls back to this branch-based resolution. - -The Global Config pin applies only to the production Vercel environment. Preview deployments continue to follow their target branch, and local development reads from your working tree. +The push webhook moves production to the new commit before purging affected pages. If the webhook fails, the stored commit is trusted for one hour, then the next request asks GitHub again. Preview deployments follow their target branch the same way, with a 10-minute fallback, and local development reads from your working tree. Pinning buys two things: - **Consistency** — a request never mixes files from two commits, even mid-push. - **Cacheability** — content at a SHA can never change, so parsed pages are cached hard. -When no Global Config pin is active, code-only commits don't move the content SHA, so they don't invalidate anything. +Code-only commits don't move the content SHA, so they don't invalidate anything. ## Cache tiers diff --git a/playground/content/4.deployment/1.vercel.md b/playground/content/4.deployment/1.vercel.md index ab6eaf0..ec0421d 100644 --- a/playground/content/4.deployment/1.vercel.md +++ b/playground/content/4.deployment/1.vercel.md @@ -1,6 +1,6 @@ --- title: Vercel -description: Deploy your docs on Vercel with content pinning, ISR caching, instant updates, and builds that skip content-only pushes. +description: Deploy your docs on Vercel with ISR caching, instant updates, and builds that skip content-only pushes. --- The layer is built for [Vercel](https://vercel.com): rendered pages are cached at the edge with [ISR](https://vercel.com/docs/incremental-static-regeneration), parsed content persists in the Runtime Cache across deployments, and a GitHub webhook purges pages the moment content changes. @@ -20,7 +20,6 @@ In the project's **Settings → Environment Variables**: | Variable | Purpose | | --- | --- | | `GITHUB_TOKEN` | Reads content from GitHub and queries the GraphQL API for page history and RSS. A fine-grained token with read access to the repository contents is enough. | -| `GLOBAL_CONFIG` | Optional connection string for pinning production content to a specific commit. Vercel creates it when you connect a Global Config store. | | `WEBHOOK_SECRET` | Shared secret that signs the push webhook. Generate a random string. | | `VERCEL_BYPASS_TOKEN` | Lets the revalidation endpoint purge ISR pages. Must be available at **build** time — it's baked into the deployment's ISR configuration, so a runtime-only value leaves purging broken. | | `NUXT_APP_SECRET` | Signs OG image URLs. Must be at least 32 characters; generate one with `npx nuxt-og-image generate-secret`. Without it, OG image requests fail with a 500 error. | @@ -61,40 +60,6 @@ Adjust the path if your content directory differs. Both setups behave the same; :: -## Pin production content - -By default, production follows the latest commit that changed your content directory. An optional Vercel Global Config value named `contentSha` lets you hold production on a reviewed commit or roll content back without moving the production branch. The pin affects production only; preview deployments and local development don't read it. - -::steps{level="3"} - -### Connect a Global Config store - -In your Vercel project, open **Global Config**, then create a project store or connect an existing store. Vercel creates a `GLOBAL_CONFIG` environment variable containing the store's connection string. See [Vercel's Global Config setup guide](https://vercel.com/docs/global-config/get-started) for the dashboard workflow. - -If you connect the store after the current production deployment was built, redeploy once so its server functions receive `GLOBAL_CONFIG`. Later item updates don't require a redeploy. - -### Add the content SHA - -Copy the full commit SHA for the content version you want to serve. In the store's **Items** editor, add `contentSha` as a JSON string, then select **Save Items**: - -```json [Global Config items] -{ - "contentSha": "0123456789abcdef0123456789abcdef01234567" -} -``` - -New server renders now read content from that commit. Pages already cached by ISR update as they expire, which takes up to the configured [`comarkDocs.isr`](/getting-started/configuration#comarkdocs-options) duration (300 seconds by default). - -### Remove or move the pin - -Replace `contentSha` with another full commit SHA to move the pin. Delete the item to resume following the latest content commit on the production branch. Neither change requires a redeploy, but the same ISR expiration window applies. - -:: - -::warning -`contentSha` must resolve to a commit in the configured GitHub repository. An invalid or inaccessible value makes production content reads fail. A missing key, disconnected store, or Global Config read error safely falls back to the production branch. -:: - ## ISR behavior The layer generates ISR route rules for every top-level content section, the landing page, previews, and the machine-readable routes (`/raw/**`, `/llms.txt`, `/llms-full.txt`, `/sitemap.md`, `/rss.xml`, `/openapi.json`). Pages expire after 300 seconds by default, or immediately when the webhook purges them. @@ -105,9 +70,7 @@ Client-side navigation is unaffected by that expiration window: it fetches each ## Rolling back content -Content follows the head of the production branch unless a `contentSha` pin is active, so rolling back a *deployment* in Vercel does not roll back *content*. For a temporary rollback that leaves git history unchanged, [pin production to an older content commit](#pin-production-content). - -For a permanent rollback on the production branch, revert the content commit with git: +Content follows the head of the production branch, so rolling back a *deployment* in Vercel does not roll back *content*. To roll content back, revert the content commit with git: ```bash [Terminal] git revert diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6c0bd91..20d91aa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -173,6 +173,11 @@ settings: overrides: h3: ^1.15.11 + '@nuxt/content': https://pkg.pr.new/@nuxt/content@b771912 + comark-content: https://pkg.pr.new/comark-content@ec7a084 + comark: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a + '@comark/vue': https://pkg.pr.new/comarkdown/comark/@comark/vue@ff4661da9422748e74bcfcee497cd6835185344a + nuxt-agent-discovery: https://pkg.pr.new/benjamincanac/nuxt-agent-discovery@584d145 importers: @@ -185,8 +190,8 @@ importers: specifier: ^4.0.173 version: 4.0.173(vue@3.5.46(typescript@6.0.3))(zod@4.6.7) '@comark/vue': - specifier: ^0.9.2 - version: 0.9.2(@nuxt/kit@4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))))(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(rangi@2.2.0)(vue@3.5.46(typescript@6.0.3)) + specifier: https://pkg.pr.new/comarkdown/comark/@comark/vue@ff4661da9422748e74bcfcee497cd6835185344a + version: https://pkg.pr.new/comarkdown/comark/@comark/vue@ff4661da9422748e74bcfcee497cd6835185344a(@nuxt/kit@4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))))(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(rangi@2.2.0)(vue@3.5.46(typescript@6.0.3)) '@iconify-json/logos': specifier: ^1.2.20 version: 1.2.20 @@ -202,6 +207,9 @@ importers: '@iconify-json/vscode-icons': specifier: ^1.2.99 version: 1.2.99 + '@nuxt/content': + specifier: https://pkg.pr.new/@nuxt/content@b771912 + version: https://pkg.pr.new/@nuxt/content@b771912(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rangi@2.2.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2)))(vue@3.5.46(typescript@6.0.3)) '@nuxt/icon': specifier: ^2.6.3 version: 2.6.3(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(nitropack@2.14.0(@vercel/functions@3.11.3(ws@8.22.0))(acorn@8.18.0)(ioredis@5.11.1(supports-color@10.2.2))(oxc-parser@0.153.0)(rolldown@1.2.19)(srvx@1.0.8)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))(vue@3.5.46(typescript@6.0.3)) @@ -210,7 +218,7 @@ importers: version: 4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))) '@nuxt/ui': specifier: ^4.13.1 - version: 4.13.1(51e03aa49bce9f212cd7c2d3737e4028) + version: 4.13.1(3473e773c3a013609ee485c66255f743) '@nuxtjs/mcp-toolkit': specifier: ^0.24.3 version: 0.24.3(@nuxt/schema@4.7.0)(@vue/compiler-sfc@3.5.46)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(h3@1.15.11)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(rollup@4.69.0)(supports-color@10.2.2)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))(vue@3.5.46(typescript@6.0.3))(zod@4.6.7) @@ -229,18 +237,12 @@ importers: '@resvg/resvg-js': specifier: ^2.6.2 version: 2.6.2 - '@sqlite.org/sqlite-wasm': - specifier: 3.53.4-build2 - version: 3.53.4-build2 '@vercel/analytics': specifier: ^2.0.1 version: 2.0.1(nuxt@4.7.0(2be802afa5a16df45825d64f947103f8))(vue@3.5.46(typescript@6.0.3)) '@vercel/functions': specifier: ^3.11.3 version: 3.11.3(ws@8.22.0) - '@vercel/global-config': - specifier: ^1.5.1 - version: 1.5.1(@opentelemetry/api@1.10.0) '@vercel/otel': specifier: ^2.3.0 version: 2.3.0(@opentelemetry/api-logs@0.223.0)(@opentelemetry/api@1.10.0)(@opentelemetry/instrumentation@0.222.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2))(@opentelemetry/resources@2.12.1(@opentelemetry/api@1.10.0))(@opentelemetry/sdk-logs@0.223.0(@opentelemetry/api@1.10.0))(@opentelemetry/sdk-metrics@2.12.0(@opentelemetry/api@1.10.0))(@opentelemetry/sdk-trace-base@2.12.1(@opentelemetry/api@1.10.0)) @@ -257,11 +259,11 @@ importers: specifier: ^1.1.3 version: 1.1.3 comark: - specifier: ^0.9.2 - version: 0.9.2(beautiful-mermaid@1.1.3)(rangi@2.2.0) + specifier: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a + version: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0) comark-content: - specifier: ^0.6.2 - version: 0.6.2(beautiful-mermaid@1.1.3)(forges@0.3.2)(rangi@2.2.0)(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))) + specifier: https://pkg.pr.new/comark-content@ec7a084 + version: https://pkg.pr.new/comark-content@ec7a084(beautiful-mermaid@1.1.3)(forges@0.3.2)(rangi@2.2.0)(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))) defu: specifier: ^6.1.7 version: 6.1.7 @@ -278,8 +280,8 @@ importers: specifier: ^5.5.0 version: 5.5.0 nuxt-agent-discovery: - specifier: ^0.8.2 - version: 0.8.2(cbbd746a6c8ee2070c16b6c08da99064) + specifier: https://pkg.pr.new/benjamincanac/nuxt-agent-discovery@584d145 + version: https://pkg.pr.new/benjamincanac/nuxt-agent-discovery@584d145(bdf8c4da06dbb0504418937122388932) nuxt-llms: specifier: ^0.3.2 version: 0.3.2(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))) @@ -292,9 +294,6 @@ importers: nuxt-seo-utils: specifier: ^9.0.2 version: 9.0.2(@nuxt/schema@4.7.0)(@unhead/vue@3.4.3(@oxc-project/types@0.153.0)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.153.0)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))(vue@3.5.46(typescript@6.0.3)))(confbox@0.3.2)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(lightningcss@1.33.0)(magic-string@1.4.5)(mlly@1.8.2)(nuxt@4.7.0(2be802afa5a16df45825d64f947103f8))(oxc-parser@0.153.0)(rolldown@1.2.19)(unhead@3.4.3(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vue@3.5.46(typescript@6.0.3))(zod@4.6.7) - nuxt-workers: - specifier: ^0.1.0 - version: 0.1.0(magicast@0.5.5) ofetch: specifier: ^1.5.1 version: 1.5.1 @@ -340,7 +339,7 @@ importers: version: 2.12.1(@opentelemetry/api@1.10.0) comark-linter: specifier: ^0.12.1 - version: 0.12.1(comark@0.9.2(beautiful-mermaid@1.1.3)(rangi@2.2.0))(eslint@10.15.0(jiti@2.7.0)(supports-color@10.2.2)) + version: 0.12.1(comark@https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0))(eslint@10.15.0(jiti@2.7.0)(supports-color@10.2.2)) es-module-lexer: specifier: ^3.0.4 version: 3.0.4 @@ -371,7 +370,7 @@ importers: devDependencies: nuxtseo-devtools-host: specifier: ^1.0.2 - version: 1.0.2(0efc79ac5846e42aa09d68a0edc521a9) + version: 1.0.2(5a4457bd73bd6743d429840d0055257a) packages: @@ -567,8 +566,9 @@ packages: '@colordx/core@7.3.0': resolution: {integrity: sha512-LVzTTPhX7wpy7TkGjouA9zbbCBIw92RGm7ZQqSKFE0oYE3sMx2FGXz90eVpgw7k/+wrrY+qJ86nHXifZWMS5jA==} - '@comark/vue@0.9.2': - resolution: {integrity: sha512-6pVb087eSYmbCcVXnBN7Uewjh7+AuZihiqHZzmkyK2i8UvgRoaTXdECXof/orjAxDxt8HFndeBWFhk0A7prUaA==} + '@comark/vue@https://pkg.pr.new/comarkdown/comark/@comark/vue@ff4661da9422748e74bcfcee497cd6835185344a': + resolution: {integrity: sha512-vAmb43qcJcnRkYoxUPJsSkfNOhAAlNk9SBv3rFTH3IsWUqA5zP4NMFBBFJhE07QTYOqoj1zmQTmPjEzPtPjS9A==, tarball: https://pkg.pr.new/comarkdown/comark/@comark/vue@ff4661da9422748e74bcfcee497cd6835185344a} + version: 0.9.2 peerDependencies: '@nuxt/kit': ^4.6.3 '@nuxt/schema': ^4.6.3 @@ -1020,6 +1020,15 @@ packages: serve: optional: true + '@nuxt/content@https://pkg.pr.new/@nuxt/content@b771912': + resolution: {integrity: sha512-3FlGt4ZyxfkLC2blQuCQdBnC8u3tro/uhWmZ8FnkUnBoTcBwpLLozyNU+cPqxzQB+Xw/4ZULpsHUQTRNGejLaA==, tarball: https://pkg.pr.new/@nuxt/content@b771912} + version: 4.0.0 + peerDependencies: + shiki: ^4.3.1 + peerDependenciesMeta: + shiki: + optional: true + '@nuxt/devalue@2.0.2': resolution: {integrity: sha512-GBzP8zOc7CGWyFQS6dv1lQz8VVpz5C2yRszbXufwG/9zhStTIH50EtD87NmWbTMwXDvZLNg8GIpb1UFdH93JCA==} @@ -1105,10 +1114,6 @@ packages: '@nuxt/icon@2.6.3': resolution: {integrity: sha512-bJ1AnMz+sX4G3+CwWoh6mwVb3ghDJjivzpIsoIqFMPr/j8ou++acU/C4LoK3SClta7cpxYi7G3MC0bjFmvDfRA==} - '@nuxt/kit@3.21.11': - resolution: {integrity: sha512-0Xi3tgwN77w43Q8GCPIrvWmF1J7Peehkts44E0uKNIml9lB8WoUn8YxyUjxBv47XtVR86NWoWALAT+/IEMHJEA==} - engines: {node: '>=18.12.0'} - '@nuxt/kit@4.7.0': resolution: {integrity: sha512-78NsjcazI8PQPE0H8+mx+0c4Wm1GlvM5Oxj60sCHil0TUjTMjqRVMoORgJLPyPulMhD2Ih1rEZh5TEvXkytdLA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2155,8 +2160,8 @@ packages: '@speed-highlight/core@1.2.24': resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==} - '@sqlite.org/sqlite-wasm@3.53.4-build2': - resolution: {integrity: sha512-kQVArGJA4z7s56Dm8t+eTBXad4LiohuVj9pfgDNOcxa+Ic5xMrWlLPTq6cT0hw5S4MIvtpsraW+B0wD+IPvC7A==} + '@sqlite.org/sqlite-wasm@3.54.1-build1': + resolution: {integrity: sha512-foW427VBLJ3G87bsnvQTZCc9zYe0Fq1wH0pz1I6BlKLKXcArIAyTkHtq0iT2llmhcMQt9T/p6l5PpQQh+6O8uQ==} engines: {node: '>=22'} '@standard-schema/spec@1.1.0': @@ -2815,21 +2820,6 @@ packages: ws: optional: true - '@vercel/global-config-fs@0.1.0': - resolution: {integrity: sha512-xxMUwf96H/qKTA4Az+uh3xlVWkwnN3z400P5gex0uUsU8pe99njopYVyKVoUTfu8gN9xbHqaigWaIBr1+lufMg==} - - '@vercel/global-config@1.5.1': - resolution: {integrity: sha512-PUJaoyMGuSLdKnBgYIqeH1i6U3G+5noLvvJLqI8IPP5+P0b2Q5EcBBraFRh6ctNY/yTpb40klyLYyE3X0OPmKQ==} - engines: {node: '>=14.6'} - peerDependencies: - '@opentelemetry/api': ^1.7.0 - next: '>=1' - peerDependenciesMeta: - '@opentelemetry/api': - optional: true - next: - optional: true - '@vercel/nft@1.11.16': resolution: {integrity: sha512-xbFSa9AD75QuT8XSWDR/3M3CWk5XFw3gXiDp4bJXy0EEAc7fa8G6NGgXX/FHuX90R8s2JkQrlTYH/FZ+kmqXHg==} engines: {node: '>=20'} @@ -3411,8 +3401,9 @@ packages: colortranslator@5.0.0: resolution: {integrity: sha512-Z3UPUKasUVDFCDYAjP2fmlVRf1jFHJv1izAmPjiOa0OCIw1W7iC8PZ2GsoDa8uZv+mKyWopxxStT9q05+27h7w==} - comark-content@0.6.2: - resolution: {integrity: sha512-LqWmTQYHCHwlWolCVad0ErzBWNiJxQdWRC8m5+z/htOB6YrVpuIScCicoMh3Yk9tPnNWQyVQd5JL+sm9acqUFA==} + 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 @@ -3425,6 +3416,7 @@ packages: comark-linter@0.12.1: resolution: {integrity: sha512-F2OsVfxL9Es0hkmkbsndH6S2SvLUifZKMPMFE/pXRKqsAOsDeEShDtYm7PFlAIOU4Dr0iwUqDVBjI8ndPGpnXA==} + version: 0.12.1 engines: {node: '>=22.12.0'} hasBin: true peerDependencies: @@ -3584,14 +3576,18 @@ packages: vite-doctor: optional: true - comark@0.9.2: - resolution: {integrity: sha512-Sasiin9ormF9P6/0shrCZCPqJrZ14ICXbgU9UBJqBkqhF3ppqaAp56CYLx4cCSK4Q9BA9vMycoS6j2AZtYozUg==} + comark@https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a: + resolution: {integrity: sha512-l7lTZB8lnG/0mZgy/VVc5EzwT96J53O7P1OasLrQ3DLKkZcPE8Z/CzgHJvJtb2Qe5EAu+tfijYyEAn2ZDE947w==, tarball: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a} + version: 0.9.2 peerDependencies: + '@pierre/highlights': ^0.5.1 beautiful-mermaid: ^1.1.3 katex: ^0.19.1 rangi: ^2.2.0 shiki: ^4.6.0 peerDependenciesMeta: + '@pierre/highlights': + optional: true beautiful-mermaid: optional: true katex: @@ -3942,9 +3938,6 @@ packages: error-stack-parser-es@2.0.1: resolution: {integrity: sha512-J36ntO+rMQVRuR/umlmxmfLi4TpWwtmTnHoJoXTiC2xDNazs0VDPKcX6pbhZMDd2HFtH9isMBJXMdbki+A++Pg==} - errx@0.1.2: - resolution: {integrity: sha512-chfpPHmCerdo/rXr/nNvPZRkV4WwDRwzwnsJ0Uzz3tVi8Z41tDctRjduYy1138ii77AFlts1qvWtX3g/Acg91Q==} - errx@0.2.2: resolution: {integrity: sha512-HaPN6cxm6iZ9bIbQQ5orChcw7SY5smUzM08ZMc6OtV4UQhrrc3Ms1G8Ww2n/9lXkWqiioNTssF8bCvchrSbFEQ==} @@ -5094,10 +5087,11 @@ packages: nth-check@2.1.1: resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} - nuxt-agent-discovery@0.8.2: - resolution: {integrity: sha512-/dQSayuT8u7oeWI6qFfwfg6sKyQsTdg+wc6wZjlCw9g7/w2J4L+lM/D3EtLhZL2V7WlWBNzSfEqy7vA3Z4M4rA==} + nuxt-agent-discovery@https://pkg.pr.new/benjamincanac/nuxt-agent-discovery@584d145: + resolution: {integrity: sha512-26FIJNFLRQHPn/wt1EBcOeGvDKYZ+6l7DTXOq0gIFCezjnOe30GEh2KW0aqQ2qKUDMKZYMf/qZCeE4WRKwOi0w==, tarball: https://pkg.pr.new/benjamincanac/nuxt-agent-discovery@584d145} + version: 0.8.2 peerDependencies: - '@nuxt/content': ^3.7.0 + '@nuxt/content': ^3.7.0 || ^4.0.0 '@nuxtjs/mcp-toolkit': '>=0.19.0' '@nuxtjs/robots': ^6.0.0 || ^7.0.0 '@nuxtjs/sitemap': ^8.0.0 || ^9.0.0 @@ -5225,9 +5219,6 @@ packages: nuxt: ^4.6.0 || ^5.0.0 vue: ^3.5.43 - nuxt-workers@0.1.0: - resolution: {integrity: sha512-npsxy72FRQZkxHV1Y+KCkuSvb2Y/7Tcp7xGXPHXXVQ5/oIZ5+69VAudfdhpuwPN1JZJn9ULr01vKRLamENsTew==} - nuxt@4.7.0: resolution: {integrity: sha512-EancrkdwxojFZn0cjmB1xe1eBHml1j5JUCZM7oIaPqyYsgU21UUqxEOuNn1hdnBM3lcRiBqS85DlU/9Fcx9NTg==} engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0} @@ -6997,15 +6988,16 @@ snapshots: '@colordx/core@7.3.0': {} - '@comark/vue@0.9.2(@nuxt/kit@4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))))(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(rangi@2.2.0)(vue@3.5.46(typescript@6.0.3))': + '@comark/vue@https://pkg.pr.new/comarkdown/comark/@comark/vue@ff4661da9422748e74bcfcee497cd6835185344a(@nuxt/kit@4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))))(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(rangi@2.2.0)(vue@3.5.46(typescript@6.0.3))': dependencies: - comark: 0.9.2(beautiful-mermaid@1.1.3)(rangi@2.2.0) + comark: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0) vue: 3.5.46(typescript@6.0.3) optionalDependencies: '@nuxt/kit': 4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))) '@nuxt/schema': 4.7.0 beautiful-mermaid: 1.1.3 transitivePeerDependencies: + - '@pierre/highlights' - rangi '@csstools/css-tokenizer@4.0.2': {} @@ -7442,6 +7434,33 @@ snapshots: transitivePeerDependencies: - vite + '@nuxt/content@https://pkg.pr.new/@nuxt/content@b771912(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rangi@2.2.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2)))(vue@3.5.46(typescript@6.0.3))': + dependencies: + '@comark/vue': https://pkg.pr.new/comarkdown/comark/@comark/vue@ff4661da9422748e74bcfcee497cd6835185344a(@nuxt/kit@4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))))(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(rangi@2.2.0)(vue@3.5.46(typescript@6.0.3)) + '@nuxt/kit': 4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))) + '@sqlite.org/sqlite-wasm': 3.54.1-build1 + comark: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0) + comark-content: https://pkg.pr.new/comark-content@ec7a084(beautiful-mermaid@1.1.3)(forges@0.3.2)(rangi@2.2.0)(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))) + defu: 6.1.7 + forges: 0.3.2 + jiti: 2.7.0 + transitivePeerDependencies: + - '@nuxt/schema' + - '@pierre/highlights' + - beautiful-mermaid + - confbox + - dotenv + - giget + - katex + - magic-string + - mlly + - oxc-parser + - rangi + - rolldown + - unplugin + - unstorage + - vue + '@nuxt/devalue@2.0.2': {} '@nuxt/devtools-kit@3.4.4(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))': @@ -7706,32 +7725,6 @@ snapshots: - vite - vue - '@nuxt/kit@3.21.11(magicast@0.5.5)': - dependencies: - c12: 3.3.4(magicast@0.5.5) - consola: 3.4.2 - defu: 6.1.7 - destr: 2.0.5 - errx: 0.1.2 - exsolve: 1.2.0 - ignore: 7.0.17 - jiti: 2.7.0 - klona: 2.0.6 - knitwork: 1.3.0 - mlly: 1.8.2 - ohash: 2.0.12 - pathe: 2.0.3 - pkg-types: 2.4.0 - rc9: 3.1.0 - scule: 1.3.0 - semver: 7.8.6 - tinyglobby: 0.2.17 - ufo: 1.6.4 - unctx: 2.5.0 - untyped: 2.0.0 - transitivePeerDependencies: - - magicast - '@nuxt/kit@4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))': dependencies: consola: 3.4.2 @@ -7944,7 +7937,7 @@ snapshots: rc9: 3.1.0 std-env: 4.3.0 - '@nuxt/ui@4.13.1(51e03aa49bce9f212cd7c2d3737e4028)': + '@nuxt/ui@4.13.1(3473e773c3a013609ee485c66255f743)': dependencies: '@floating-ui/dom': 1.8.0 '@iconify/vue': 5.0.5(vue@3.5.46(typescript@6.0.3)) @@ -8013,6 +8006,7 @@ snapshots: vaul-vue: 0.4.1(reka-ui@2.11.0(vue@3.5.46(typescript@6.0.3)))(vue@3.5.46(typescript@6.0.3)) vue-component-type-helpers: 3.3.14 optionalDependencies: + '@nuxt/content': https://pkg.pr.new/@nuxt/content@b771912(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rangi@2.2.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2)))(vue@3.5.46(typescript@6.0.3)) ai: 7.0.173(zod@4.6.7) vue-router: 5.5.3(@vue/compiler-sfc@3.5.46)(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))(vue@3.5.46(typescript@6.0.3)) zod: 4.6.7 @@ -8857,7 +8851,7 @@ snapshots: '@speed-highlight/core@1.2.24': {} - '@sqlite.org/sqlite-wasm@3.53.4-build2': {} + '@sqlite.org/sqlite-wasm@3.54.1-build1': {} '@standard-schema/spec@1.1.0': {} @@ -9458,14 +9452,6 @@ snapshots: optionalDependencies: ws: 8.22.0 - '@vercel/global-config-fs@0.1.0': {} - - '@vercel/global-config@1.5.1(@opentelemetry/api@1.10.0)': - dependencies: - '@vercel/global-config-fs': 0.1.0 - optionalDependencies: - '@opentelemetry/api': 1.10.0 - '@vercel/nft@1.11.16(rollup@4.69.0)(supports-color@10.2.2)': dependencies: '@mapbox/node-pre-gyp': 2.0.3(supports-color@10.2.2) @@ -10066,9 +10052,9 @@ snapshots: colortranslator@5.0.0: {} - comark-content@0.6.2(beautiful-mermaid@1.1.3)(forges@0.3.2)(rangi@2.2.0)(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))): + comark-content@https://pkg.pr.new/comark-content@ec7a084(beautiful-mermaid@1.1.3)(forges@0.3.2)(rangi@2.2.0)(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2))): dependencies: - comark: 0.9.2(beautiful-mermaid@1.1.3)(rangi@2.2.0) + comark: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0) hookable: 6.1.2 pathe: 2.0.3 picomatch: 4.0.7 @@ -10077,18 +10063,19 @@ snapshots: forges: 0.3.2 unstorage: 1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2)) transitivePeerDependencies: + - '@pierre/highlights' - beautiful-mermaid - katex - rangi - shiki - comark-linter@0.12.1(comark@0.9.2(beautiful-mermaid@1.1.3)(rangi@2.2.0))(eslint@10.15.0(jiti@2.7.0)(supports-color@10.2.2)): + comark-linter@0.12.1(comark@https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0))(eslint@10.15.0(jiti@2.7.0)(supports-color@10.2.2)): dependencies: - comark: 0.9.2(beautiful-mermaid@1.1.3)(rangi@2.2.0) + comark: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0) optionalDependencies: eslint: 10.15.0(jiti@2.7.0)(supports-color@10.2.2) - comark@0.9.2(beautiful-mermaid@1.1.3)(rangi@2.2.0): + comark@https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0): dependencies: character-entities: 2.0.2 character-entities-legacy: 3.0.0 @@ -10344,8 +10331,6 @@ snapshots: error-stack-parser-es@2.0.1: optional: true - errx@0.1.2: {} - errx@0.2.2: {} es-define-property@1.0.1: {} @@ -11673,7 +11658,7 @@ snapshots: dependencies: boolbase: 1.0.0 - nuxt-agent-discovery@0.8.2(cbbd746a6c8ee2070c16b6c08da99064): + nuxt-agent-discovery@https://pkg.pr.new/benjamincanac/nuxt-agent-discovery@584d145(bdf8c4da06dbb0504418937122388932): dependencies: '@nuxt/kit': 4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))) defu: 6.1.7 @@ -11681,10 +11666,11 @@ snapshots: ufo: 1.6.4 yaml: 2.9.1 optionalDependencies: + '@nuxt/content': https://pkg.pr.new/@nuxt/content@b771912(@nuxt/schema@4.7.0)(beautiful-mermaid@1.1.3)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rangi@2.2.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(unstorage@1.17.6(@vercel/functions@3.11.3(ws@8.22.0))(db0@0.3.4)(ioredis@5.11.1(supports-color@10.2.2)))(vue@3.5.46(typescript@6.0.3)) '@nuxtjs/mcp-toolkit': 0.24.3(@nuxt/schema@4.7.0)(@vue/compiler-sfc@3.5.46)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(h3@1.15.11)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(rollup@4.69.0)(supports-color@10.2.2)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))(vue@3.5.46(typescript@6.0.3))(zod@4.6.7) '@nuxtjs/robots': 7.0.2(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(nuxt@4.7.0(2be802afa5a16df45825d64f947103f8))(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vue@3.5.46(typescript@6.0.3))(zod@4.6.7) '@nuxtjs/sitemap': 9.1.0(@nuxt/schema@4.7.0)(@oxc-project/types@0.153.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(nuxt@4.7.0(2be802afa5a16df45825d64f947103f8))(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vue@3.5.46(typescript@6.0.3))(zod@4.6.7) - comark: 0.9.2(beautiful-mermaid@1.1.3)(rangi@2.2.0) + comark: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a(beautiful-mermaid@1.1.3)(rangi@2.2.0) nuxt-llms: 0.3.2(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))) transitivePeerDependencies: - '@nuxt/schema' @@ -11877,17 +11863,6 @@ snapshots: - unplugin - zod - nuxt-workers@0.1.0(magicast@0.5.5): - dependencies: - '@nuxt/kit': 3.21.11(magicast@0.5.5) - magic-string: 0.30.21 - mlly: 1.8.2 - pathe: 2.0.3 - ufo: 1.6.4 - unplugin: 2.3.11 - transitivePeerDependencies: - - magicast - nuxt@4.7.0(2be802afa5a16df45825d64f947103f8): dependencies: '@dxup/nuxt': 0.5.11(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)) @@ -12044,13 +12019,13 @@ snapshots: - xml2js - yaml - nuxtseo-devtools-host@1.0.2(0efc79ac5846e42aa09d68a0edc521a9): + nuxtseo-devtools-host@1.0.2(5a4457bd73bd6743d429840d0055257a): dependencies: '@nuxt/devtools-kit': 4.0.0-beta.4(@nuxt/kit@4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))))(nitropack@2.14.0(@vercel/functions@3.11.3(ws@8.22.0))(acorn@8.18.0)(ioredis@5.11.1(supports-color@10.2.2))(oxc-parser@0.153.0)(rolldown@1.2.19)(srvx@1.0.8)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)) '@nuxt/kit': 4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))) birpc: 4.2.0 nuxt: 4.7.0(2be802afa5a16df45825d64f947103f8) - nuxtseo-layer-devtools: 6.0.2(0efc79ac5846e42aa09d68a0edc521a9) + nuxtseo-layer-devtools: 6.0.2(5a4457bd73bd6743d429840d0055257a) nuxtseo-shared: 6.0.3(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(nuxt-site-config@5.0.3(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(nuxt@4.7.0(2be802afa5a16df45825d64f947103f8))(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vue@3.5.46(typescript@6.0.3))(zod@4.6.7))(nuxt@4.7.0(2be802afa5a16df45825d64f947103f8))(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vue@3.5.46(typescript@6.0.3))(zod@4.6.7) sirv: 3.0.2 transitivePeerDependencies: @@ -12150,12 +12125,12 @@ snapshots: - yup - zod - nuxtseo-layer-devtools@6.0.2(0efc79ac5846e42aa09d68a0edc521a9): + nuxtseo-layer-devtools@6.0.2(5a4457bd73bd6743d429840d0055257a): dependencies: '@iconify-json/carbon': 1.2.28 '@nuxt/devtools-kit': 4.0.0-beta.4(@nuxt/kit@4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))))(nitropack@2.14.0(@vercel/functions@3.11.3(ws@8.22.0))(acorn@8.18.0)(ioredis@5.11.1(supports-color@10.2.2))(oxc-parser@0.153.0)(rolldown@1.2.19)(srvx@1.0.8)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)))(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1)) '@nuxt/kit': 4.7.0(@nuxt/schema@4.7.0)(confbox@0.3.2)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(oxc-parser@0.153.0)(rolldown@1.2.19)(unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.0)(vite@8.4.0(@types/node@26.6.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.1))) - '@nuxt/ui': 4.13.1(51e03aa49bce9f212cd7c2d3737e4028) + '@nuxt/ui': 4.13.1(3473e773c3a013609ee485c66255f743) '@shikijs/langs': 4.5.0 '@shikijs/themes': 4.5.0 '@vueuse/core': 15.0.0(vue@3.5.46(typescript@6.0.3)) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 80aaeb1..e22e87c 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -9,6 +9,7 @@ allowBuilds: minimumReleaseAgeExclude: # First-party packages, published and consumed here in the same session. - '@comark/vue' + - '@nuxt/content' - '@nuxt/ui' - comark - comark-content @@ -17,3 +18,16 @@ minimumReleaseAgeExclude: overrides: # Keep the workspace on a single h3 major (v1), matching comark-content. h3: ^1.15.11 + # Nuxt Content v4 isn't on npm yet: nuxt/content#3936 (live mode), stacked on #3931 (search worker). + '@nuxt/content': https://pkg.pr.new/@nuxt/content@b771912 + # Repeated from @nuxt/content, since pnpm does not apply a dependency's overrides. + # comarkdown/comark-content#172 and #175, until they're released. + comark-content: https://pkg.pr.new/comark-content@ec7a084 + # comark `main`, until comark 0.9.3 is released. + comark: https://pkg.pr.new/comarkdown/comark/comark@ff4661da9422748e74bcfcee497cd6835185344a + '@comark/vue': https://pkg.pr.new/comarkdown/comark/@comark/vue@ff4661da9422748e74bcfcee497cd6835185344a + # 0.8.3 refuses Nuxt Content v4: latest build of benjamincanac/nuxt-agent-discovery#61. + nuxt-agent-discovery: https://pkg.pr.new/benjamincanac/nuxt-agent-discovery@584d145 + +# The overrides above are pkg.pr.new tarballs. +blockExoticSubdeps: false diff --git a/scripts/test-pack.sh b/scripts/test-pack.sh index b40fd34..abfdce1 100755 --- a/scripts/test-pack.sh +++ b/scripts/test-pack.sh @@ -27,10 +27,8 @@ echo "› Copying the consumer fixture to $work/app" cp -R "$root/test/fixtures/consumer" "$work/app" cd "$work/app" -# A git checkout like a real site, so the build-time content snapshot runs too. -# The empty root commit gives the content commit a parent, as in any non-shallow clone. +# A git checkout like a real site, so `modules/config` finds the content directory from git. git init -q -git -c user.name=ci -c user.email=ci@localhost commit -q --allow-empty -m root git add -A git -c user.name=ci -c user.email=ci@localhost commit -qm fixture diff --git a/server/api/__sitemap__/urls.get.ts b/server/api/__sitemap__/urls.get.ts index a7a2977..998f348 100644 --- a/server/api/__sitemap__/urls.get.ts +++ b/server/api/__sitemap__/urls.get.ts @@ -1,9 +1,9 @@ import type { NavigationItem } from 'comark-content' +import { content } from '../../content' /** Sitemap source for `@nuxtjs/sitemap`. */ export default defineEventHandler(async () => { - const content = await getProdContent() - const navigation = await content.navigation() + const navigation = await (await resolveContent(content)).navigation() const urls: string[] = ['/', '/logos'] const collect = (items: NavigationItem[]) => { diff --git a/server/api/assistant.post.ts b/server/api/assistant.post.ts index 15bcd24..294dace 100644 --- a/server/api/assistant.post.ts +++ b/server/api/assistant.post.ts @@ -11,6 +11,7 @@ import { gateway } from '@ai-sdk/gateway' import { z } from 'zod' import type { NavigationItem } from 'comark-content' import { getAgentDocument } from '#agent-discovery' +import { content } from '../content' /** Keep the context bounded on a public endpoint: only the tail of long conversations is forwarded. */ const MAX_MESSAGES = 20 @@ -47,8 +48,8 @@ export default defineEventHandler(async (event) => { const site = getSiteConfig(event) const siteName = appConfig.seo?.siteName || site.name || 'this site' - const content = await getProdContent() - const navigation = await content.navigation() + const docs = await resolveContent(content) + const navigation = await docs.navigation() const result = streamText({ model: gateway(useRuntimeConfig(event).assistant.model), @@ -80,7 +81,7 @@ ${pageIndex(navigation)}`, query: z.string().describe('Search terms, e.g. "github source" or "custom components"'), }), execute: async ({ query }) => { - const results = await searchDocSections(content, query) + const results = await searchDocSections(docs, query) if (!results.length) return `No results for "${query}". Try other terms or get_page with a path from the page index.` return results .map((section) => { diff --git a/server/api/content/[...path].get.ts b/server/api/content/[...path].get.ts deleted file mode 100644 index c4f39d7..0000000 --- a/server/api/content/[...path].get.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Single data endpoint: `content.handler()` dispatches `get`, `navigation`, `list`, `manifest` - * and `snapshot`. Must be cached per-URL by layer consumer. - */ -export default defineEventHandler(async (event) => { - const content = await getProdContent() - - return content.handler(toWebRequest(event)) -}) diff --git a/server/api/content/head.get.ts b/server/api/content/head.get.ts index 493c5bb..1da1d89 100644 --- a/server/api/content/head.get.ts +++ b/server/api/content/head.get.ts @@ -1,10 +1,9 @@ +import { content } from '../../content' + /** - * The commit SHA production content is pinned to, or `null` in dev. + * The commit SHA production content is served at, or `null` in dev. */ export default defineEventHandler(async () => { - if (import.meta.dev) return { sha: null } - - // Same resolution as the pages (`getProdContent`), so the search artifacts the client hydrates - // from can't come from a different commit than the rendered content — notably under a pin. - return { sha: await resolveProdSha() } + // The commit the pages read, so search loads the same content as the rendered pages. + return { sha: (await resolveContent(content)).ref ?? null } }) diff --git a/server/api/history.get.ts b/server/api/history.get.ts index 0b6e030..38efb83 100644 --- a/server/api/history.get.ts +++ b/server/api/history.get.ts @@ -1,4 +1,5 @@ import { withLeadingSlash } from 'ufo' +import { content } from '../content' /** * Commit history for a single content page. @@ -63,10 +64,9 @@ export default defineEventHandler(async (event): Promise => { const raw = getQuery(event).path const path = typeof raw === 'string' && raw ? withLeadingSlash(raw) : '/' - const content = await getProdContent() const branch = targetBranch() - const item = await content.get(path) + const item = await (await resolveContent(content)).get(path) if (!item || item.meta.kind !== 'document') return { branch, commits: [] } const file = `${item.meta.stem.split('/').pop()}${item.meta.extension}` diff --git a/server/api/revalidate.post.ts b/server/api/revalidate.post.ts index 56544d4..cb63c24 100644 --- a/server/api/revalidate.post.ts +++ b/server/api/revalidate.post.ts @@ -2,6 +2,7 @@ import { verify } from '@octokit/webhooks-methods' import { rawUrl } from '#agent-discovery' import { DEFAULT_CONTENT_NAME } from 'comark-content' import { waitUntil } from '@vercel/functions' +import { content } from '../content' /** Each re-render hits this same deployment, so the ceiling is about not stampeding ourselves. */ const REVALIDATE_CONCURRENCY = 8 @@ -49,9 +50,7 @@ export default defineEventHandler(async (event) => { } const payload = JSON.parse(raw) as GitHubPushPayload - const branch = targetBranch() - const contentDir = docs.contentDir - const expectedRef = `refs/heads/${branch}` + const expectedRef = `refs/heads/${targetBranch()}` const repo = githubRepo() if (payload.repository?.full_name && payload.repository.full_name !== repo) { @@ -64,8 +63,9 @@ export default defineEventHandler(async (event) => { return { ok: true, skipped: 'non-target-branch', expected: expectedRef, received: payload.ref } } - const changes = changesForPush(contentDir, payload.commits ?? []) - if (!changes.upserted.length && !changes.removed.length && !changes.navTouched) { + // Moves production to the last commit touching the content directory, and compares it with the one served before. + const { from, to, changed, removed, navigation } = await timings.time('revalidate', () => revalidateContent(content)) + if (from === to) { return { ok: true, skipped: 'no-content-changes' } } @@ -83,34 +83,17 @@ export default defineEventHandler(async (event) => { byReason.set(reason, paths) } - // Diffed against the live prod instance, already warm - const { headSha, newItems, pagePaths, navChanged } = await timings.time('rebuild', async () => { - const outdated = await getProdContent() - await outdated.init() - const oldItems = { ...(await outdated.manifest()).items } - - // Refresh the content SHA - const headSha = await resolveContentSha(branch, contentDir, { refresh: true }) - - // Throwaway instance: the diff needs the index only. - // It lands in the commit's cache namespace to be reused by the prod warm below. - const fresh = contentAt(headSha) - await fresh.init() - const newItems = (await fresh.manifest()).items - await fresh.dispose() - - return { headSha, newItems, ...diffContent(changes, oldItems, newItems) } - }) - - for (const path of pagePaths) { + // A removed page is purged too, so it stops being served. + for (const path of [...changed, ...removed]) { addPath('page', path) addPath('payload', payloadUrlForPage(path, buildId)) addPath('raw', rawPathFor(path)) } // Navigation renders on every page, so a change to it re-renders all of them. - if (navChanged) { - for (const item of Object.values(newItems)) { + if (navigation) { + const { items } = await (await resolveContent(content)).manifest() + for (const item of Object.values(items)) { if (item.meta.kind !== 'document') continue addPath('nav', item.path) addPath('nav', payloadUrlForPage(item.path, buildId)) @@ -119,7 +102,7 @@ export default defineEventHandler(async (event) => { } // Per-commit search artifacts (ISR, immutable). - const artifactBase = `/api/content/blob/${headSha}` + const artifactBase = `/api/content/blob/${to}` const pathsToWarm = [`${artifactBase}/manifest.json`, `${artifactBase}/snapshot/${DEFAULT_CONTENT_NAME}.json`] // Any content change invalidates the global indexes: each is rebuilt from the whole tree. @@ -128,27 +111,14 @@ export default defineEventHandler(async (event) => { } console.log( - `${tag} navChanged=${navChanged} ` + - `(upserted=${changes.upserted.length}, removed=${changes.removed.length}, navConfig=${changes.navTouched}) | ` + + `${tag} ${from?.slice(0, 7) ?? 'none'} -> ${to.slice(0, 7)} navigation=${navigation} ` + + `(changed=${changed.length}, removed=${removed.length}) | ` + `${pathsToPurge.size} to purge, ${pathsToWarm.length} to warm | ${timings.format()}` ) logBreakdown(tag, byReason) for (const path of pathsToWarm) console.log(`${tag} warm\t${path}`) - // Dev has no ISR cache to purge - if (import.meta.dev) { - return { - ok: true, - requestId, - deliveryId, - navChanged, - routes: routesBreakdown(byReason), - warm: pathsToWarm.length, - dev: true, - } - } - const protocol = getRequestProtocol(event) const host = getRequestHost(event, { xForwardedHost: true }) const baseURL = `${protocol}://${host}` @@ -207,8 +177,10 @@ export default defineEventHandler(async (event) => { ok: true, requestId, deliveryId, - navChanged, - manifest: { upserted: changes.upserted, removed: changes.removed }, + from, + to, + navigation, + pages: { changed, removed }, routes: routesBreakdown(byReason), } }) diff --git a/server/content.ts b/server/content.ts new file mode 100644 index 0000000..d937d59 --- /dev/null +++ b/server/content.ts @@ -0,0 +1,65 @@ +import { createNuxtContent, lastCommit } from '@nuxt/content/server' +import markdown from 'comark-content/plugins/markdown' +import yaml from 'comark-content/plugins/yaml' +import tracingOtel from 'comark-content/plugins/tracing/otel' +import fs from 'comark-content/sources/fs' +import forge from 'comark-content/sources/forge' +import emoji from 'comark/plugins/emoji' +import mermaid from 'comark/plugins/mermaid' +import security from 'comark/plugins/security' +import toc from 'comark/plugins/toc' +import { github } from 'forges/github' +import highlighter from '#comark-docs/highlighter' +import { contentCacheDriver } from './utils/cache' +import { gitLocalSource } from './utils/local' +import { contentTracer } from './utils/tracer' +import type { BuildContent } from '../shared/types/build-content' + +// This file also runs at build, outside Nitro, so it reads `process.env` where server code reads `useRuntimeConfig()`. +const build: BuildContent = JSON.parse(process.env.COMARK_DOCS_CONTENT!) +const env = process.env +const token = env.NUXT_DOCS_GITHUB_TOKEN || env.GITHUB_TOKEN +const contentDir = env.NUXT_DOCS_CONTENT_DIR || build.contentDir +const repository = { + provider: github(token ? { auth: { type: 'token', token } } : {}), + repo: `${env.NUXT_DOCS_GITHUB_OWNER || build.owner || env.VERCEL_GIT_REPO_OWNER}/${env.NUXT_DOCS_GITHUB_REPO || build.repo || env.VERCEL_GIT_REPO_SLUG}`, + // Content pushes skip redeploys (`vercel.json` `ignoreCommand`), so the branch is read at runtime. + ref: env.VERCEL_GIT_COMMIT_REF || env.NUXT_DOCS_GITHUB_BRANCH || build.branch || 'main', + path: contentDir, +} + +/** Frontmatter kept in the manifest, so `list()` and `navigation()` render without reading bodies. */ +const LISTING_FIELDS = ['title', 'description', 'navigation', 'icon', 'layout'] + +const tracer = contentTracer() + +export const content = createNuxtContent({ + mode: 'server-only', + // Dev reads the working tree, and its previews read the local repository at a commit. + source: import.meta.dev + ? { ...fs(build.contentPath), withRef: (ref: string) => gitLocalSource(ref, contentDir) } + : forge(repository), + // Bump CONTENT_PARSER_VERSION in `utils/cache.ts` when these plugins or their options change cached output. + plugins: [ + markdown({ + comark: { + plugins: [ + mermaid({ theme: 'zinc-light', themeDark: 'zinc-dark' }), + highlighter, + toc({ depth: 3 }), + emoji(), + security({ + blockedTags: ['script', 'iframe', 'embed', 'form', 'base', 'meta', 'link', 'style'], + allowDataImages: false, + }), + ], + }, + listingFields: LISTING_FIELDS, + }), + yaml({ listingFields: LISTING_FIELDS }), + tracer && tracingOtel({ tracer }), + ], + cache: { driver: contentCacheDriver(build.highlighterVersion) }, + // The webhook moves production at once, `maxAge` bounds recovery when a delivery fails. + live: { ref: lastCommit(repository), maxAge: env.VERCEL_ENV === 'production' ? 60 * 60 : 10 * 60 }, +}) diff --git a/server/mcp/tools/search-docs.ts b/server/mcp/tools/search-docs.ts index 3290d55..0fa5673 100644 --- a/server/mcp/tools/search-docs.ts +++ b/server/mcp/tools/search-docs.ts @@ -1,4 +1,5 @@ import { z } from 'zod' +import { content } from '../../content' export default defineMcpTool({ description: @@ -7,8 +8,7 @@ export default defineMcpTool({ query: z.string().describe('Search terms, e.g. "github source" or "full text search"'), }, handler: async ({ query }) => { - const content = await getProdContent() - const results = await searchDocSections(content, query) + const results = await searchDocSections(await resolveContent(content), query) if (!results.length) { return { diff --git a/server/middleware/payload-etag.ts b/server/middleware/payload-etag.ts index c871046..b6a3f0b 100644 --- a/server/middleware/payload-etag.ts +++ b/server/middleware/payload-etag.ts @@ -1,3 +1,5 @@ +import { content } from '../content' + /** * A weak ETag on `_payload.json`, so client-side navigation on prod pages (cached via `isr`) can * send a conditional request instead of always re-downloading the payload body. @@ -13,12 +15,12 @@ export default defineEventHandler(async (event) => { if (!pathname.endsWith('/_payload.json')) return if (/^\/(?:tree|blob|pr)\//.test(pathname)) return - let sha: string + let sha: string | undefined try { - sha = await resolveProdSha() + sha = (await resolveContent(content)).ref } catch { return } - setResponseHeader(event, 'etag', `W/"${sha}"`) + if (sha) setResponseHeader(event, 'etag', `W/"${sha}"`) }) diff --git a/server/routes/.well-known/search.ts b/server/routes/.well-known/search.ts index c0dfffa..1cdd13b 100644 --- a/server/routes/.well-known/search.ts +++ b/server/routes/.well-known/search.ts @@ -2,6 +2,7 @@ import { getAgentSiteUrl } from '#agent-discovery' import { createError, defineEventHandler, getQuery, getRequestHeader } from 'nuxt/server' import type { RequestEvent } from 'nuxt/server' import { joinURL } from 'ufo' +import { content } from '../../content' /** A search query, not a document: anything larger is refused before it is buffered. */ const MAX_QUERY_BODY = 16 * 1024 @@ -31,7 +32,7 @@ export default defineEventHandler(async (event) => { query = query.trim() if (!query) throw createError({ status: 400, statusText: 'Missing `q` parameter' }) - const sections = await searchDocSections(await getProdContent(), query) + const sections = await searchDocSections(await resolveContent(content), query) const siteUrl = getAgentSiteUrl(event) const results = sections.map((section) => { const heading = [...section.titles, section.title].filter(Boolean).join(' > ') diff --git a/server/routes/rss.xml.get.ts b/server/routes/rss.xml.get.ts index 893c6f1..b444ac8 100644 --- a/server/routes/rss.xml.get.ts +++ b/server/routes/rss.xml.get.ts @@ -1,6 +1,7 @@ import type { NavigationItem } from 'comark-content' import { useAppConfig } from 'nitropack/runtime' import { joinURL } from 'ufo' +import { content } from '../content' // RSS 2.0 feed of every docs page, last-modified dates from git. ISR-cached; purged by the push webhook. @@ -24,8 +25,8 @@ const escapeXml = (value: string) => .replaceAll("'", ''') export default defineEventHandler(async (event) => { - const content = await getProdContent() - const navigation = await content.navigation() + const docs = await resolveContent(content) + const navigation = await docs.navigation() const site = getSiteConfig(event) const appConfig = useAppConfig(event) const siteUrl = site.url || '/' @@ -37,7 +38,7 @@ export default defineEventHandler(async (event) => { const collect = (items: NavigationItem[]) => { for (const item of items) { if (item.page !== false && item.path) { - const entry = content.stat(item.path) + const entry = docs.stat(item.path) if (entry && entry.meta.kind === 'document') { pages.push({ path: item.path, @@ -52,7 +53,7 @@ export default defineEventHandler(async (event) => { } collect(navigation) - const dates = await lastModifiedDates(pages.map((page) => page.repoPath)) + const dates = await lastModifiedDates(pages.map((page) => page.repoPath), docs.ref) const items = pages .map((page) => { @@ -96,7 +97,7 @@ ${items} }) /** repoPath → ISO date of the last commit touching it. */ -async function lastModifiedDates(repoPaths: string[]): Promise> { +async function lastModifiedDates(repoPaths: string[], rev = targetBranch()): Promise> { const dates = new Map() if (import.meta.dev) { @@ -110,7 +111,6 @@ async function lastModifiedDates(repoPaths: string[]): Promise>(cacheKey) diff --git a/server/utils/agent-source.ts b/server/utils/agent-source.ts index 0ec9df9..77caa90 100644 --- a/server/utils/agent-source.ts +++ b/server/utils/agent-source.ts @@ -1,8 +1,9 @@ import { createComarkSource } from '#agent-discovery/comark' +import { content } from '../content' /** * Content adapter behind nuxt-agent-discovery: the raw markdown route, `sitemap.md`, the `llms.txt` * bridge and the MCP helpers all read production content through it. Versioned previews (`/tree`, * `/blob`, `/pr`) are excluded from negotiation in nuxt.config.ts and keep serving HTML. */ -export default createComarkSource(() => getProdContent()) +export default createComarkSource(() => resolveContent(content)) diff --git a/server/utils/cache.ts b/server/utils/cache.ts index ee5a3cb..e3a95bb 100644 --- a/server/utils/cache.ts +++ b/server/utils/cache.ts @@ -17,11 +17,10 @@ function runtimeCacheDriver(base: string, ttl?: number): Driver { * Bump when content parser/plugin configuration, relevant parser dependencies, or cached derived * data changes. Keeping this explicit lets unrelated deployments reuse immutable content artifacts. */ -export const CONTENT_PARSER_VERSION = 'v6' +export const CONTENT_PARSER_VERSION = 'v7' /** The parser version, plus a hash of the site's `comarkDocs.highlighter` when it sets one. */ -function parserVersion(): string { - const { highlighterVersion } = useRuntimeConfig().docs +function parserVersion(highlighterVersion = useRuntimeConfig().docs.highlighterVersion): string { return highlighterVersion ? `${CONTENT_PARSER_VERSION}-${highlighterVersion}` : CONTENT_PARSER_VERSION } @@ -31,20 +30,20 @@ function parserVersion(): string { const IMMUTABLE_TTL = 60 * 60 * 24 /** - * Comark cache: index, parsed bodies and artifacts of every commit. + * Comark cache: index, parsed bodies and artifacts of every commit, and the live commit Nuxt Content serves. * Base namespace is per parser version and keys are per-sha. */ -export function contentCacheDriver(): Driver { - return runtimeCacheDriver(`content:${parserVersion()}`, IMMUTABLE_TTL) +export function contentCacheDriver(highlighterVersion: string): Driver { + return runtimeCacheDriver(`content:${parserVersion(highlighterVersion)}`, IMMUTABLE_TTL) } /** - * Shared driver backing branch pointers and preview authorization decisions (`github.ts`). + * Shared driver backing `/tree/:branch` pointers and preview authorization decisions (`github.ts`). * The branch is mutable, so the TTL is bounded. * * TODO: Vercel Runtime Cache is **regional**, not global (https://vercel.com/docs/caching/runtime-cache): * It assumes Functions run in a single region. - * Multi-region would confine the webhook's forced refresh to its region (others self-heal on TTL) + * Multi-region would confine the webhook's move of the production commit (in `contentCacheDriver()`) to its region. * We should reach for a globally replicated store (e.g. Edge Config). */ export function refCacheDriver(ttl: number): Driver { diff --git a/server/utils/content.ts b/server/utils/content.ts deleted file mode 100644 index 8791039..0000000 --- a/server/utils/content.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { type ContentSource, DEFAULT_CONTENT_NAME } from 'comark-content' -import fs from 'comark-content/sources/fs' -import forge from 'comark-content/sources/forge' -import { withSnapshot } from 'comark-content/sources/snapshot' -import { createRuntimeContentInstance } from '../../utils/factory.ts' -import highlighter from '#comark-docs/highlighter' - -/** - * The instance serving requests in this layer. - */ -export type DocsContent = ReturnType - -/** - * Holds the source, the plugins and the cache driver. - * Once per function invocation. - * Base for all instances "cloned" with `withRef(sha)` in `contentAt()`. - */ -let base: DocsContent | undefined - -function getBaseContent(): DocsContent { - base ??= createBaseContent() - return base -} - -function createBaseContent() { - return createRuntimeContentInstance( - { - source: contentSource(), - cache: { driver: contentCacheDriver() }, - }, - highlighter, - ) -} - -/** - * Base instance cloned and pinned to a SHA. - * Nothing is read until the first call. - * `dispose()` it when you replace it. -*/ -export function contentAt(sha: string): DocsContent { - return getBaseContent().withRef(sha) -} - -// The content commit currently served, once `getProdContent()` has resolved one. -// Pin GitHub reads to an immutable SHA: -// bypasses the stale `raw.githubusercontent.com/` CDN. -let headSha: string | undefined - -/** - * The pinned head commit, or nothing while none is resolved (dev, off-Vercel, pre-first-resolve). - */ -export function getHeadSha(): string | undefined { - return headSha -} - -/** - * The pinned head SHA, falling back to the branch while none is resolved. - * The fallback only ever applies off-Vercel (self-hosted, `nuxt preview`, `vercel dev`). - */ -export function getHeadRef(): string { - return headSha ?? targetBranch() -} - -// Share pending promises to avoid multiple concurrent requests. -let pendingSha: Promise | undefined - -/** - * The SHA prod instance currently serves: - * - global config pin if one is set (production only) - * - latest commit touching the content directory via `resolveContentSha()` - */ -export function resolveProdSha(): Promise { - pendingSha ??= (async () => { - const { contentDir } = useRuntimeConfig().docs - if (process.env.VERCEL_ENV === 'production') { - const pinned = await getPinnedSha() - if (pinned) return pinned - } - return resolveContentSha(targetBranch(), contentDir) - })().finally(() => { - pendingSha = undefined - }) - return pendingSha -} - -// Rebuild the promise when the head advances. -// Holds the promise to ensure two requests on a cold process don't each build one. -let prod: Promise | undefined - -/** - * Shared instance for the lifetime of the process, pinned to `headSha`. - * Always resolves the head via `resolveProdSha()`. - * Swaps to a new pinned instance when the head advances. - */ -export async function getProdContent(): Promise { - if (['production', 'preview'].includes(process.env.VERCEL_ENV || '')) { - const sha = await resolveProdSha() - if (sha !== headSha) { - if (headSha) { - console.log(`[comark-docs] New head: ${headSha} -> ${sha}`) - void prod?.then((instance) => instance.dispose()).catch(() => {}) - prod = undefined - } - headSha = sha - } - } - - if (!prod) { - prod = (async () => { - const instance = import.meta.dev ? await watchedDevContent() : contentAt(getHeadRef()) - const startedAt = performance.now() - await instance.init() - recordDuration('content.init.ms', startedAt) - return instance - })().catch((error) => { - prod = undefined - throw error - }) - } - return prod -} - -/** The unpinned base in development — it reads the working tree and follows file changes. */ -async function watchedDevContent(): Promise { - const instance = getBaseContent() - await instance.watch() - instance.hooks.hook('watch:file:update', (_source: string, key: string) => { - invalidateSearchSections(instance) - console.log(`[comark-docs] ${key} updated`) - }) - instance.hooks.hook('watch:file:remove', () => invalidateSearchSections(instance)) - return instance -} - -/** - * The source every instance derives from. - * `withRef(sha)` pins it to a commit. - * - * Production: - * - GitHub reads the tree and files at `sha` - * - the build snapshot supplies every body whose source hash is unchanged - * - * Development: - * - unpinned reads the working tree, which `watch()` follows - * - pinned reads the repo at that commit - * - no snapshot - */ -function contentSource(): ContentSource { - const { docs } = useRuntimeConfig() - - if (import.meta.dev) { - return { - ...fs(docs.contentPath), - withRef: (ref) => gitLocalSource(ref, docs.contentDir), - } - } - - const source = forge({ - provider: githubProvider(), - repo: githubRepo(), - ref: targetBranch(), - path: docs.contentDir, - }) - - // Snaphot build during build time by `modules/snapshot/` is used. - // Snpahost is pinned to the latest commit at the time of the build. - // First head moves, only the bodies whose source hash matches are reused. - return withSnapshot(source, () => readSnapshot(), () => readManifest()) -} - -/** - * Read the build-time snapshot, or nothing when this deployment did not ship one. - */ -async function readSnapshot(): Promise { - const span = contentTracer()?.startSpan('snapshot:read') - const startedAt = performance.now() - try { - // Untyped read: unstorage runs every value through `destr`, so this arrives already parsed. - const data = await useStorage('assets:comark-content').get(`${DEFAULT_CONTENT_NAME}/snapshot.json`) - const hit = data != null - span?.setAttribute('comark.snapshot.hit', hit) - recordDuration('content.snapshot.read.ms', startedAt, { hit: String(hit) }) - return data - } finally { - span?.end() - } -} - -/** - * Read the build-time snapshot, or nothing when this deployment did not ship one. - */ -async function readManifest(): Promise { - const span = contentTracer()?.startSpan('manifest:read') - const startedAt = performance.now() - try { - // Untyped read: unstorage runs every value through `destr`, so this arrives already parsed. - const data = await useStorage('assets:comark-content').get(`${DEFAULT_CONTENT_NAME}/manifest.json`) - const hit = data != null - span?.setAttribute('comark.manifest.hit', hit) - recordDuration('content.manifest.read.ms', startedAt, { hit: String(hit) }) - return data - } finally { - span?.end() - } -} diff --git a/server/utils/github.ts b/server/utils/github.ts index 556123f..b3541cc 100644 --- a/server/utils/github.ts +++ b/server/utils/github.ts @@ -3,18 +3,8 @@ import { createStorage } from 'unstorage' import { github } from 'forges/github' import { fetchLastContentCommit } from '../../utils/github' -export interface GitHubCommit { - added?: string[] - removed?: string[] - modified?: string[] -} - export interface GitHubPushPayload { ref?: string - /** Parent SHA of the ref before this push */ - before?: string - commits?: GitHubCommit[] - head_commit?: GitHubCommit & { id?: string } repository?: { full_name?: string } } @@ -53,25 +43,15 @@ export function targetBranch(): string { return process.env.VERCEL_GIT_COMMIT_REF || useRuntimeConfig().docs.github.branch || 'main' } -/** The webhook refreshes production immediately; this bounds recovery when delivery fails. */ -const PRODUCTION_REF_TTL = 60 * 60 - -/** Moving previews and negative decisions refresh or recover more frequently. */ +/** How long `/tree/:branch` previews and preview decisions are trusted before GitHub is asked again. */ const PREVIEW_REF_TTL = 600 -// Branch + content directory → content commit SHA pointer, shared across every instance. The -// production branch is refreshed by its push webhook; TTL remains a bounded fallback. -const refStorage = createStorage({ driver: refCacheDriver(PRODUCTION_REF_TTL) }) +// Branch + content directory → content commit SHA pointer for `/tree/:branch`, shared across every instance. +const refStorage = createStorage({ driver: refCacheDriver(PREVIEW_REF_TTL) }) const normalizeContentDir = (contentDir: string) => contentDir.replace(/^\/+|\/+$/g, '') const refKey = (branch: string, contentDir: string) => `branch:${encodeURIComponent(branch)}:path:${encodeURIComponent(normalizeContentDir(contentDir))}` -/** Production has a longer fallback because its webhook owns the normal refresh path. */ -function refTtl(branch: string): number { - if (process.env.VERCEL_ENV === 'production' && branch === targetBranch()) return PRODUCTION_REF_TTL - return PREVIEW_REF_TTL -} - /** Sentinel for "this ref doesn't resolve" — see the negative caching in `resolveContentSha`. */ const UNRESOLVED = '\0unresolved' @@ -87,21 +67,17 @@ const UNRESOLVED = '\0unresolved' export async function resolveContentSha( branch: string, contentDir: string, - opts: { cacheMisses?: boolean; refresh?: boolean } = {} + opts: { cacheMisses?: boolean } = {} ): Promise { if (import.meta.dev) return branch const key = refKey(branch, contentDir) - if (!opts.refresh) { - const cached = await refStorage.getItem(key) - if (cached === UNRESOLVED) { - throw createError({ statusCode: 404, statusMessage: `Ref not found: ${branch}` }) - } - if (cached) return cached + const cached = await refStorage.getItem(key) + if (cached === UNRESOLVED) { + throw createError({ statusCode: 404, statusMessage: `Ref not found: ${branch}` }) } + if (cached) return cached - // Shared with the build-time snapshot, which walks the built commit instead of a branch — see - // `fetchLastContentCommit()`. One query, so the two cannot drift apart. let sha: string | undefined try { sha = await fetchLastContentCommit({ @@ -126,7 +102,7 @@ export async function resolveContentSha( throw createError({ statusCode: 404, statusMessage: `Content not found at ref: ${branch}` }) } - await refStorage.setItem(key, sha, { ttl: refTtl(branch) }) + await refStorage.setItem(key, sha, { ttl: PREVIEW_REF_TTL }) return sha } diff --git a/server/utils/global-config.ts b/server/utils/global-config.ts deleted file mode 100644 index 3f52fba..0000000 --- a/server/utils/global-config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { get } from '@vercel/global-config' - -/** Key looked up in the connected Global Config store for the pinned production content SHA. */ -const PINNED_SHA_KEY = 'contentSha' - -/** - * The content SHA pinned in Vercel Global Config, if any. - */ -export async function getPinnedSha(): Promise { - if (!process.env.GLOBAL_CONFIG) return undefined - try { - const sha = await get(PINNED_SHA_KEY) - return sha || undefined - } catch (error) { - console.error('[content] failed to read pinned SHA from Global Config', error) - return undefined - } -} diff --git a/server/utils/json.ts b/server/utils/json.ts deleted file mode 100644 index 9123ee9..0000000 --- a/server/utils/json.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { ContentListFile } from 'comark-content' - -/** Deterministic JSON (sorted object keys) for stable equality checks. */ -export function stableStringify(value: unknown): string { - if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null' - if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]` - const obj = value as Record - return `{${Object.keys(obj) - .sort() - .map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`) - .join(',')}}` -} - -/** Stable hash of a manifest item's visible metadata (its `data` — identity lives on `meta`). */ -export function hashManifestItem(item: ContentListFile | undefined): string { - if (!item) return '' - return stableStringify(item.data ?? {}) -} diff --git a/server/utils/preview.ts b/server/utils/preview.ts index 97e9cf9..feabe4a 100644 --- a/server/utils/preview.ts +++ b/server/utils/preview.ts @@ -1,11 +1,12 @@ -import type { DocsContent } from './content' +import type { ContentInstance } from '@nuxt/content/server' +import { content } from '../content' // Preview instances for `/blob/:sha`, `/tree/:branch` and `/pr/:number`. -const previews = new Map() +const previews = new Map() const MAX_PREVIEW_INSTANCES = 8 -function getPreviewContent(sha: string): DocsContent { +function getPreviewContent(sha: string): ContentInstance { const existing = previews.get(sha) if (existing) { previews.delete(sha) @@ -13,7 +14,7 @@ function getPreviewContent(sha: string): DocsContent { return existing } - const instance = contentAt(sha) + const instance = content.withRef(sha) previews.set(sha, instance) while (previews.size > MAX_PREVIEW_INSTANCES) { @@ -28,18 +29,15 @@ function getPreviewContent(sha: string): DocsContent { } /** - * Serve a preview request through the instance pinned to `sha`. + * Serve a preview request through the instance pinned to `sha`, or the live one when it serves `sha`. */ export async function servePreview(event: Parameters[0], sha: string, segment: string) { const request = toWebRequest(event) const url = new URL(request.url) - url.pathname = url.pathname.replace(segment, '') + // The content handler answers under `/__nuxt_content`. + url.pathname = url.pathname.replace(`/api/content${segment}`, '/__nuxt_content') const rewritten = new Request(url, request) - if (!getHeadSha() || sha === getHeadSha()) { - const instance = await getProdContent() - // Recheck after promise resolves. - if (sha === getHeadSha()) return instance.handler(rewritten) - } - return getPreviewContent(sha).handler(rewritten) + const live = await resolveContent(content) + return (live.ref === sha ? live : getPreviewContent(sha)).handler(rewritten) } diff --git a/server/utils/search.ts b/server/utils/search.ts index 9357bf3..ccdf923 100644 --- a/server/utils/search.ts +++ b/server/utils/search.ts @@ -1,4 +1,4 @@ -import type { DocsContent } from './content' +import type { ContentInstance } from '@nuxt/content/server' interface SearchSection { id: string @@ -17,19 +17,10 @@ interface SearchSection { // this file: bump it when the sections it builds change, or a deploy keeps serving the old ones. const SEARCH_SECTIONS_KEY = 'search-sections-v2' -/** - * Drop the cached index — the one case the per-SHA namespace can't cover: in dev the default - * instance watches the working tree, so content changes under a stable ref. Called from - * `watch:file:update`. - */ -export function invalidateSearchSections(content: DocsContent): void { - void content.cache.invalidate(SEARCH_SECTIONS_KEY).catch(() => {}) -} - /** * Keyword-score the search index against `query` and return the best sections. */ -export async function searchDocSections(content: DocsContent, query: string, limit = 10): Promise { +export async function searchDocSections(content: ContentInstance, query: string, limit = 10): Promise { const sections = await buildSearchSections(content) const terms = query.toLowerCase().split(/\s+/).filter(Boolean) @@ -51,7 +42,7 @@ export async function searchDocSections(content: DocsContent, query: string, lim } /** Walk every document's AST, one section per heading — the shape `UContentSearch` takes as `files`. */ -export async function buildSearchSections(content: DocsContent): Promise { +export async function buildSearchSections(content: ContentInstance): Promise { const cached = await content.cache.get(SEARCH_SECTIONS_KEY) if (cached) return cached @@ -61,7 +52,7 @@ export async function buildSearchSections(content: DocsContent): Promise { +async function collectSearchSections(content: ContentInstance): Promise { const docs = await content.list() const sections: SearchSection[] = [] diff --git a/server/utils/webhook.ts b/server/utils/webhook.ts index d08b8fb..5461696 100644 --- a/server/utils/webhook.ts +++ b/server/utils/webhook.ts @@ -1,69 +1,3 @@ -import { DEFAULT_CONTENT_NAME, type ContentListFile } from 'comark-content' -import type { GitHubCommit } from './github' -import { hashManifestItem } from './json' - -/** How a push changed the content source, already filtered to `contentDir`. */ -export interface ContentChanges { - /** Manifest keys (`default/`) of files added or modified. */ - upserted: string[] - /** Manifest keys of files removed — only the previous manifest can resolve their paths. */ - removed: string[] - /** A `.navigation.*` file changed, so the tree changed regardless of which pages did. */ - navTouched: boolean -} - -/** Files the content source can actually serve — matches the parsers installed in `content.ts`. */ -const CONTENT_EXTENSIONS = ['.md', '.yml', '.yaml', '.json'] - -/** The content instance's name (see `createBaseContent()` in `content.ts`) — unnamed, so `default`. */ -const SOURCE_NAME = DEFAULT_CONTENT_NAME - -/** - * A push's changed content files, named by their manifest key (`default/`) — the - * reverse of `meta.key`, so a diff against `manifest.items` doesn't need to re-derive file → URL - * mappings that comark already owns. - */ -export function changesForPush(contentDir: string, commits: GitHubCommit[]): ContentChanges { - const upserted = new Set() - const removed = new Set() - let navTouched = false - - const consider = (file: string, into: Set) => { - const key = manifestKeyFor(file, contentDir) - if (!key) return - - if (isNavConfigFile(file)) navTouched = true - else into.add(key) - } - - for (const commit of commits) { - for (const file of commit.added ?? []) consider(file, upserted) - for (const file of commit.modified ?? []) consider(file, upserted) - for (const file of commit.removed ?? []) consider(file, removed) - } - - // A path removed and re-added in the same push is an upsert, not a removal. - for (const key of upserted) removed.delete(key) - - return { upserted: [...upserted], removed: [...removed], navTouched } -} - -/** Repo-relative path → its key in the manifest, or `null` when it can't be a content file. */ -function manifestKeyFor(file: string, contentDir: string): string | null { - const dir = contentDir.replace(/^\/+|\/+$/g, '') - const prefix = dir ? `${dir}/` : '' - - if (prefix && !file.startsWith(prefix)) return null - if (!CONTENT_EXTENSIONS.some((ext) => file.toLowerCase().endsWith(ext))) return null - - return `${SOURCE_NAME}/${file.slice(prefix.length)}` -} - -/** Directory configuration (`.navigation.yml`), which contributes to the tree rather than a page. */ -function isNavConfigFile(file: string): boolean { - return /\.navigation\.(?:ya?ml|json)$/i.test(file) -} - /** * The payload URL a client-side navigation fetches for `path` */ @@ -71,47 +5,3 @@ export function payloadUrlForPage(path: string, buildId?: string): string { const base = path === '/' ? '/_payload.json' : `${path.replace(/\/$/, '')}/_payload.json` return buildId ? `${base}?_b=${buildId}` : base } - -/** `default/` (a manifest key) → page path, the reverse of what the path-keyed manifest gives. */ -export function indexByFileKey(items: Record): Map { - const index = new Map() - for (const item of Object.values(items)) index.set(item.meta.key, item.path) - return index -} - -/** - * Which pages a push changed, and whether the tree itself moved. - */ -export function diffContent( - changes: ContentChanges, - before: Record, - after: Record -): { pagePaths: string[]; navChanged: boolean } { - const pagePaths = new Set() - - const afterByKey = indexByFileKey(after) - const beforeByKey = indexByFileKey(before) - - for (const key of changes.upserted) { - const path = afterByKey.get(key) - if (path) pagePaths.add(path) - } - for (const key of changes.removed) { - const path = beforeByKey.get(key) - if (path) pagePaths.add(path) - } - - const beforeKeys = Object.keys(before) - const afterKeys = Object.keys(after) - const navChanged = - beforeKeys.length !== afterKeys.length || - afterKeys.some((key) => !before[key]) || - // Listing fields (title, description, icon, `navigation`…) are what the tree renders from. - afterKeys.some((key) => before[key] && !sameListing(before[key]!, after[key]!)) - - return { pagePaths: [...pagePaths], navChanged } -} - -function sameListing(a: ContentListFile, b: ContentListFile): boolean { - return a.path === b.path && hashManifestItem(a) === hashManifestItem(b) -} diff --git a/shared/types/build-content.ts b/shared/types/build-content.ts new file mode 100644 index 0000000..d1aa35f --- /dev/null +++ b/shared/types/build-content.ts @@ -0,0 +1,11 @@ +/** What `modules/config` finds from git at build, for `server/content.ts`. */ +export interface BuildContent { + owner: string + repo: string + branch: string + /** Relative to the repository root. */ + contentDir: string + /** Absolute, on the build machine: read in dev only. */ + contentPath: string + highlighterVersion: string +} diff --git a/test/content-contract.test.ts b/test/content-contract.test.ts index ef3a297..201cb49 100644 --- a/test/content-contract.test.ts +++ b/test/content-contract.test.ts @@ -2,39 +2,22 @@ * Contract test against the installed `comark-content`. * * Every other test here imports a pure function and never touches the package, - * which is how comark-content#77's `metaOnly` -> `partial` rename silently degraded - * the webhook's body warm-up. This exercises the surface the layer depends on. + * which is how comark-content#77's `metaOnly` -> `partial` rename went unnoticed. + * This exercises the surface the layer depends on. */ -import { mkdtemp, readFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import { comarkContent, DEFAULT_CONTENT_NAME, readArtifact } from 'comark-content' -import { writeSnapshots } from 'comark-content/build' import fsSource from 'comark-content/sources/fs' import forgeSource from 'comark-content/sources/forge' -import snapshot, { withSnapshot } from 'comark-content/sources/snapshot' import { createContentClient } from 'comark-content/client' -import { comarkContent as runtimeComarkContent, DEFAULT_CONTENT_NAME as RUNTIME_CONTENT_NAME, readArtifact as runtimeReadArtifact } from 'comark-content/runtime' -import sqliteWasm from 'comark-content/database/sqlite-wasm' -import sqliteFullTextSearch from 'comark-content/plugins/sqlite-full-text-search' import memoryDriver from 'unstorage/drivers/memory' const fixture = fileURLToPath(new URL('./fixtures/content-contract', import.meta.url)) -/** - * The warm-up options from `server/api/revalidate.post.ts` — keep the two in step. - * This object has to keep meaning "full init" on whichever build is installed. - */ +/** A full init, so the snapshot holds every body. */ const full = { partial: false } -/** - * `:` — the cache key comark-content writes a parsed body - * under. The prefix is the *instance* name, which defaults to `default`. - */ -const bodyKey = 'default:index.md' - function createFixtureContent() { return comarkContent({ source: fsSource(fixture), @@ -50,11 +33,6 @@ describe('comark-content contract', () => { fsSource, forgeSource, createContentClient, - runtimeComarkContent, - runtimeReadArtifact, - // Browser-only at runtime, but the subpaths resolve under node — enough to catch a rename. - sqliteWasm, - sqliteFullTextSearch, ]) { expect(typeof entry).toBe('function') } @@ -70,31 +48,11 @@ describe('comark-content contract', () => { expect(manifest.items['/']?.data?.title).toBe('Contract fixture') }) - it('writes parsed bodies to the cache on the revalidate warm-up init', async () => { - const content = createFixtureContent() - - // The metadata pass the webhook runs before responding (revalidate.post.ts:142). - await content.init() - // Without this the assertion below would pass even if the warm-up did nothing. - // `cache.keys` can't stand in — it is derived from the manifest, not the driver. - expect(await content.cache.get(bodyKey)).toBeNull() - - await content.init(full) - - // The one status spelled the same before and after the rename - // ('initialized-meta' -> 'initialized-partial'). - expect(content.status).toBe('initialized-full') - - const cached = await content.cache.get(bodyKey) - expect(cached).not.toBeNull() - expect(cached!.nodes.length).toBeGreaterThan(0) - }) - it('serves the manifest and snapshot artifacts through content.handler', async () => { const content = createFixtureContent() await content.init(full) - // The exact paths the search worker fetches and `modules/config/` declares ISR rules for. + // The per-commit paths the search worker loads, and `modules/config/` declares ISR rules for. for (const path of ['manifest.json', `snapshot/${DEFAULT_CONTENT_NAME}.json`]) { const response = await content.handler(new Request(`http://localhost/api/content/${path}`)) expect(response.status, path).toBe(200) @@ -103,117 +61,4 @@ describe('comark-content contract', () => { expect(Object.keys(await readArtifact(artifact)).length, path).toBeGreaterThan(0) } }) - - it('hydrates a sourceless instance from those artifacts', async () => { - const server = createFixtureContent() - await server.init(full) - - const fetchArtifact = async (path: string) => - await (await server.handler(new Request(`http://localhost/api/content/${path}`))).json() - - // The search feature is this round-trip, so a break here is a silently empty search index. - // `snapshot()`'s first argument is the full-body tier; the second (optional) manifest tier - // lets a bare `init()` skip downloading bodies until a document is actually requested. - const client = comarkContent({ - source: snapshot( - () => fetchArtifact(`snapshot/${DEFAULT_CONTENT_NAME}.json`), - () => fetchArtifact('manifest.json') - ), - }) - await client.init() - - expect(Object.keys((await client.manifest()).items)).toEqual(['/']) - - // Bodies have to arrive parsed: the client has no source to read a document from. - const doc = await client.get('/') - expect(doc?.data?.title).toBe('Contract fixture') - expect(doc?.nodes?.length).toBeGreaterThan(0) - }) - - it('hydrates a runtime-entry instance from those artifacts', async () => { - // `app/workers/search.ts` imports from `comark-content/runtime`, the parser-free entry. - // A snapshot-only instance must still hydrate there, and the name has to stay in step with - // the artifact paths the worker fetches. - expect(RUNTIME_CONTENT_NAME).toBe(DEFAULT_CONTENT_NAME) - - const server = createFixtureContent() - await server.init(full) - - const fetchArtifact = async (path: string) => - await (await server.handler(new Request(`http://localhost/api/content/${path}`))).json() - - const client = runtimeComarkContent({ - source: snapshot( - () => fetchArtifact(`snapshot/${RUNTIME_CONTENT_NAME}.json`), - () => fetchArtifact('manifest.json') - ), - }) - await client.init() - - expect(Object.keys((await client.manifest()).items)).toEqual(['/']) - const doc = await client.get('/') - expect(doc?.data?.title).toBe('Contract fixture') - expect(doc?.nodes?.length).toBeGreaterThan(0) - }) - - describe('build-time snapshot', () => { - /** - * `modules/snapshot/` writes it with `writeSnapshots()`, and - * `server/utils/content.ts` reads it back through a Nitro server asset. Three things here are - * layout, not behaviour, and all are silent when wrong: the per-instance subdirectory, the fact - * that a server asset hands back JSON *text*, and `manifest: false` suppressing the light tier - * the layer does not read. - */ - async function writeSnapshotFile() { - const dir = await mkdtemp(join(tmpdir(), 'comark-snapshot-')) - await writeSnapshots(createFixtureContent(), { dir, manifest: false }) - // One directory per instance, named after it — ours is unnamed, so `default`. - const read = (file: string) => readFile(join(dir, DEFAULT_CONTENT_NAME, file), 'utf8') - return { snapshot: () => read('snapshot.json'), manifest: () => read('manifest.json') } - } - - it('writes the snapshot alone when the manifest tier is off', async () => { - const stored = await writeSnapshotFile() - - await expect(stored.snapshot()).resolves.toContain('Contract fixture') - await expect(stored.manifest()).rejects.toThrow() - }) - - it('hydrates a withSnapshot instance from the snapshot without reading the source', async () => { - const stored = await writeSnapshotFile() - - // A source that throws on any read: hydrating from the snapshot must not touch it. This is the - // cold start being bought — in production the reads it stands in for are GitHub API calls. - const unreachable = { - ...fsSource(fixture), - keys: () => { - throw new Error('the origin was walked') - }, - } - - const content = comarkContent({ - source: withSnapshot(unreachable, stored.snapshot), - cache: { driver: memoryDriver() }, - }) - await content.init(full) - - expect(Object.keys((await content.manifest()).items)).toEqual(['/']) - const doc = await content.get('/') - expect(doc?.data?.title).toBe('Contract fixture') - expect(doc?.nodes?.length).toBeGreaterThan(0) - }) - - it('falls back to the source when no snapshot is stored', async () => { - // What every ref other than the build commit gets: loaders return `null`, so the origin is - // the only provider. A snapshot that cannot prove it belongs to this ref must never be used. - const content = comarkContent({ - source: withSnapshot(fsSource(fixture), () => null), - cache: { driver: memoryDriver() }, - }) - await content.init(full) - - expect(Object.keys((await content.manifest()).items)).toEqual(['/']) - expect((await content.get('/'))?.data?.title).toBe('Contract fixture') - }) - }) }) diff --git a/test/content-head.test.ts b/test/content-head.test.ts deleted file mode 100644 index 3cba512..0000000 --- a/test/content-head.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// `resolveProdSha` calls `getPinnedSha`, `targetBranch` and `resolveContentSha` as Nitro -// auto-imports (no explicit import in `content.ts`), so they're stubbed as globals here. -beforeEach(() => { - vi.resetModules() -}) - -afterEach(() => { - vi.unstubAllEnvs() - vi.unstubAllGlobals() -}) - -describe('resolveProdSha', () => { - it('shares the in-flight resolution across concurrent callers', async () => { - vi.stubEnv('VERCEL_ENV', 'production') - let pinCalls = 0 - let shaCalls = 0 - vi.stubGlobal('getPinnedSha', async () => { - pinCalls++ - await Promise.resolve() // force a tick so both calls land inside the same in-flight promise - return undefined - }) - vi.stubGlobal('targetBranch', () => 'main') - vi.stubGlobal('resolveContentSha', async () => { - shaCalls++ - return 'sha-1' - }) - - const { resolveProdSha } = await import('../server/utils/content') - - const [a, b] = await Promise.all([resolveProdSha(), resolveProdSha()]) - - expect(a).toBe('sha-1') - expect(b).toBe('sha-1') - expect(pinCalls).toBe(1) - expect(shaCalls).toBe(1) - }) - - it('resolves again once the in-flight promise has settled, so head can still advance', async () => { - vi.stubEnv('VERCEL_ENV', 'preview') // skips the pinned-config lookup, isolating resolveContentSha - const shas = ['sha-1', 'sha-2'] - vi.stubGlobal('targetBranch', () => 'main') - vi.stubGlobal('resolveContentSha', async () => shas.shift()) - - const { resolveProdSha } = await import('../server/utils/content') - - await expect(resolveProdSha()).resolves.toBe('sha-1') - await expect(resolveProdSha()).resolves.toBe('sha-2') - }) - - it('lets a failed resolution be retried instead of caching the rejection', async () => { - vi.stubEnv('VERCEL_ENV', 'preview') - vi.stubGlobal('targetBranch', () => 'main') - const resolveContentSha = vi.fn().mockRejectedValueOnce(new Error('rate limited')).mockResolvedValueOnce('sha-1') - vi.stubGlobal('resolveContentSha', resolveContentSha) - - const { resolveProdSha } = await import('../server/utils/content') - - await expect(resolveProdSha()).rejects.toThrow('rate limited') - await expect(resolveProdSha()).resolves.toBe('sha-1') - expect(resolveContentSha).toHaveBeenCalledTimes(2) - }) -}) diff --git a/test/e2e/push.test.ts b/test/e2e/push.test.ts new file mode 100644 index 0000000..31dcb9f --- /dev/null +++ b/test/e2e/push.test.ts @@ -0,0 +1,211 @@ +import { type ChildProcess, spawn } from 'node:child_process' +import { createHmac, randomBytes } from 'node:crypto' +import { mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { createServer, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { tmpdir } from 'node:os' +import { join, relative } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + +// The built playground on a GitHub answered by `test/fixtures/github-mock.mjs`: a push is a new commit in its state file. +const root = fileURLToPath(new URL('../..', import.meta.url)) +const entry = join(root, 'playground/.output/server/index.mjs') +const mock = join(root, 'test/fixtures/github-mock.mjs') +const REPO = 'comarkdown/comark-docs' +const SECRET = 'push-test-secret' +const CONFIGURATION = 'playground/content/1.getting-started/3.configuration.md' +const INSTALLATION = 'playground/content/1.getting-started/2.installation.md' + +interface Commit { sha: string; message: string; files: Record } + +function readTree(dir: string): Record { + const files: Record = {} + for (const name of readdirSync(dir)) { + const path = join(dir, name) + if (statSync(path).isDirectory()) Object.assign(files, readTree(path)) + else files[relative(root, path)] = readFileSync(path, 'utf8') + } + return files +} + +const stateDir = mkdtempSync(join(tmpdir(), 'comark-docs-push-')) +const statePath = join(stateDir, 'state.json') +const commits: Commit[] = [] + +function commit(message: string, change: (files: Record) => void): string { + const files = { ...commits.at(-1)?.files } + change(files) + const sha = createHmac('sha1', 'mock').update(`${commits.length}:${message}`).digest('hex') + commits.push({ sha, message, files }) + writeFileSync(statePath, JSON.stringify({ repo: REPO, branch: 'main', commits })) + return sha +} + +/** The requests the webhook sends to "its own deployment", which points at this recorder. */ +const recorded: string[] = [] +let recorder: Server +let server: ChildProcess +let baseURL: string +let recorderHost: string + +async function listen(target: Server): Promise { + await new Promise((resolve) => target.listen(0, '127.0.0.1', resolve)) + return (target.address() as AddressInfo).port +} + +async function freePort(): Promise { + const probe = createServer() + const port = await listen(probe) + await new Promise((resolve) => probe.close(resolve)) + return port +} + +async function push(modified: string[], removed: string[] = []) { + const body = JSON.stringify({ + ref: 'refs/heads/main', + repository: { full_name: REPO }, + commits: [{ added: [], removed, modified }], + }) + const signature = `sha256=${createHmac('sha256', SECRET).update(body).digest('hex')}` + recorded.length = 0 + const response = await fetch(`${baseURL}/api/revalidate`, { + method: 'POST', + body, + headers: { + 'content-type': 'application/json', + 'x-github-event': 'push', + 'x-hub-signature-256': signature, + 'x-forwarded-host': recorderHost, + }, + }) + expect(response.status, await response.clone().text()).toBe(200) + // The purge runs after the response: wait until no request arrived for a second. + let seen = -1 + while (seen !== recorded.length) { + seen = recorded.length + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + return [...recorded].sort() +} + +const head = async () => ((await (await fetch(`${baseURL}/api/content/head`)).json()) as { sha: string }).sha +const page = async (path: string) => (await fetch(`${baseURL}${path}`, { headers: { accept: 'text/html' } })).text() + +const GLOBALS = ['/llms-full.txt', '/llms.txt', '/rss.xml', '/sitemap.md', '/sitemap.xml'].map((path) => `purge ${path}`) +const warm = (sha: string) => [`warm /api/content/blob/${sha}/manifest.json`, `warm /api/content/blob/${sha}/snapshot/default.json`] +const pagePurges = (path: string) => [ + `purge ${path}`, + `purge ${path === '/' ? '' : path}/_payload.json?_b=`, + `purge /raw${path === '/' ? '/index' : path}.md`, +] + +describe('a push to the production branch', () => { + const first = commit('initial', (files) => Object.assign(files, readTree(join(root, 'playground/content')), { 'README.md': '# Docs' })) + + beforeAll(async () => { + recorder = createServer((req, res) => { + const kind = req.headers['x-prerender-revalidate'] === 'push-test-bypass' ? 'purge' : 'warm' + recorded.push(`${kind} ${req.url!.replace(/_b=[^&]+/, '_b=')}`) + res.setHeader('content-type', 'application/json') + res.end('{}') + }) + recorderHost = `127.0.0.1:${await listen(recorder)}` + + const port = await freePort() + baseURL = `http://127.0.0.1:${port}` + const { VERCEL_GIT_COMMIT_REF: _ref, ...env } = process.env + server = spawn(process.execPath, ['--import', mock, entry], { + env: { + ...env, + NUXT_APP_SECRET: randomBytes(32).toString('base64'), + GITHUB_MOCK_STATE: statePath, + GITHUB_TOKEN: 'mock-token', + NUXT_DOCS_GITHUB_BRANCH: 'main', + NUXT_DOCS_WEBHOOK_SECRET: SECRET, + NUXT_DOCS_BYPASS_TOKEN: 'push-test-bypass', + VERCEL_ENV: 'production', + HOST: '127.0.0.1', + PORT: String(port), + }, + stdio: ['ignore', 'inherit', 'inherit'], + }) + const deadline = Date.now() + 30_000 + while (!(await fetch(`${baseURL}/robots.txt`).catch(() => undefined))) { + if (Date.now() > deadline || server.exitCode !== null) throw new Error('The playground server did not start') + await new Promise((resolve) => setTimeout(resolve, 200)) + } + }) + + afterAll(() => { + server?.kill() + recorder?.close() + }) + + it('serves the last commit touching the content directory', async () => { + expect(await head()).toBe(first) + expect(await page('/getting-started/configuration')).not.toContain('Pushed without a build.') + }) + + it('moves to a commit changing one page, and purges that page and the global indexes', async () => { + const second = commit('edit configuration', (files) => { + files[CONFIGURATION] += '\nPushed without a build.\n' + }) + + expect(await push([CONFIGURATION])).toEqual([...pagePurges('/getting-started/configuration'), ...GLOBALS, ...warm(second)].sort()) + expect(await head()).toBe(second) + expect(await page('/getting-started/configuration')).toContain('Pushed without a build.') + }) + + it('purges every page when a title changes', async () => { + const third = commit('rename installation', (files) => { + files[INSTALLATION] = files[INSTALLATION]!.replace(/^title: .*$/m, 'title: Setting up') + }) + + expect(await push([INSTALLATION])).toEqual([ + ...[ + '/', + '/concepts/architecture', + '/concepts/versioned-previews', + '/deployment/pr-preview-comments', + '/deployment/vercel', + '/getting-started/configuration', + '/getting-started/installation', + '/getting-started/introduction', + '/page', + '/pages/test', + '/writing/components', + '/writing/landing-page', + '/writing/markdown', + '/writing/navigation', + '/writing/pages', + ].flatMap(pagePurges), + // `.navigation.yml` files are documents too, with no raw markdown twin. + ...['/concepts', '/deployment', '/getting-started', '/pages', '/writing'].flatMap((dir) => pagePurges(`${dir}/.navigation`).slice(0, 2)), + ...GLOBALS, + ...warm(third), + ].sort()) + expect(await head()).toBe(third) + expect(await page('/getting-started/configuration')).toContain('Setting up') + }) + + it('stops serving a deleted page, and purges it', async () => { + commit('delete a page', (files) => { + delete files['playground/content/pages/test.md'] + }) + + expect(await push([], ['playground/content/pages/test.md'])).toEqual(expect.arrayContaining(pagePurges('/pages/test'))) + const response = await fetch(`${baseURL}/pages/test`, { headers: { accept: 'text/html' } }) + expect(response.status).toBe(404) + }) + + it('leaves the served commit alone for a push that changes no content', async () => { + const served = await head() + commit('code only', (files) => { + files['README.md'] = '# Docs, edited' + }) + + expect(await push(['README.md'])).toEqual([]) + expect(await head()).toBe(served) + }) +}) diff --git a/test/e2e/routes.test.ts b/test/e2e/routes.test.ts index 21a84b7..8dfde5b 100644 --- a/test/e2e/routes.test.ts +++ b/test/e2e/routes.test.ts @@ -20,6 +20,12 @@ describe('pages', () => { }) // The sitemap protocol requires absolute URLs, on the canonical origin rather than the serving host. + // The link and the dates are built from the page's file name, extension included. + it('links each page to its file on GitHub', async () => { + const html = await fetchPath(INTRO_PAGE.path).then((res) => res.text()) + expect(html).toMatch(/\/edit\/[^"]+\/playground\/content\/1\.getting-started\/1\.introduction\.md"/) + }) + it('lists absolute URLs on the site origin', () => { const offsite = locs.filter((loc) => !loc.startsWith(`${SITE_URL}/`)) expect(offsite).toEqual([]) @@ -65,6 +71,13 @@ describe('agent routes', () => { expect(response.status, failure).toBe(200) }) + it('dates every page of the RSS feed from git', async () => { + const rss = await fetchPath('/rss.xml').then((res) => res.text()) + const items = rss.match(/[\s\S]*?<\/item>/g) ?? [] + expect(items.length).toBeGreaterThan(5) + expect(items.filter((item) => !item.includes(''))).toEqual([]) + }) + // Cached routes answer with a redirect to the `/raw` twin rather than a rewrite. it('negotiates markdown on a page URL', async () => { const { response, failure } = await fetchWithFailure(INTRO_PAGE.path, { accept: 'text/markdown' }) diff --git a/test/fixtures/github-mock.mjs b/test/fixtures/github-mock.mjs new file mode 100644 index 0000000..ad83eec --- /dev/null +++ b/test/fixtures/github-mock.mjs @@ -0,0 +1,126 @@ +// Loaded with `node --import` before the built server: answers GitHub from the repository in `GITHUB_MOCK_STATE`. +// The state file is read on every request, so a test pushes a commit by rewriting it. +import { createHash } from 'node:crypto' +import { readFileSync } from 'node:fs' + +/** + * @typedef {{ sha: string, message: string, files: Record }} MockCommit + * @typedef {{ repo: string, branch: string, commits: MockCommit[] }} MockState + */ + +const statePath = process.env.GITHUB_MOCK_STATE +if (!statePath) throw new Error('github-mock: set GITHUB_MOCK_STATE to the state file') + +const realFetch = globalThis.fetch + +/** @returns {MockState} The repository, as the test last wrote it. */ +const readState = () => JSON.parse(readFileSync(statePath, 'utf8')) + +const blobSha = (text) => { + const body = Buffer.from(text) + return createHash('sha1').update(`blob ${body.length}\0`).update(body).digest('hex') +} + +const json = (body, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }) + +const notFound = () => json({ message: 'Not Found' }, 404) + +/** Commits reachable from `ref`, newest first. */ +function history(state, ref) { + const index = ref === state.branch || ref === `refs/heads/${state.branch}` || ref === 'HEAD' + ? state.commits.length - 1 + : state.commits.findIndex((commit) => commit.sha === ref || (ref.length >= 7 && commit.sha.startsWith(ref))) + return index === -1 ? undefined : state.commits.slice(0, index + 1).reverse() +} + +const under = (file, path) => !path || file === path || file.startsWith(`${path}/`) + +/** Whether `commit` changed a file at or under `path`, compared with its parent. */ +function touches(commit, parent, path) { + const files = new Set([...Object.keys(commit.files), ...Object.keys(parent?.files ?? {})]) + return [...files].some((file) => under(file, path) && commit.files[file] !== parent?.files[file]) +} + +const apiCommit = (commit) => ({ + sha: commit.sha, + commit: { message: commit.message, author: { name: 'Mock', date: '2026-01-01T00:00:00Z' } }, + author: { login: 'mock' }, +}) + +function tree(commit, path) { + const prefix = path ? `${path}/` : '' + const entries = Object.entries(commit.files) + .filter(([file]) => under(file, path)) + .map(([file, text]) => ({ path: file.slice(prefix.length), mode: '100644', type: 'blob', sha: blobSha(text), size: Buffer.byteLength(text) })) + const dirs = new Set(entries.flatMap(({ path }) => path.split('/').slice(0, -1).map((_, i, parts) => parts.slice(0, i + 1).join('/')))) + return { + sha: createHash('sha1').update(JSON.stringify(entries)).digest('hex'), + truncated: false, + tree: [...[...dirs].map((dir) => ({ path: dir, mode: '040000', type: 'tree', sha: blobSha(dir) })), ...entries], + } +} + +function answer(url) { + const state = readState() + const [owner, name] = state.repo.split('/') + + if (url.hostname === 'raw.githubusercontent.com') { + const [, o, r, ref, ...rest] = decodeURIComponent(url.pathname).split('/') + if (o !== owner || r !== name) return notFound() + const text = history(state, ref)?.[0]?.files[rest.join('/')] + return text === undefined ? notFound() : new Response(text) + } + + const prefix = `/repos/${owner}/${name}` + if (url.hostname !== 'api.github.com') return undefined + if (!url.pathname.startsWith(`${prefix}/`)) return notFound() + const route = decodeURIComponent(url.pathname.slice(prefix.length)) + let match + + if (route === '/commits') { + const commits = history(state, url.searchParams.get('sha') || state.branch) + if (!commits) return notFound() + const path = (url.searchParams.get('path') ?? '').replace(/^\/+|\/+$/g, '') + const touching = commits.filter((commit, i) => touches(commit, commits[i + 1], path)) + return json(touching.slice(0, Number(url.searchParams.get('per_page') ?? 30)).map(apiCommit)) + } + + if (/^\/commits\/[^/]+\/pulls$/.test(route)) return json([]) + + if ((match = route.match(/^\/commits\/([^/]+)$/))) { + const commit = history(state, match[1])?.[0] + return commit ? json(apiCommit(commit)) : json({ message: 'No commit found' }, 422) + } + + if ((match = route.match(/^\/compare\/([^.]+(?:\.[^.]+)*)\.\.\.([^.]+)$/))) { + const base = history(state, match[1]) + const head = history(state, match[2])?.[0] + if (!base || !head) return notFound() + return json({ status: base[0].sha === head.sha ? 'identical' : base.some((c) => c.sha === head.sha) ? 'behind' : 'diverged' }) + } + + if ((match = route.match(/^\/git\/trees\/(.+)$/))) { + const [ref, path = ''] = match[1].split(':') + const commit = history(state, ref)?.[0] + return commit ? json(tree(commit, path.replace(/^\/+|\/+$/g, ''))) : notFound() + } + + if ((match = route.match(/^\/contents\/(.+)$/))) { + const commit = history(state, url.searchParams.get('ref') || state.branch)?.[0] + const text = commit?.files[match[1]] + if (text === undefined) return notFound() + return json({ type: 'file', path: match[1], sha: blobSha(text), encoding: 'base64', content: Buffer.from(text).toString('base64') }) + } + + if (route === '' || route === '/') return json({ full_name: state.repo, default_branch: state.branch }) + + console.error(`[github-mock] unhandled ${url.href}`) + return notFound() +} + +globalThis.fetch = async (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (process.env.GITHUB_MOCK_LOG) console.error(`[github-mock] ${url.href}`) + return answer(url) ?? realFetch(input, init) +} diff --git a/test/git.test.ts b/test/git.test.ts index 7728da7..f11f451 100644 --- a/test/git.test.ts +++ b/test/git.test.ts @@ -1,9 +1,5 @@ -import { execFileSync } from 'node:child_process' -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { getLastCommit, getTreeSha, hasParent, parseGitRemote } from '../utils/git' +import { describe, expect, it } from 'vitest' +import { parseGitRemote } from '../utils/git' describe('parseGitRemote', () => { it('parses SSH remotes', () => { @@ -33,77 +29,3 @@ describe('parseGitRemote', () => { expect(parseGitRemote('/local/path/repo')).toBeUndefined() }) }) - - -describe('commit and tree helpers', () => { - let repo: string - - const run = (...args: string[]) => execFileSync('git', args, { cwd: repo, stdio: 'ignore' }) - const write = async (file: string, body: string) => { - await mkdir(dirname(join(repo, file)), { recursive: true }) - await writeFile(join(repo, file), body, 'utf8') - } - - beforeEach(async () => { - repo = await mkdtemp(join(tmpdir(), 'comark-git-')) - run('init', '-q', '-b', 'main') - run('config', 'user.email', 'test@example.com') - run('config', 'user.name', 'Test') - - await write('content/index.md', '# one\n') - run('add', '-A') - run('commit', '-qm', 'add content') - - // A later commit that leaves `content/` untouched, so HEAD is not the last content commit. - await write('src/app.ts', 'export const a = 1\n') - run('add', '-A') - run('commit', '-qm', 'add code') - }) - - afterEach(async () => { - await rm(repo, { recursive: true, force: true }) - }) - - it('finds the last commit touching a directory, not HEAD', () => { - const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim() - const last = getLastCommit(repo, 'content') - - expect(last).toMatch(/^[0-9a-f]{40}$/) - expect(last).not.toBe(head) - }) - - it('returns the same tree for a ref whose content matches HEAD', () => { - // The whole safety property of the build-time snapshot: the commit it is labelled with has to hold - // the content that was parsed. Here the code commit did not touch `content/`, so both agree. - const last = getLastCommit(repo, 'content')! - expect(getTreeSha(repo, last, 'content')).toBe(getTreeSha(repo, 'HEAD', 'content')) - }) - - it('returns a different tree once the content changes', async () => { - const before = getTreeSha(repo, 'HEAD', 'content')! - - await write('content/index.md', '# two\n') - run('add', '-A') - run('commit', '-qm', 'edit content') - - expect(getTreeSha(repo, 'HEAD', 'content')).not.toBe(before) - // A stale label is what the snapshot must never be written under. - expect(getTreeSha(repo, 'HEAD~1', 'content')).toBe(before) - }) - - it('returns undefined for a ref or path outside the checkout', () => { - expect(getTreeSha(repo, 'HEAD', 'nope')).toBeUndefined() - expect(getTreeSha(repo, 'a'.repeat(40), 'content')).toBeUndefined() - expect(getLastCommit(repo, 'nope')).toBeUndefined() - }) - - it('reports a missing parent at the root commit', () => { - const root = execFileSync('git', ['rev-list', '--max-parents=0', 'HEAD'], { - cwd: repo, - encoding: 'utf8', - }).trim() - - expect(hasParent(repo, 'HEAD')).toBe(true) - expect(hasParent(repo, root)).toBe(false) - }) -}) diff --git a/test/github.test.ts b/test/github.test.ts index 24c4904..619473e 100644 --- a/test/github.test.ts +++ b/test/github.test.ts @@ -34,15 +34,4 @@ describe('resolveContentSha', () => { await expect(resolveContentSha('test/cache-key', 'api/content')).resolves.toBe('api-sha') expect(fetch).toHaveBeenCalledTimes(2) }) - - it('can refresh a cached content revision for the push webhook', async () => { - const fetch = vi.fn().mockResolvedValueOnce(commits('before')).mockResolvedValueOnce(commits('after')) - vi.stubGlobal('fetch', fetch) - - await expect(resolveContentSha('test/refresh', 'docs/content')).resolves.toBe('before') - await expect(resolveContentSha('test/refresh', 'docs/content')).resolves.toBe('before') - await expect(resolveContentSha('test/refresh', 'docs/content', { refresh: true })).resolves.toBe('after') - await expect(resolveContentSha('test/refresh', 'docs/content')).resolves.toBe('after') - expect(fetch).toHaveBeenCalledTimes(2) - }) }) diff --git a/test/global-config.test.ts b/test/global-config.test.ts deleted file mode 100644 index 3435950..0000000 --- a/test/global-config.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { get } = vi.hoisted(() => ({ get: vi.fn() })) -vi.mock('@vercel/global-config', () => ({ get })) - -afterEach(() => { - vi.unstubAllEnvs() - get.mockReset() -}) - -describe('getPinnedSha', () => { - it('returns undefined without reading the store when no Global Config is connected', async () => { - vi.stubEnv('GLOBAL_CONFIG', '') - const { getPinnedSha } = await import('../server/utils/global-config') - - await expect(getPinnedSha()).resolves.toBeUndefined() - expect(get).not.toHaveBeenCalled() - }) - - it('returns the pinned SHA when the store has one', async () => { - vi.stubEnv('GLOBAL_CONFIG', 'connection-string') - get.mockResolvedValue('abc123') - const { getPinnedSha } = await import('../server/utils/global-config') - - await expect(getPinnedSha()).resolves.toBe('abc123') - expect(get).toHaveBeenCalledWith('contentSha') - }) - - it('returns undefined when the key is unset', async () => { - vi.stubEnv('GLOBAL_CONFIG', 'connection-string') - get.mockResolvedValue(undefined) - const { getPinnedSha } = await import('../server/utils/global-config') - - await expect(getPinnedSha()).resolves.toBeUndefined() - }) - - it('falls back to undefined when the read fails', async () => { - vi.stubEnv('GLOBAL_CONFIG', 'connection-string') - get.mockRejectedValue(new Error('network error')) - const { getPinnedSha } = await import('../server/utils/global-config') - - await expect(getPinnedSha()).resolves.toBeUndefined() - }) -}) diff --git a/test/highlighter.test.ts b/test/highlighter.test.ts deleted file mode 100644 index 81737e3..0000000 --- a/test/highlighter.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { expect, it } from 'vitest' -import type { ComarkPlugin } from 'comark' -import fsSource from 'comark-content/sources/fs' -import { createBuildContentInstance } from '../utils/factory' -import defaultHighlighter from '../utils/highlighter' - -async function parse(highlighter: ComarkPlugin) { - const dir = await mkdtemp(join(tmpdir(), 'comark-docs-highlighter-')) - try { - await writeFile(join(dir, 'index.md'), '```ts\nconst answer = 42\n```\n') - return JSON.stringify(await createBuildContentInstance({ source: fsSource(dir) }, highlighter).get('/')) - } finally { - await rm(dir, { recursive: true, force: true }) - } -} - -// `comarkDocs.highlighter` replaces rangi: the plugin a site passes runs, and the default one doesn't. -it('highlights code blocks with the highlighter it is given', async () => { - const marker: ComarkPlugin = { - name: 'test-highlighter', - post({ tree }) { - const mark = (node: unknown) => { - if (!Array.isArray(node)) return - if (node[0] === 'pre') node[1] = { ...node[1], highlightedBy: 'test' } - node.slice(2).forEach(mark) - } - tree.nodes.forEach(mark) - }, - } - const custom = await parse(marker) - expect(custom).toContain('"highlightedBy":"test"') - expect(custom).not.toContain('#c41562') - - // Geist's keyword color, so the default is rangi with the layer's theme. - expect(await parse(defaultHighlighter)).toContain('#c41562') -}) diff --git a/test/json.test.ts b/test/json.test.ts deleted file mode 100644 index 1ab0ada..0000000 --- a/test/json.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { hashManifestItem, stableStringify } from '../server/utils/json' -import type { ContentListFile } from 'comark-content' - -describe('stableStringify', () => { - it('sorts object keys so equal content compares equal', () => { - expect(stableStringify({ b: 1, a: 2 })).toBe(stableStringify({ a: 2, b: 1 })) - expect(stableStringify({ b: 1, a: 2 })).toBe('{"a":2,"b":1}') - }) - - it('sorts nested keys too', () => { - expect(stableStringify({ x: { d: 1, c: 2 } })).toBe('{"x":{"c":2,"d":1}}') - }) - - it('preserves array order — position is meaningful', () => { - expect(stableStringify([3, 1, 2])).toBe('[3,1,2]') - }) - - it('handles primitives and null', () => { - expect(stableStringify(null)).toBe('null') - expect(stableStringify(1)).toBe('1') - expect(stableStringify('x')).toBe('"x"') - expect(stableStringify(true)).toBe('true') - }) - - it('emits null for values JSON.stringify drops', () => { - expect(stableStringify(undefined)).toBe('null') - }) -}) - -describe('hashManifestItem', () => { - const item = (data: Record) => ({ data }) as unknown as ContentListFile - - it('is stable across key order — this decides whether nav changed', () => { - expect(hashManifestItem(item({ title: 'A', description: 'B' }))).toBe( - hashManifestItem(item({ description: 'B', title: 'A' })) - ) - }) - - it('changes when visible metadata changes', () => { - expect(hashManifestItem(item({ title: 'A' }))).not.toBe(hashManifestItem(item({ title: 'B' }))) - }) - - it('treats a missing item and an empty one distinctly', () => { - expect(hashManifestItem(undefined)).toBe('') - expect(hashManifestItem(item({}))).toBe('{}') - }) -}) diff --git a/test/vercel/output.test.ts b/test/vercel/output.test.ts index 9e09990..c0a1c11 100644 --- a/test/vercel/output.test.ts +++ b/test/vercel/output.test.ts @@ -2,6 +2,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs' import { join, relative } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' +import { readArtifact } from 'comark-content' import { expectSelfContainedBundle } from '../server-bundle' const outputDir = fileURLToPath(new URL('../../playground/.vercel/output/', import.meta.url)) @@ -64,10 +65,10 @@ function filesIn(dir: string): string[] { .map((entry) => join(entry.parentPath, entry.name)) } -/** Nitro inlines each server asset as a raw chunk named after the asset, exporting its contents as a string. */ +/** Nitro inlines each server asset as a raw chunk named after the asset, exporting a content artifact as a string. */ async function readRawAsset(name: string): Promise { const chunk = (await import(join(serverDir, 'chunks/raw', `${name}.mjs`))) as { default: string } - return JSON.parse(chunk.default) as T + return (await readArtifact(JSON.parse(chunk.default))) as T } describe('routing', () => { @@ -113,8 +114,8 @@ describe('ISR', () => { expect(resolveFunction(path)?.expiration).toBe(expiration) }) - // Answers that must reflect the request: the webhook, the assistant stream, MCP and the pinned head commit. - it.each(['/api/revalidate', '/api/assistant', '/api/content/head', '/mcp'])('%s is not cached', (path) => { + // Answers that must reflect the request: the webhook, the assistant stream, MCP, and the content at the commit served. + it.each(['/api/revalidate', '/api/assistant', '/api/content/head', '/__nuxt_content/navigation', '/mcp'])('%s is not cached', (path) => { const resolved = resolveFunction(path) expect(resolved?.dest).toBeDefined() expect(resolved?.expiration).toBeUndefined() diff --git a/test/webhook.test.ts b/test/webhook.test.ts index 25cc85f..e9209d9 100644 --- a/test/webhook.test.ts +++ b/test/webhook.test.ts @@ -1,65 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { ContentListFile } from 'comark-content' -import type { GitHubCommit } from '../server/utils/github' -import { changesForPush, diffContent, indexByFileKey, payloadUrlForPage } from '../server/utils/webhook' - -const commit = (partial: GitHubCommit): GitHubCommit => partial - -describe('changesForPush', () => { - it('classifies added/modified/removed content files, keyed by their manifest key', () => { - const commits = [ - commit({ - added: ['content/1.guide/2.intro.md'], - modified: ['content/index.md'], - removed: ['content/old.md'], - }), - ] - expect(changesForPush('content', commits)).toEqual({ - upserted: ['default/1.guide/2.intro.md', 'default/index.md'], - removed: ['default/old.md'], - navTouched: false, - }) - }) - - it('ignores files outside the content dir', () => { - expect(changesForPush('content', [commit({ modified: ['README.md', 'other/content/x.md'] })])).toEqual({ - upserted: [], - removed: [], - navTouched: false, - }) - }) - - it('follows a nested content dir', () => { - expect(changesForPush('docs/content', [commit({ modified: ['docs/content/x.md'] })])).toEqual({ - upserted: ['default/x.md'], - removed: [], - navTouched: false, - }) - }) - - it('covers every parser extension, not just markdown', () => { - const commits = [commit({ added: ['content/data.yml', 'content/data.yaml', 'content/data.json'] })] - expect(changesForPush('content', commits).upserted).toEqual([ - 'default/data.yml', - 'default/data.yaml', - 'default/data.json', - ]) - }) - - it('flags a navigation config file instead of collecting it', () => { - const commits = [commit({ modified: ['content/1.guide/.navigation.yml'] })] - expect(changesForPush('content', commits)).toEqual({ upserted: [], removed: [], navTouched: true }) - }) - - it('treats a path removed and re-added in the same push as an upsert', () => { - const commits = [commit({ added: ['content/index.md'], removed: ['content/index.md'] })] - expect(changesForPush('content', commits)).toEqual({ - upserted: ['default/index.md'], - removed: [], - navTouched: false, - }) - }) -}) +import { payloadUrlForPage } from '../server/utils/webhook' describe('payloadUrlForPage', () => { it('matches the `_b` query param Nuxt requests (`nuxt/dist/app/composables/payload.js`)', () => { @@ -69,44 +9,3 @@ describe('payloadUrlForPage', () => { expect(payloadUrlForPage('/', 'abc123')).toBe('/_payload.json?_b=abc123') }) }) - -describe('indexByFileKey', () => { - it('maps a manifest key back to its page path', () => { - const items: Record = { - '/guide/intro': { path: '/guide/intro', data: {}, meta: { key: 'content/1.guide/2.intro.md' } } as never, - } - expect(indexByFileKey(items).get('content/1.guide/2.intro.md')).toBe('/guide/intro') - }) -}) - -describe('diffContent', () => { - const file = (path: string, key: string, data: Record = {}): ContentListFile => - ({ path, data, meta: { key } }) as never - - it('resolves upserted/removed manifest keys to page paths', () => { - const before = { '/old': file('/old', 'content/old.md') } - const after = { '/guide/intro': file('/guide/intro', 'content/1.guide/2.intro.md') } - const changes = { upserted: ['content/1.guide/2.intro.md'], removed: ['content/old.md'], navTouched: false } - expect(diffContent(changes, before, after).pagePaths.sort()).toEqual(['/guide/intro', '/old']) - }) - - it('flags navChanged when a page is added or removed', () => { - const before = { '/a': file('/a', 'content/a.md') } - const after = { '/a': file('/a', 'content/a.md'), '/b': file('/b', 'content/b.md') } - expect(diffContent({ upserted: [], removed: [], navTouched: false }, before, after).navChanged).toBe(true) - }) - - it('flags navChanged when listing data changes, even with the same page set', () => { - const before = { '/a': file('/a', 'content/a.md', { title: 'A' }) } - const after = { '/a': file('/a', 'content/a.md', { title: 'B' }) } - expect(diffContent({ upserted: [], removed: [], navTouched: false }, before, after).navChanged).toBe(true) - }) - - it('does not flag navChanged when nothing listing-relevant moved', () => { - const before = { '/a': file('/a', 'content/a.md', { title: 'A' }) } - const after = { '/a': file('/a', 'content/a.md', { title: 'A' }) } - expect(diffContent({ upserted: ['content/a.md'], removed: [], navTouched: false }, before, after).navChanged).toBe( - false - ) - }) -}) diff --git a/utils/factory.ts b/utils/factory.ts deleted file mode 100644 index 472ae01..0000000 --- a/utils/factory.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { Tracer } from '@opentelemetry/api' -import type { ComarkPlugin } from 'comark' -import { type ContentOptions, comarkContent } from 'comark-content' -import markdown from 'comark-content/plugins/markdown' -import yaml from 'comark-content/plugins/yaml' -import tracingOtel from 'comark-content/plugins/tracing/otel' -import security from 'comark/plugins/security' -import emoji from 'comark/plugins/emoji' -import toc from 'comark/plugins/toc' -import mermaid from 'comark/plugins/mermaid' -import { contentTracer } from '../server/utils/tracer.ts' - -/** Frontmatter kept in the manifest, so `list()` and `navigation()` render without reading bodies. */ -const LISTING_FIELDS = ['title', 'description', 'navigation', 'icon', 'layout'] - -// Bump CONTENT_PARSER_VERSION in `server/utils/cache.ts` when these plugins or their options change cached output. -// The highlighter is the site's choice (`comarkDocs.highlighter`), so it is passed in. -const comarkPlugins = (highlighter: ComarkPlugin) => [ - mermaid({ theme: 'zinc-light', themeDark: 'zinc-dark' }), - highlighter, - toc({ depth: 3 }), - emoji(), - security({ - blockedTags: ['script', 'iframe', 'embed', 'form', 'base', 'meta', 'link', 'style'], - allowDataImages: false, - }), -] - -/** - * The parser, in one place for: - * - The build-time snapshot - * - The runtime instance - */ -function create(options: Pick, highlighter: ComarkPlugin, tracer?: Tracer) { - return comarkContent({ - source: options.source, - plugins: [ - markdown({ - comark: { plugins: comarkPlugins(highlighter) }, - listingFields: LISTING_FIELDS, - }), - yaml({ listingFields: LISTING_FIELDS }), - tracer && tracingOtel({ tracer }), - ], - cache: options.cache, - basePath: options.basePath, - }) -} - -/** An instance serving requests: traced, and cached per content SHA. */ -export function createRuntimeContentInstance( - options: Pick, - highlighter: ComarkPlugin, -) { - return create(options, highlighter, contentTracer()) -} - -/** - * The throwaway instance the build-time snapshot is parsed with (`modules/snapshot/`). - */ -export function createBuildContentInstance(options: Pick, highlighter: ComarkPlugin) { - return create(options, highlighter) -} diff --git a/utils/git.ts b/utils/git.ts index e323fa6..de238e2 100644 --- a/utils/git.ts +++ b/utils/git.ts @@ -73,32 +73,3 @@ export function getGitEnv(): GitInfo | undefined { return { name, owner, url: `https://${provider || 'github'}.com/${owner}/${name}` } } - -/** - * The last commit touching `dir`, or `undefined`. - * - * Unverified on purpose. CI clones shallowly, and when the last commit touching `dir` predates the - * fetched window git answers with the shallow boundary commit rather than nothing — at depth 1, - * that is HEAD for every path. Confirm the answer with {@link getTreeSha} before trusting it to - * name a commit's content. - */ -export function getLastCommit(cwd: string, dir: string): string | undefined { - const sha = git(['log', '-1', '--format=%H', '--', dir], cwd) - return sha && /^[0-9a-f]{40}$/.test(sha) ? sha : undefined -} - -/** Tree object id of `:`, or `undefined` when the ref or the path is not in this checkout. */ -export function getTreeSha(cwd: string, ref: string, dir: string): string | undefined { - return git(['rev-parse', `${ref}:${dir}`], cwd) -} - -/** Whether `ref` has a parent in this checkout. `false` at a shallow-clone boundary. */ -export function hasParent(cwd: string, ref: string): boolean { - return Boolean(git(['rev-parse', '--verify', `${ref}^`], cwd)) -} - -/** The commit checked out here, falling back to the CI-provided one. */ -export function headCommit(cwd: string): string | undefined { - const sha = git(['rev-parse', 'HEAD'], cwd) || process.env.VERCEL_GIT_COMMIT_SHA - return sha && /^[0-9a-f]{40}$/.test(sha) ? sha : undefined -}