nuxt-ai-ready 3.6.1 → 3.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-skills-config-CmZq9uWW.mjs +18 -0
- package/dist/agent-skills-zGLgFB6H.mjs +468 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +656 -570
- package/dist/devtools/pages/ai-ready/debug.vue +9 -3
- package/dist/devtools/pages/ai-ready/index.vue +3 -1
- package/dist/devtools/pages/ai-ready/llms-txt.vue +15 -4
- package/dist/devtools/pages/ai-ready.vue +28 -4
- package/dist/module.d.mts +106 -112
- package/dist/module.json +3 -3
- package/dist/module.mjs +2732 -26
- package/dist/package-metadata-B1darl8W.mjs +28 -0
- package/dist/prerender-QMv07W4h.mjs +650 -0
- package/dist/runtime/app/composables/webmcp.js +90 -97
- package/dist/runtime/app/plugins/md-alternate.server.js +29 -26
- package/dist/runtime/app/plugins/md-hints.prerender.js +13 -15
- package/dist/runtime/app/plugins/webmcp.client.js +49 -53
- package/dist/runtime/app/webmcp-config.js +2 -2
- package/dist/runtime/cache-control.js +16 -10
- package/dist/runtime/i18n-url.js +6 -6
- package/dist/runtime/index.js +4 -12
- package/dist/runtime/llms-txt-directive.js +20 -13
- package/dist/runtime/llms-txt-files.js +188 -187
- package/dist/runtime/llms-txt-format.js +54 -55
- package/dist/runtime/llms-txt-i18n.js +22 -19
- package/dist/runtime/llms-txt-utils.js +140 -95
- package/dist/runtime/markdown-links.js +45 -39
- package/dist/runtime/markdown-path.js +29 -9
- package/dist/runtime/markdown-text.js +2 -1
- package/dist/runtime/mcp.js +5 -1
- package/dist/runtime/route-path.js +14 -8
- package/dist/runtime/server/db/drizzle/client.js +71 -75
- package/dist/runtime/server/db/drizzle/index.js +16 -28
- package/dist/runtime/server/db/drizzle/providers/bun.d.ts +2 -1
- package/dist/runtime/server/db/drizzle/providers/bun.js +10 -7
- package/dist/runtime/server/db/drizzle/providers/d1.js +16 -13
- package/dist/runtime/server/db/drizzle/providers/dbPath.js +60 -37
- package/dist/runtime/server/db/drizzle/providers/libsql.js +23 -11
- package/dist/runtime/server/db/drizzle/providers/neon.js +13 -10
- package/dist/runtime/server/db/drizzle/providers/node-sqlite.js +10 -7
- package/dist/runtime/server/db/drizzle/providers/postgres.js +13 -10
- package/dist/runtime/server/db/drizzle/queries.js +633 -532
- package/dist/runtime/server/db/drizzle/raw.js +200 -176
- package/dist/runtime/server/db/index.js +3 -0
- package/dist/runtime/server/db/queries.js +816 -607
- package/dist/runtime/server/db/schema/postgres.js +56 -50
- package/dist/runtime/server/db/schema/sqlite.js +56 -50
- package/dist/runtime/server/db/schema-sql.js +35 -38
- package/dist/runtime/server/db/seed.js +60 -45
- package/dist/runtime/server/db/shared.js +300 -213
- package/dist/runtime/server/index.js +1 -17
- package/dist/runtime/server/mcp/cache-key.js +5 -1
- package/dist/runtime/server/mcp/resources/pages.js +32 -33
- package/dist/runtime/server/mcp/tools/get-page-markdown.js +41 -27
- package/dist/runtime/server/mcp/tools/list-pages.js +40 -34
- package/dist/runtime/server/mcp/tools/search-pages.js +24 -16
- package/dist/runtime/server/middleware/markdown.d.ts +1 -1
- package/dist/runtime/server/middleware/markdown.js +15 -13
- package/dist/runtime/server/middleware/markdown.prerender.d.ts +1 -1
- package/dist/runtime/server/middleware/markdown.prerender.js +135 -119
- package/dist/runtime/server/middleware/render-markdown.d.ts +1 -1
- package/dist/runtime/server/middleware/render-markdown.js +164 -144
- package/dist/runtime/server/plugins/ai-terms.d.ts +1 -1
- package/dist/runtime/server/plugins/ai-terms.js +4 -8
- package/dist/runtime/server/plugins/content-signal-capture-nitro3.prerender.d.ts +1 -1
- package/dist/runtime/server/plugins/content-signal-capture-nitro3.prerender.js +7 -8
- package/dist/runtime/server/plugins/content-signal-capture.prerender.d.ts +1 -1
- package/dist/runtime/server/plugins/content-signal-capture.prerender.js +7 -7
- package/dist/runtime/server/plugins/db-lifecycle-nitro3.d.ts +1 -1
- package/dist/runtime/server/plugins/db-lifecycle-nitro3.js +13 -14
- package/dist/runtime/server/plugins/db-lifecycle.js +13 -11
- package/dist/runtime/server/plugins/html-capture.prerender.js +6 -6
- package/dist/runtime/server/plugins/link-header-nitro3.d.ts +1 -1
- package/dist/runtime/server/plugins/link-header-nitro3.js +23 -13
- package/dist/runtime/server/plugins/link-header.d.ts +1 -1
- package/dist/runtime/server/plugins/link-header.js +30 -30
- package/dist/runtime/server/plugins/llms-txt-directive-html.d.ts +1 -1
- package/dist/runtime/server/plugins/llms-txt-directive-html.js +4 -3
- package/dist/runtime/server/plugins/markdown-negotiation.d.ts +1 -1
- package/dist/runtime/server/plugins/markdown-negotiation.js +64 -45
- package/dist/runtime/server/plugins/sitemap-seeder.js +144 -112
- package/dist/runtime/server/routes/__ai-ready/cron.get.d.ts +1 -1
- package/dist/runtime/server/routes/__ai-ready/cron.get.js +17 -11
- package/dist/runtime/server/routes/__ai-ready/devtools.get.d.ts +1 -1
- package/dist/runtime/server/routes/__ai-ready/devtools.get.js +60 -45
- package/dist/runtime/server/routes/__ai-ready/pages.get.d.ts +36 -1
- package/dist/runtime/server/routes/__ai-ready/pages.get.js +44 -40
- package/dist/runtime/server/routes/__ai-ready/poll.post.d.ts +15 -1
- package/dist/runtime/server/routes/__ai-ready/poll.post.js +30 -30
- package/dist/runtime/server/routes/__ai-ready/prune.post.d.ts +13 -1
- package/dist/runtime/server/routes/__ai-ready/prune.post.js +29 -15
- package/dist/runtime/server/routes/__ai-ready/reindex.post.d.ts +22 -1
- package/dist/runtime/server/routes/__ai-ready/reindex.post.js +31 -21
- package/dist/runtime/server/routes/__ai-ready/restore.post.d.ts +4 -1
- package/dist/runtime/server/routes/__ai-ready/restore.post.js +28 -22
- package/dist/runtime/server/routes/__ai-ready/status.get.d.ts +1 -1
- package/dist/runtime/server/routes/__ai-ready/status.get.js +52 -53
- package/dist/runtime/server/routes/__ai-ready-debug.get.d.ts +83 -1
- package/dist/runtime/server/routes/__ai-ready-debug.get.js +209 -189
- package/dist/runtime/server/routes/agent-skills-artifact.d.ts +1 -1
- package/dist/runtime/server/routes/agent-skills-artifact.js +16 -14
- package/dist/runtime/server/routes/agent-skills-index.d.ts +1 -1
- package/dist/runtime/server/routes/agent-skills-index.js +8 -6
- package/dist/runtime/server/routes/ai-catalog.js +19 -19
- package/dist/runtime/server/routes/ai-terms.js +23 -19
- package/dist/runtime/server/routes/api-catalog.js +23 -23
- package/dist/runtime/server/routes/llms-full.txt.get.d.ts +1 -1
- package/dist/runtime/server/routes/llms-full.txt.get.js +42 -41
- package/dist/runtime/server/routes/llms.txt.get.d.ts +1 -1
- package/dist/runtime/server/routes/llms.txt.get.js +38 -33
- package/dist/runtime/server/routes/mcp-server-card.js +19 -19
- package/dist/runtime/server/routes/sitemap.md.get.d.ts +1 -1
- package/dist/runtime/server/routes/sitemap.md.get.js +38 -39
- package/dist/runtime/server/tasks/ai-ready-cron.d.ts +1 -1
- package/dist/runtime/server/tasks/ai-ready-cron.js +17 -14
- package/dist/runtime/server/utils/auth.js +76 -53
- package/dist/runtime/server/utils/batchIndex.js +72 -60
- package/dist/runtime/server/utils/checkStale.js +181 -134
- package/dist/runtime/server/utils/cloudflare-prerendered.js +23 -20
- package/dist/runtime/server/utils/cloudflare.js +69 -51
- package/dist/runtime/server/utils/content-negotiation.js +30 -18
- package/dist/runtime/server/utils/content.js +4 -1
- package/dist/runtime/server/utils/context.js +30 -19
- package/dist/runtime/server/utils/cron-plan.js +6 -6
- package/dist/runtime/server/utils/discovery-response.js +5 -6
- package/dist/runtime/server/utils/fetch.js +2 -1
- package/dist/runtime/server/utils/frontmatter.js +44 -57
- package/dist/runtime/server/utils/i18n.js +3 -8
- package/dist/runtime/server/utils/indexPage.js +152 -113
- package/dist/runtime/server/utils/keywords.js +278 -277
- package/dist/runtime/server/utils/link-header.js +67 -56
- package/dist/runtime/server/utils/llms-full.js +39 -49
- package/dist/runtime/server/utils/markdown-redirect.js +26 -14
- package/dist/runtime/server/utils/markdown-request.js +62 -47
- package/dist/runtime/server/utils/negotiation-decision.d.ts +8 -0
- package/dist/runtime/server/utils/negotiation-decision.js +106 -34
- package/dist/runtime/server/utils/negotiation-response.d.ts +1 -1
- package/dist/runtime/server/utils/negotiation-response.js +195 -144
- package/dist/runtime/server/utils/page-updated-at.js +23 -15
- package/dist/runtime/server/utils/prerender-html.js +31 -17
- package/dist/runtime/server/utils/runCron.js +263 -192
- package/dist/runtime/server/utils/sitemap-crawl-state.js +57 -39
- package/dist/runtime/server/utils/sitemap-lastmod.js +16 -14
- package/dist/runtime/server/utils/sitemap-md.js +39 -50
- package/dist/runtime/server/utils/sitemap-routes.js +7 -7
- package/dist/runtime/server/utils/sitemap.js +459 -414
- package/dist/runtime/server/utils.js +141 -122
- package/dist/runtime/site-tool-catalog.js +39 -43
- package/dist/runtime/site-tool-config.js +1 -0
- package/dist/runtime/sync-secret.js +11 -11
- package/dist/runtime/types.js +1 -0
- package/dist/runtime/webmcp-site-tools.js +278 -250
- package/dist/runtime/webmcp.js +53 -42
- package/dist/static-headers-G7hFL3wE.mjs +328 -0
- package/dist/types.d.mts +1 -9
- package/package.json +18 -22
- package/skills/nuxt-ai-ready/SKILL.md +8 -2
- package/dist/chunks/agent-skills.mjs +0 -383
- package/dist/chunks/prerender.mjs +0 -683
- package/dist/shared/nuxt-ai-ready.Bzx0dNWj.mjs +0 -3034
- package/dist/shared/nuxt-ai-ready.DCd-1s1G.mjs +0 -29
|
@@ -1,3034 +0,0 @@
|
|
|
1
|
-
import { readFile, access, mkdir, mkdtemp, writeFile, rename, rm } from 'node:fs/promises';
|
|
2
|
-
import { createRequire } from 'node:module';
|
|
3
|
-
import { dirname, basename, join, resolve, relative } from 'node:path';
|
|
4
|
-
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
|
-
import { hasNuxtModule, useNuxt, useLogger, addTypeTemplate, addTemplate, defineNuxtModule, createResolver, getLayerDirectories, tryResolveModule, directoryToURL, addServerImports, addServerHandler, extendRouteRules, getNitroVersion, addPlugin, addNitroPlugin, addImports } from '@nuxt/kit';
|
|
6
|
-
import defu$1, { defu } from 'defu';
|
|
7
|
-
import { useSiteConfig, withSiteUrl } from 'nuxt-site-config/kit';
|
|
8
|
-
import { resolveNuxtContentVersion, renderNitroTypeAugmentations, setupRuntimeAliases, setupNitroRuntimeCompatibility, isAgent, isCI } from 'nuxtseo-shared/kit';
|
|
9
|
-
import { createNitroRouteRuleMatcher } from 'nuxtseo-shared/server';
|
|
10
|
-
import { decodePath } from 'ufo';
|
|
11
|
-
import { r as readPackageMetadata, a as resolvePackageMetadataPath } from './nuxt-ai-ready.DCd-1s1G.mjs';
|
|
12
|
-
import { AI_TERMS_PATH } from '../../dist/runtime/ai-terms.js';
|
|
13
|
-
import { parseLlmsTxtConfig } from '../../dist/runtime/llms-txt-files.js';
|
|
14
|
-
import { toDeployedRoute } from '../../dist/runtime/route-path.js';
|
|
15
|
-
import { SITEMAP_MD_ROUTE } from '../../dist/runtime/server/utils/sitemap-md.js';
|
|
16
|
-
import { LEGACY_RUNTIME_SYNC_SECRET_WARNING, deriveRuntimeSyncSecret } from '../../dist/runtime/sync-secret.js';
|
|
17
|
-
import { publicCacheControl, mergeVaryHeader } from '../../dist/runtime/cache-control.js';
|
|
18
|
-
import { createHash } from 'node:crypto';
|
|
19
|
-
import { MCP_SERVER_CARD_MEDIA_TYPE, AI_CATALOG_MEDIA_TYPE } from '../../dist/runtime/server/utils/discovery-response.js';
|
|
20
|
-
import { parseTOML, parseJSONC } from 'confbox';
|
|
21
|
-
import { hasMarkdownTwin, toMarkdownPath, normalizePagePath } from '../../dist/runtime/markdown-path.js';
|
|
22
|
-
import { getContentNegotiationVary, resolveContentNegotiation } from '../../dist/runtime/server/utils/content-negotiation.js';
|
|
23
|
-
import { isAbsolute, join as join$1 } from 'pathe';
|
|
24
|
-
import { resolveI18nConfig, toRuntimeI18nConfig as toRuntimeI18nConfig$1 } from 'nuxtseo-shared/i18n';
|
|
25
|
-
|
|
26
|
-
const SELECT_PAGE_DATA = "SELECT route, title, description, markdown, headings, keywords, updated_at, is_error, locale FROM ai_ready_pages";
|
|
27
|
-
function createBuildPageDataVirtual(options) {
|
|
28
|
-
if (options.dev) {
|
|
29
|
-
return `
|
|
30
|
-
export async function readPageDataFromFilesystem() { return { pages: [], errorRoutes: [] } }
|
|
31
|
-
export async function readMarkdownLinkAvailabilityFromFilesystem() { return { runtimeMarkdownAvailable: false, paths: [] } }
|
|
32
|
-
`;
|
|
33
|
-
}
|
|
34
|
-
const readRows = `const { DatabaseSync } = await import('node' + ':sqlite')
|
|
35
|
-
const db = new DatabaseSync(dbPath, { open: true })
|
|
36
|
-
const rows = db.prepare(${JSON.stringify(SELECT_PAGE_DATA)}).all()
|
|
37
|
-
db.close()`;
|
|
38
|
-
return `
|
|
39
|
-
export async function readMarkdownLinkAvailabilityFromFilesystem() {
|
|
40
|
-
if (!import.meta.prerender) {
|
|
41
|
-
return { runtimeMarkdownAvailable: false, paths: [] }
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const { readFile } = await import('node:fs/promises')
|
|
45
|
-
try {
|
|
46
|
-
const availability = JSON.parse(await readFile(${JSON.stringify(options.markdownLinkAvailabilityPath)}, 'utf8'))
|
|
47
|
-
return {
|
|
48
|
-
runtimeMarkdownAvailable: availability?.runtimeMarkdownAvailable === true,
|
|
49
|
-
paths: Array.isArray(availability?.paths) ? availability.paths.filter(path => typeof path === 'string') : [],
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
catch (error) {
|
|
53
|
-
console.warn('[nuxt-ai-ready] Failed to read Markdown link availability; keeping canonical links.', error)
|
|
54
|
-
return { runtimeMarkdownAvailable: false, paths: [] }
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export async function readPageDataFromFilesystem() {
|
|
59
|
-
if (!import.meta.prerender) {
|
|
60
|
-
return { pages: [], errorRoutes: [] }
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
const dbPath = ${JSON.stringify(options.buildDbPath)}
|
|
64
|
-
const { existsSync } = await import('node:fs')
|
|
65
|
-
if (!existsSync(dbPath)) {
|
|
66
|
-
return { pages: [], errorRoutes: [] }
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
${readRows}
|
|
70
|
-
|
|
71
|
-
const pages = rows.filter(r => !r.is_error).map(r => ({
|
|
72
|
-
route: r.route,
|
|
73
|
-
title: r.title,
|
|
74
|
-
description: r.description,
|
|
75
|
-
markdown: r.markdown,
|
|
76
|
-
headings: r.headings,
|
|
77
|
-
keywords: JSON.parse(r.keywords || '[]'),
|
|
78
|
-
updatedAt: r.updated_at,
|
|
79
|
-
locale: r.locale || '',
|
|
80
|
-
}))
|
|
81
|
-
const errorRoutes = rows.filter(r => r.is_error).map(r => r.route)
|
|
82
|
-
|
|
83
|
-
return { pages, errorRoutes }
|
|
84
|
-
}
|
|
85
|
-
`;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const COMARK_MODULE = "@harlan-zw/comark-content";
|
|
89
|
-
const COMARK_MINIMUM = [0, 1, 2];
|
|
90
|
-
async function comarkSatisfiesMinimum() {
|
|
91
|
-
const url = useNuxt().options.rootDir;
|
|
92
|
-
const pkg = await readPackageMetadata(COMARK_MODULE, url).catch(() => {
|
|
93
|
-
return null;
|
|
94
|
-
});
|
|
95
|
-
const parts = pkg?.version?.split(".").map((part) => Number.parseInt(part, 10));
|
|
96
|
-
if (!parts || parts.length < 3 || parts.some((part) => !Number.isFinite(part)))
|
|
97
|
-
return false;
|
|
98
|
-
for (const [index, minimum] of COMARK_MINIMUM.entries()) {
|
|
99
|
-
if (parts[index] !== minimum)
|
|
100
|
-
return parts[index] > minimum;
|
|
101
|
-
}
|
|
102
|
-
return true;
|
|
103
|
-
}
|
|
104
|
-
async function resolveContentSource(enabled) {
|
|
105
|
-
if (!enabled)
|
|
106
|
-
return { _tag: "None" };
|
|
107
|
-
const contentVersion = await resolveNuxtContentVersion();
|
|
108
|
-
if (contentVersion && contentVersion.version === 3)
|
|
109
|
-
return { _tag: "NuxtContentV3" };
|
|
110
|
-
if (hasNuxtModule(COMARK_MODULE) && await comarkSatisfiesMinimum())
|
|
111
|
-
return { _tag: "ComarkContent" };
|
|
112
|
-
return { _tag: "None" };
|
|
113
|
-
}
|
|
114
|
-
const NUXT_CONTENT_V3_LOOKUP = `
|
|
115
|
-
import { queryCollection } from '@nuxt/content/server'
|
|
116
|
-
import manifest from '#content/manifest'
|
|
117
|
-
import { stringify } from 'minimark/stringify'
|
|
118
|
-
|
|
119
|
-
const pageCollections = Object.entries(manifest)
|
|
120
|
-
.filter(([, info]) => info.type === 'page')
|
|
121
|
-
.map(([name]) => name)
|
|
122
|
-
|
|
123
|
-
export async function lookupContentPage(event, path) {
|
|
124
|
-
if (!pageCollections.length) return null
|
|
125
|
-
const candidates = path === '/' ? ['/'] : [path, path.replace(/\\/$/, '')]
|
|
126
|
-
for (const collection of pageCollections) {
|
|
127
|
-
for (const candidate of candidates) {
|
|
128
|
-
const page = await queryCollection(event, collection).path(candidate).first().catch(() => null)
|
|
129
|
-
if (!page) continue
|
|
130
|
-
const markdown = stringify({ ...page.body, type: 'minimark' }, { format: 'markdown/html' })
|
|
131
|
-
return {
|
|
132
|
-
markdown,
|
|
133
|
-
title: page.title,
|
|
134
|
-
description: page.description,
|
|
135
|
-
updatedAt: page.seo?.articleModifiedTime || page.updatedAt,
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
return null
|
|
140
|
-
}
|
|
141
|
-
`;
|
|
142
|
-
const COMARK_LOOKUP = `
|
|
143
|
-
import { queryCollection, queryCollectionManifest, renderPageMarkdown } from '@harlan-zw/comark-content/server'
|
|
144
|
-
|
|
145
|
-
let manifestPromise
|
|
146
|
-
|
|
147
|
-
export async function lookupContentPage(event, path) {
|
|
148
|
-
manifestPromise ??= queryCollectionManifest(event)
|
|
149
|
-
const manifest = await manifestPromise
|
|
150
|
-
for (const { name } of manifest) {
|
|
151
|
-
const page = await queryCollection(event, name).path(path).first()
|
|
152
|
-
if (!page) continue
|
|
153
|
-
return {
|
|
154
|
-
markdown: await renderPageMarkdown(page.body),
|
|
155
|
-
title: page.title,
|
|
156
|
-
description: page.description,
|
|
157
|
-
updatedAt: page.seo?.articleModifiedTime || page.updatedAt,
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
return null
|
|
161
|
-
}
|
|
162
|
-
`;
|
|
163
|
-
const NO_CONTENT_LOOKUP = `export async function lookupContentPage() { return null }`;
|
|
164
|
-
function contentLookupModule(source) {
|
|
165
|
-
switch (source._tag) {
|
|
166
|
-
case "NuxtContentV3":
|
|
167
|
-
return NUXT_CONTENT_V3_LOOKUP;
|
|
168
|
-
case "ComarkContent":
|
|
169
|
-
return COMARK_LOOKUP;
|
|
170
|
-
case "None":
|
|
171
|
-
return NO_CONTENT_LOOKUP;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const logger = useLogger("nuxt-ai-ready");
|
|
176
|
-
|
|
177
|
-
function resolveModuleEntryUrl(url) {
|
|
178
|
-
const directory = dirname(fileURLToPath(url));
|
|
179
|
-
if (basename(directory) !== "shared")
|
|
180
|
-
return url;
|
|
181
|
-
return pathToFileURL(join(directory, "../module.mjs")).href;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
const MARKDOWN_LINK_AVAILABILITY_FILE = "markdown-link-availability.json";
|
|
185
|
-
|
|
186
|
-
const webmcpTypes = `
|
|
187
|
-
import type { WebMcpToolsContext } from 'nuxt-ai-ready/webmcp'
|
|
188
|
-
|
|
189
|
-
declare module '#app' {
|
|
190
|
-
interface RuntimeNuxtHooks {
|
|
191
|
-
/** Mutate built-in browser tools and their registration options before registration. */
|
|
192
|
-
'ai-ready:webmcp:tools': (context: WebMcpToolsContext) => void | Promise<void>
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
`;
|
|
196
|
-
function registerTypeTemplates(ctx) {
|
|
197
|
-
const nitroTypes = renderNitroTypeAugmentations(ctx.nitroCompatibility, {
|
|
198
|
-
runtimeHooks: `'ai-ready:page:markdown': (context: MarkdownContext) => void | Promise<void>
|
|
199
|
-
'ai-ready:markdown:source': (context: MarkdownSourceContext) => void | Promise<void>
|
|
200
|
-
'ai-ready:mdreamConfig': (config: MdreamOptions) => void | Promise<void>
|
|
201
|
-
'ai-ready:page:indexed': (context: PageIndexedContext) => void | Promise<void>`
|
|
202
|
-
});
|
|
203
|
-
addTypeTemplate({
|
|
204
|
-
filename: "types/nuxt-ai-ready-augments.d.ts",
|
|
205
|
-
getContents: () => `// Generated by nuxt-ai-ready
|
|
206
|
-
/// <reference path="./ai-ready-virtual.d.ts" />
|
|
207
|
-
import type { MarkdownContext, MarkdownSourceContext, PageIndexedContext } from 'nuxt-ai-ready'
|
|
208
|
-
import type { MdreamOptions } from 'mdream'
|
|
209
|
-
|
|
210
|
-
${nitroTypes}
|
|
211
|
-
${ctx.config.webmcp ? webmcpTypes : ""}
|
|
212
|
-
export {}
|
|
213
|
-
`
|
|
214
|
-
});
|
|
215
|
-
addTemplate({
|
|
216
|
-
filename: "types/ai-ready-virtual.d.ts",
|
|
217
|
-
getContents: () => `declare module '#ai-ready-virtual/sitemap-config.mjs' {
|
|
218
|
-
const config: { sitemaps?: Record<string, { sitemapName?: string, route?: string, _route?: string }> }
|
|
219
|
-
export default config
|
|
220
|
-
}
|
|
221
|
-
declare module '#ai-ready-virtual/read-page-data.mjs' {
|
|
222
|
-
export function readMarkdownLinkAvailabilityFromFilesystem(): Promise<{
|
|
223
|
-
runtimeMarkdownAvailable: boolean
|
|
224
|
-
paths: string[]
|
|
225
|
-
}>
|
|
226
|
-
export function readPageDataFromFilesystem(): Promise<{
|
|
227
|
-
pages: Array<{
|
|
228
|
-
route: string
|
|
229
|
-
title: string
|
|
230
|
-
description: string
|
|
231
|
-
headings: string
|
|
232
|
-
keywords: string[]
|
|
233
|
-
updatedAt: string
|
|
234
|
-
markdown: string
|
|
235
|
-
}>
|
|
236
|
-
errorRoutes: string[]
|
|
237
|
-
}>
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
declare module '#ai-ready-virtual/page-data.mjs' {
|
|
241
|
-
export const pages: never[]
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
declare module '#ai-ready-virtual/logger.mjs' {
|
|
245
|
-
import type { ConsolaInstance } from 'consola'
|
|
246
|
-
export const logger: ConsolaInstance
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
declare module '#ai-ready-virtual/i18n-runtime.mjs' {
|
|
250
|
-
export {
|
|
251
|
-
computeLocaleAlternates,
|
|
252
|
-
localePath,
|
|
253
|
-
resolveI18nDomain,
|
|
254
|
-
resolveLocaleAlternates,
|
|
255
|
-
resolveLocaleFromRoute,
|
|
256
|
-
} from 'nuxtseo-shared/i18n-runtime'
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
declare module '#ai-ready-virtual/db-provider.mjs' {
|
|
260
|
-
import type { AiReadyDatabaseEvent } from '#ai-ready/server/db/context'
|
|
261
|
-
import type { DrizzleDatabase } from '#ai-ready/server/db/drizzle/client'
|
|
262
|
-
export function createClient(event?: AiReadyDatabaseEvent): Promise<DrizzleDatabase>
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
declare module '#ai-ready-virtual/db-schema.mjs' {
|
|
266
|
-
export * from '#ai-ready/server/db/schema/sqlite'
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
declare module '#ai-ready-virtual/database-runtime.mjs' {
|
|
270
|
-
export * from '#ai-ready/server/db/drizzle'
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
declare module '#ai-ready-virtual/content-lookup.mjs' {
|
|
274
|
-
import type { H3Event } from '#nuxtseo/h3'
|
|
275
|
-
export function lookupContentPage(event: H3Event, path: string): Promise<{
|
|
276
|
-
markdown: string
|
|
277
|
-
title?: string
|
|
278
|
-
description?: string
|
|
279
|
-
updatedAt?: string
|
|
280
|
-
} | null>
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
declare module '#ai-ready-virtual/agent-skills.mjs' {
|
|
284
|
-
import type { AgentSkillsIndex } from 'nuxt-ai-ready'
|
|
285
|
-
export const agentSkillsIndex: AgentSkillsIndex | null
|
|
286
|
-
export const localAgentSkillArtifacts: Record<string, string>
|
|
287
|
-
}
|
|
288
|
-
`
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const AGENT_SKILLS_SCHEMA = "https://schemas.agentskills.io/discovery/0.2.0/schema.json";
|
|
293
|
-
const AGENT_SKILLS_INDEX_ROUTE = "/.well-known/agent-skills/index.json";
|
|
294
|
-
const AGENT_SKILLS_CACHE_CONTROL = publicCacheControl(3600, 86400);
|
|
295
|
-
function resolveExternalSkillUrl(href, indexUrl) {
|
|
296
|
-
const normalized = href.replaceAll(/[\t\n\r]/g, "");
|
|
297
|
-
if (URL.canParse(normalized))
|
|
298
|
-
return new URL(normalized).href;
|
|
299
|
-
if (normalized.startsWith("//")) {
|
|
300
|
-
const resolved2 = new URL(normalized, "https://nuxt-ai-ready.invalid");
|
|
301
|
-
const auth = resolved2.username || resolved2.password ? `${resolved2.username}${resolved2.password ? `:${resolved2.password}` : ""}@` : "";
|
|
302
|
-
return `//${auth}${resolved2.host}${resolved2.pathname}${resolved2.search}${resolved2.hash}`;
|
|
303
|
-
}
|
|
304
|
-
if (URL.canParse(indexUrl))
|
|
305
|
-
return new URL(normalized, indexUrl).href;
|
|
306
|
-
const resolved = new URL(normalized, new URL(indexUrl, "https://nuxt-ai-ready.invalid"));
|
|
307
|
-
return `${resolved.pathname}${resolved.search}${resolved.hash}`;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
const AI_CATALOG_PATH = "/.well-known/ai-catalog.json";
|
|
311
|
-
const ARD_PATH = "/.well-known/ard.json";
|
|
312
|
-
function resolveAiCatalog(input) {
|
|
313
|
-
const hostname = new URL(input.siteUrl).hostname;
|
|
314
|
-
const serverName = input.serverCardName.split("/").at(-1);
|
|
315
|
-
return {
|
|
316
|
-
specVersion: "1.0",
|
|
317
|
-
entries: [{
|
|
318
|
-
identifier: `urn:air:${hostname}:mcp:${serverName}`,
|
|
319
|
-
displayName: input.serverCardTitle || input.serverCardName,
|
|
320
|
-
...input.serverCardDescription ? { description: input.serverCardDescription } : {},
|
|
321
|
-
type: MCP_SERVER_CARD_MEDIA_TYPE,
|
|
322
|
-
url: input.serverCardUrl
|
|
323
|
-
}]
|
|
324
|
-
};
|
|
325
|
-
}
|
|
326
|
-
function createAiCatalogEtag(catalog) {
|
|
327
|
-
return `"${createHash("sha256").update(JSON.stringify(catalog)).digest("hex")}"`;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
const purposes = ["search", "answer", "training", "agent"];
|
|
331
|
-
const accesses = ["allow", "paid", "deny"];
|
|
332
|
-
function isRecord$1(value) {
|
|
333
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
334
|
-
}
|
|
335
|
-
function checkPayment(value, field, errors) {
|
|
336
|
-
if (!isRecord$1(value)) {
|
|
337
|
-
errors.push(`${field}: configure an x402 payment endpoint.`);
|
|
338
|
-
return;
|
|
339
|
-
}
|
|
340
|
-
if (value.protocol !== "x402")
|
|
341
|
-
errors.push(`${field}.protocol: use x402.`);
|
|
342
|
-
const endpoint = typeof value.endpoint === "string" && /^https:\/\/[^/?#\\\s][^?#\\\s]*$/.test(value.endpoint) ? URL.parse(value.endpoint) : null;
|
|
343
|
-
if (!endpoint || endpoint.username || endpoint.password)
|
|
344
|
-
errors.push(`${field}.endpoint: use an absolute HTTPS URL without credentials, query parameters, or a fragment.`);
|
|
345
|
-
if (value.version !== void 0 && !Number.isInteger(value.version))
|
|
346
|
-
errors.push(`${field}.version: use an integer.`);
|
|
347
|
-
for (const key of ["network", "asset"]) {
|
|
348
|
-
if (value[key] !== void 0 && typeof value[key] !== "string")
|
|
349
|
-
errors.push(`${field}.${key}: use a string.`);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
function checkUses(value, field, payment, partial, errors) {
|
|
353
|
-
if (!isRecord$1(value)) {
|
|
354
|
-
errors.push(`${field}: set the AI use rules.`);
|
|
355
|
-
return;
|
|
356
|
-
}
|
|
357
|
-
if (partial && !purposes.some((purpose) => value[purpose] !== void 0))
|
|
358
|
-
errors.push(`${field}: set at least one AI use rule.`);
|
|
359
|
-
for (const purpose of purposes) {
|
|
360
|
-
const rule = value[purpose];
|
|
361
|
-
const path = `${field}.${purpose}`;
|
|
362
|
-
if (rule === void 0 && partial)
|
|
363
|
-
continue;
|
|
364
|
-
if (!isRecord$1(rule)) {
|
|
365
|
-
errors.push(`${path}: set an access rule.`);
|
|
366
|
-
continue;
|
|
367
|
-
}
|
|
368
|
-
if (!accesses.includes(rule.access))
|
|
369
|
-
errors.push(`${path}.access: use allow, paid, or deny.`);
|
|
370
|
-
if (rule.attribution !== void 0 && !["required", "requested", "none"].includes(rule.attribution))
|
|
371
|
-
errors.push(`${path}.attribution: use required, requested, or none.`);
|
|
372
|
-
if (rule.access === "paid") {
|
|
373
|
-
if (!isRecord$1(rule.price)) {
|
|
374
|
-
errors.push(`${path}.price: set the paid use price.`);
|
|
375
|
-
} else {
|
|
376
|
-
if (typeof rule.price.amount !== "string" || !/^\d+(?:\.\d+)?$/.test(rule.price.amount))
|
|
377
|
-
errors.push(`${path}.price.amount: use a decimal string.`);
|
|
378
|
-
if (rule.price.currency !== "USD")
|
|
379
|
-
errors.push(`${path}.price.currency: use USD.`);
|
|
380
|
-
if (!["page", "request"].includes(rule.price.per))
|
|
381
|
-
errors.push(`${path}.price.per: use page or request.`);
|
|
382
|
-
}
|
|
383
|
-
if (!payment)
|
|
384
|
-
errors.push(`${field === "uses" ? "payment" : field.replace(/\.uses$/, ".payment")}: paid uses need a payment endpoint.`);
|
|
385
|
-
} else if (rule.price !== void 0) {
|
|
386
|
-
errors.push(`${path}.price: only paid uses have a price.`);
|
|
387
|
-
}
|
|
388
|
-
if (rule.free !== void 0) {
|
|
389
|
-
if (!isRecord$1(rule.free) || !Number.isInteger(rule.free.requests) || Number(rule.free.requests) < 1 || Number(rule.free.requests) > 1e9 || !["hour", "day"].includes(rule.free.per))
|
|
390
|
-
errors.push(`${path}.free: set 1 to 1000000000 requests per hour or day.`);
|
|
391
|
-
if (rule.access === "allow")
|
|
392
|
-
errors.push(`${path}.free: only paid or denied uses have a free allowance.`);
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
function publicPayment({ protocol, endpoint, version, network, asset }) {
|
|
397
|
-
return { protocol, endpoint, version, network, asset };
|
|
398
|
-
}
|
|
399
|
-
function publicUse(use) {
|
|
400
|
-
const { access, attribution, free } = use;
|
|
401
|
-
if (access === "allow")
|
|
402
|
-
return { access, attribution };
|
|
403
|
-
const allowance = free && { requests: free.requests, per: free.per };
|
|
404
|
-
if (access === "deny")
|
|
405
|
-
return { access, attribution, free: allowance };
|
|
406
|
-
const { amount, currency, per } = use.price;
|
|
407
|
-
return { access, attribution, free: allowance, price: { amount, currency, per } };
|
|
408
|
-
}
|
|
409
|
-
function publicDocument(policy, site) {
|
|
410
|
-
const { updated, uses, paths, payment, identity, receipts, report_only, contact, preview } = policy;
|
|
411
|
-
return {
|
|
412
|
-
ai_terms: "0.1",
|
|
413
|
-
site,
|
|
414
|
-
updated,
|
|
415
|
-
default: policy.default,
|
|
416
|
-
uses: {
|
|
417
|
-
search: publicUse(uses.search),
|
|
418
|
-
answer: publicUse(uses.answer),
|
|
419
|
-
training: publicUse(uses.training),
|
|
420
|
-
agent: publicUse(uses.agent)
|
|
421
|
-
},
|
|
422
|
-
paths: paths?.map(({ match, uses: uses2, payment: payment2 }) => {
|
|
423
|
-
const overrides = {};
|
|
424
|
-
for (const purpose of purposes) {
|
|
425
|
-
const rule = uses2[purpose];
|
|
426
|
-
if (rule)
|
|
427
|
-
overrides[purpose] = publicUse(rule);
|
|
428
|
-
}
|
|
429
|
-
return { match, uses: overrides, payment: payment2 && publicPayment(payment2) };
|
|
430
|
-
}),
|
|
431
|
-
payment: payment && publicPayment(payment),
|
|
432
|
-
identity: identity && { verify: identity.verify && [...identity.verify], unverified: identity.unverified },
|
|
433
|
-
receipts,
|
|
434
|
-
report_only,
|
|
435
|
-
contact: contact && { licensing: contact.licensing },
|
|
436
|
-
preview: preview && { shows: preview.shows && [...preview.shows], delivery: preview.delivery, described_quote: preview.described_quote },
|
|
437
|
-
purpose_header: "AI-Purpose",
|
|
438
|
-
spec: "https://aipaygen.com/ai-terms"
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
function resolveAiTermsConfig(input, siteBaseURL) {
|
|
442
|
-
if (input === void 0 || input === false)
|
|
443
|
-
return { _tag: "Disabled" };
|
|
444
|
-
if (!isRecord$1(input))
|
|
445
|
-
return { _tag: "Invalid", errors: ["aiTerms: configure an explicit AI Terms policy, or use false."] };
|
|
446
|
-
const errors = [];
|
|
447
|
-
const site = siteBaseURL && URL.canParse(siteBaseURL) ? new URL(siteBaseURL) : void 0;
|
|
448
|
-
if (!site || !["https:", "http:"].includes(site.protocol) || site.username || site.password)
|
|
449
|
-
errors.push("site.url: set an absolute HTTP or HTTPS URL to publish AI Terms.");
|
|
450
|
-
if (typeof input.updated !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(input.updated) || !Number.isFinite(Date.parse(input.updated)) || new Date(input.updated).toISOString().slice(0, 10) !== input.updated)
|
|
451
|
-
errors.push("updated: set the policy change date in YYYY-MM-DD format.");
|
|
452
|
-
if (!accesses.includes(input.default))
|
|
453
|
-
errors.push("default: use allow, paid, or deny.");
|
|
454
|
-
if (input.payment !== void 0)
|
|
455
|
-
checkPayment(input.payment, "payment", errors);
|
|
456
|
-
if (input.default === "paid" && !input.payment)
|
|
457
|
-
errors.push("payment: a paid default needs a payment endpoint.");
|
|
458
|
-
checkUses(input.uses, "uses", input.payment, false, errors);
|
|
459
|
-
if (input.paths !== void 0) {
|
|
460
|
-
if (!Array.isArray(input.paths)) {
|
|
461
|
-
errors.push("paths: use an array of path overrides.");
|
|
462
|
-
} else {
|
|
463
|
-
for (const [index, entry] of input.paths.entries()) {
|
|
464
|
-
const field = `paths[${index}]`;
|
|
465
|
-
if (!isRecord$1(entry)) {
|
|
466
|
-
errors.push(`${field}: set a path match and AI use rules.`);
|
|
467
|
-
continue;
|
|
468
|
-
}
|
|
469
|
-
if (typeof entry.match !== "string" || !/^\/[^?#]*$/.test(entry.match))
|
|
470
|
-
errors.push(`${field}.match: start the path pattern with / and omit any query or fragment.`);
|
|
471
|
-
if (entry.payment !== void 0)
|
|
472
|
-
checkPayment(entry.payment, `${field}.payment`, errors);
|
|
473
|
-
checkUses(entry.uses, `${field}.uses`, entry.payment ?? input.payment, true, errors);
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
if (input.identity !== void 0) {
|
|
478
|
-
if (!isRecord$1(input.identity)) {
|
|
479
|
-
errors.push("identity: configure the identity checks used by your server.");
|
|
480
|
-
} else {
|
|
481
|
-
if (input.identity.verify !== void 0 && (!Array.isArray(input.identity.verify) || [...input.identity.verify].some((value) => typeof value !== "string")))
|
|
482
|
-
errors.push("identity.verify: use an array of verification methods.");
|
|
483
|
-
if (input.identity.unverified !== void 0 && typeof input.identity.unverified !== "string")
|
|
484
|
-
errors.push("identity.unverified: use a string.");
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
if (input.receipts !== void 0 && typeof input.receipts !== "string")
|
|
488
|
-
errors.push("receipts: use a string.");
|
|
489
|
-
if (input.report_only !== void 0 && typeof input.report_only !== "boolean")
|
|
490
|
-
errors.push("report_only: use true or false.");
|
|
491
|
-
if (input.contact !== void 0 && (!isRecord$1(input.contact) || input.contact.licensing !== void 0 && typeof input.contact.licensing !== "string"))
|
|
492
|
-
errors.push("contact.licensing: use a string.");
|
|
493
|
-
if (input.preview !== void 0) {
|
|
494
|
-
if (!isRecord$1(input.preview) || !["must-match", "per-quote", "not-checked"].includes(input.preview.delivery)) {
|
|
495
|
-
errors.push("preview.delivery: use must-match, per-quote, or not-checked.");
|
|
496
|
-
} else {
|
|
497
|
-
if (input.preview.shows !== void 0 && (!Array.isArray(input.preview.shows) || [...input.preview.shows].some((value) => !["title", "description", "excerpt", "words"].includes(value))))
|
|
498
|
-
errors.push("preview.shows: use title, description, excerpt, or words.");
|
|
499
|
-
if (input.preview.described_quote !== void 0 && typeof input.preview.described_quote !== "string")
|
|
500
|
-
errors.push("preview.described_quote: use a string.");
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
if (errors.length || !site)
|
|
504
|
-
return { _tag: "Invalid", errors };
|
|
505
|
-
const href = new URL(site.origin);
|
|
506
|
-
href.pathname = `${site.pathname.replace(/\/$/, "")}${AI_TERMS_PATH}`;
|
|
507
|
-
return {
|
|
508
|
-
_tag: "Enabled",
|
|
509
|
-
config: {
|
|
510
|
-
href: href.href,
|
|
511
|
-
document: publicDocument(input, site.origin)
|
|
512
|
-
}
|
|
513
|
-
};
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
const API_CATALOG_PATH = "/.well-known/api-catalog";
|
|
517
|
-
const API_CATALOG_PROFILE = "https://www.rfc-editor.org/info/rfc9727";
|
|
518
|
-
const API_CATALOG_MEDIA_TYPE = `application/linkset+json; profile="${API_CATALOG_PROFILE}"`;
|
|
519
|
-
const RELATION_FIELDS = {
|
|
520
|
-
item: "item",
|
|
521
|
-
serviceDesc: "service-desc",
|
|
522
|
-
serviceDoc: "service-doc",
|
|
523
|
-
serviceMeta: "service-meta",
|
|
524
|
-
status: "status",
|
|
525
|
-
apiCatalog: "api-catalog"
|
|
526
|
-
};
|
|
527
|
-
function parseBaseURL(siteBaseURL) {
|
|
528
|
-
if (!siteBaseURL || !URL.canParse(siteBaseURL))
|
|
529
|
-
return void 0;
|
|
530
|
-
const parsed = new URL(siteBaseURL);
|
|
531
|
-
if (!parsed.pathname.endsWith("/"))
|
|
532
|
-
parsed.pathname = `${parsed.pathname}/`;
|
|
533
|
-
return parsed;
|
|
534
|
-
}
|
|
535
|
-
function resolveUrl(value, baseURL, errorContext) {
|
|
536
|
-
if (!value.trim()) {
|
|
537
|
-
return {
|
|
538
|
-
_tag: "Err",
|
|
539
|
-
error: errorContext.field === "anchor" ? { _tag: "InvalidAnchor", entryIndex: errorContext.entryIndex } : {
|
|
540
|
-
_tag: "InvalidUrl",
|
|
541
|
-
entryIndex: errorContext.entryIndex,
|
|
542
|
-
field: errorContext.field,
|
|
543
|
-
value
|
|
544
|
-
}
|
|
545
|
-
};
|
|
546
|
-
}
|
|
547
|
-
if (value.startsWith("//")) {
|
|
548
|
-
if (!baseURL) {
|
|
549
|
-
return {
|
|
550
|
-
_tag: "Err",
|
|
551
|
-
error: { _tag: "MissingSiteUrl", entryIndex: errorContext.entryIndex, field: errorContext.field }
|
|
552
|
-
};
|
|
553
|
-
}
|
|
554
|
-
return URL.canParse(value, baseURL) ? { _tag: "Ok", value: new URL(value, baseURL).href } : {
|
|
555
|
-
_tag: "Err",
|
|
556
|
-
error: {
|
|
557
|
-
_tag: "InvalidUrl",
|
|
558
|
-
entryIndex: errorContext.entryIndex,
|
|
559
|
-
field: errorContext.field,
|
|
560
|
-
value
|
|
561
|
-
}
|
|
562
|
-
};
|
|
563
|
-
}
|
|
564
|
-
if (URL.canParse(value))
|
|
565
|
-
return { _tag: "Ok", value: new URL(value).href };
|
|
566
|
-
if (!baseURL) {
|
|
567
|
-
return {
|
|
568
|
-
_tag: "Err",
|
|
569
|
-
error: { _tag: "MissingSiteUrl", entryIndex: errorContext.entryIndex, field: errorContext.field }
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
const relativeValue = value.replace(/^\/+/, "");
|
|
573
|
-
return URL.canParse(relativeValue, baseURL) ? { _tag: "Ok", value: new URL(relativeValue, baseURL).href } : {
|
|
574
|
-
_tag: "Err",
|
|
575
|
-
error: {
|
|
576
|
-
_tag: "InvalidUrl",
|
|
577
|
-
entryIndex: errorContext.entryIndex,
|
|
578
|
-
field: errorContext.field,
|
|
579
|
-
value
|
|
580
|
-
}
|
|
581
|
-
};
|
|
582
|
-
}
|
|
583
|
-
function normalizeLinks(value) {
|
|
584
|
-
return Array.isArray(value) ? value : [value];
|
|
585
|
-
}
|
|
586
|
-
const registeredRelationPattern = /^[a-z][a-z0-9.-]*$/;
|
|
587
|
-
function isValidCustomRelation(relation) {
|
|
588
|
-
return relation !== "anchor" && (registeredRelationPattern.test(relation) || URL.canParse(relation));
|
|
589
|
-
}
|
|
590
|
-
function parseLinks(input, relation, entryIndex, baseURL, errors) {
|
|
591
|
-
const resolved = [];
|
|
592
|
-
for (const [targetIndex, target] of normalizeLinks(input).entries()) {
|
|
593
|
-
if (!target || typeof target !== "object" || Array.isArray(target)) {
|
|
594
|
-
errors.push({ _tag: "InvalidLink", entryIndex, relation, targetIndex });
|
|
595
|
-
continue;
|
|
596
|
-
}
|
|
597
|
-
const candidate = target;
|
|
598
|
-
if (typeof candidate.href !== "string" || !candidate.href.trim()) {
|
|
599
|
-
errors.push({ _tag: "InvalidLinkHref", entryIndex, relation, targetIndex });
|
|
600
|
-
continue;
|
|
601
|
-
}
|
|
602
|
-
const href = resolveUrl(candidate.href, baseURL, {
|
|
603
|
-
entryIndex,
|
|
604
|
-
field: `${relation}[${targetIndex}].href`
|
|
605
|
-
});
|
|
606
|
-
if (href._tag === "Err") {
|
|
607
|
-
errors.push(href.error);
|
|
608
|
-
continue;
|
|
609
|
-
}
|
|
610
|
-
resolved.push({
|
|
611
|
-
href: href.value,
|
|
612
|
-
...typeof candidate.type === "string" && { type: candidate.type },
|
|
613
|
-
...typeof candidate.title === "string" && { title: candidate.title },
|
|
614
|
-
...typeof candidate.hreflang === "string" ? { hreflang: [candidate.hreflang] } : Array.isArray(candidate.hreflang) && candidate.hreflang.every((value) => typeof value === "string") ? { hreflang: candidate.hreflang } : {},
|
|
615
|
-
...typeof candidate.media === "string" && { media: candidate.media }
|
|
616
|
-
});
|
|
617
|
-
}
|
|
618
|
-
return resolved;
|
|
619
|
-
}
|
|
620
|
-
function parseEntry(input, entryIndex, baseURL, errors) {
|
|
621
|
-
const entryErrorStart = errors.length;
|
|
622
|
-
if (!input || typeof input !== "object" || Array.isArray(input)) {
|
|
623
|
-
errors.push({ _tag: "InvalidEntry", entryIndex });
|
|
624
|
-
return void 0;
|
|
625
|
-
}
|
|
626
|
-
const entry = input;
|
|
627
|
-
if (typeof entry.anchor !== "string") {
|
|
628
|
-
errors.push({ _tag: "InvalidAnchor", entryIndex });
|
|
629
|
-
return void 0;
|
|
630
|
-
}
|
|
631
|
-
const anchor = resolveUrl(entry.anchor, baseURL, { entryIndex, field: "anchor" });
|
|
632
|
-
if (anchor._tag === "Err")
|
|
633
|
-
errors.push(anchor.error);
|
|
634
|
-
const resolved = {
|
|
635
|
-
anchor: anchor._tag === "Ok" ? anchor.value : entry.anchor
|
|
636
|
-
};
|
|
637
|
-
for (const [field, relation] of Object.entries(RELATION_FIELDS)) {
|
|
638
|
-
const links = entry[field];
|
|
639
|
-
if (links === void 0)
|
|
640
|
-
continue;
|
|
641
|
-
resolved[relation] = parseLinks(links, field, entryIndex, baseURL, errors);
|
|
642
|
-
}
|
|
643
|
-
if (entry.relations !== void 0) {
|
|
644
|
-
if (!entry.relations || typeof entry.relations !== "object" || Array.isArray(entry.relations)) {
|
|
645
|
-
errors.push({ _tag: "InvalidRelation", entryIndex, relation: "relations" });
|
|
646
|
-
} else {
|
|
647
|
-
for (const [relation, links] of Object.entries(entry.relations)) {
|
|
648
|
-
if (!isValidCustomRelation(relation)) {
|
|
649
|
-
errors.push({ _tag: "InvalidRelation", entryIndex, relation });
|
|
650
|
-
continue;
|
|
651
|
-
}
|
|
652
|
-
const parsed = parseLinks(links, relation, entryIndex, baseURL, errors);
|
|
653
|
-
const existing = resolved[relation];
|
|
654
|
-
resolved[relation] = Array.isArray(existing) ? [...existing, ...parsed] : parsed;
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
const hasLinks = Object.entries(resolved).some(([relation, links]) => relation !== "anchor" && Array.isArray(links) && links.length > 0);
|
|
659
|
-
if (!hasLinks && errors.length === entryErrorStart)
|
|
660
|
-
errors.push({ _tag: "MissingLinks", entryIndex });
|
|
661
|
-
return resolved;
|
|
662
|
-
}
|
|
663
|
-
function resolveApiCatalogConfig(input, context) {
|
|
664
|
-
if (input === false)
|
|
665
|
-
return { _tag: "Disabled" };
|
|
666
|
-
const generatedEntries = context.generatedEntries || [];
|
|
667
|
-
if (input === void 0 && generatedEntries.length === 0)
|
|
668
|
-
return { _tag: "Disabled" };
|
|
669
|
-
if (input !== void 0 && (!input || typeof input !== "object" || Array.isArray(input))) {
|
|
670
|
-
return { _tag: "Invalid", errors: [{ _tag: "InvalidOptions" }] };
|
|
671
|
-
}
|
|
672
|
-
const configuredEntries = input === void 0 ? [] : Array.isArray(input.entries) ? input.entries : [];
|
|
673
|
-
const entries = [...configuredEntries, ...generatedEntries];
|
|
674
|
-
if (entries.length === 0)
|
|
675
|
-
return { _tag: "Invalid", errors: [{ _tag: "MissingEntries" }] };
|
|
676
|
-
const errors = [];
|
|
677
|
-
const baseURL = parseBaseURL(context.siteBaseURL);
|
|
678
|
-
const linkset = entries.map((entry, entryIndex) => parseEntry(entry, entryIndex, baseURL, errors)).filter((entry) => !!entry);
|
|
679
|
-
if (errors.length > 0)
|
|
680
|
-
return { _tag: "Invalid", errors };
|
|
681
|
-
const href = baseURL ? new URL(API_CATALOG_PATH.slice(1), baseURL).href : API_CATALOG_PATH;
|
|
682
|
-
return {
|
|
683
|
-
_tag: "Enabled",
|
|
684
|
-
config: {
|
|
685
|
-
href,
|
|
686
|
-
mediaType: API_CATALOG_MEDIA_TYPE,
|
|
687
|
-
document: { linkset }
|
|
688
|
-
}
|
|
689
|
-
};
|
|
690
|
-
}
|
|
691
|
-
function formatApiCatalogConfigError(error) {
|
|
692
|
-
switch (error._tag) {
|
|
693
|
-
case "InvalidOptions":
|
|
694
|
-
return "`aiReady.apiCatalog` must be false or an object.";
|
|
695
|
-
case "MissingEntries":
|
|
696
|
-
return "`aiReady.apiCatalog.entries` must contain at least one entry.";
|
|
697
|
-
case "InvalidEntry":
|
|
698
|
-
return `\`aiReady.apiCatalog.entries[${error.entryIndex}]\` must be an object.`;
|
|
699
|
-
case "InvalidAnchor":
|
|
700
|
-
return `\`aiReady.apiCatalog.entries[${error.entryIndex}].anchor\` must be a non-empty URL.`;
|
|
701
|
-
case "InvalidRelation":
|
|
702
|
-
return `API catalog relation \`${error.relation}\` in entry ${error.entryIndex} is invalid.`;
|
|
703
|
-
case "MissingLinks":
|
|
704
|
-
return `API catalog entry ${error.entryIndex} must contain at least one link.`;
|
|
705
|
-
case "InvalidLink":
|
|
706
|
-
return `API catalog ${error.relation} target ${error.targetIndex} in entry ${error.entryIndex} must be an object.`;
|
|
707
|
-
case "InvalidLinkHref":
|
|
708
|
-
return `API catalog ${error.relation} target ${error.targetIndex} in entry ${error.entryIndex} needs a non-empty href.`;
|
|
709
|
-
case "InvalidUrl":
|
|
710
|
-
return `API catalog URL \`${error.value}\` at ${error.field} in entry ${error.entryIndex} is invalid.`;
|
|
711
|
-
case "MissingSiteUrl":
|
|
712
|
-
return `API catalog relative URL at ${error.field} in entry ${error.entryIndex} requires a configured site.url.`;
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
const PARSERS = {
|
|
717
|
-
"wrangler.json": JSON.parse,
|
|
718
|
-
"wrangler.jsonc": parseJSONC,
|
|
719
|
-
"wrangler.toml": parseTOML
|
|
720
|
-
};
|
|
721
|
-
function parseRouting(routing) {
|
|
722
|
-
if (routing === void 0 || typeof routing === "boolean")
|
|
723
|
-
return routing;
|
|
724
|
-
if (Array.isArray(routing) && routing.every((pattern) => typeof pattern === "string"))
|
|
725
|
-
return routing;
|
|
726
|
-
throw new Error("Cloudflare assets.run_worker_first must be a boolean or an array of path patterns.");
|
|
727
|
-
}
|
|
728
|
-
async function readCloudflareAssetRouting(rootDir) {
|
|
729
|
-
let directory = rootDir;
|
|
730
|
-
while (true) {
|
|
731
|
-
for (const [name, parse] of Object.entries(PARSERS)) {
|
|
732
|
-
const source = await readFile(join(directory, name), "utf8").catch((error) => {
|
|
733
|
-
if (error.code === "ENOENT")
|
|
734
|
-
return void 0;
|
|
735
|
-
throw error;
|
|
736
|
-
});
|
|
737
|
-
if (source === void 0)
|
|
738
|
-
continue;
|
|
739
|
-
const config = parse(source);
|
|
740
|
-
return {
|
|
741
|
-
root: parseRouting(config.assets?.run_worker_first),
|
|
742
|
-
environments: Object.values(config.env || {}).flatMap((env) => {
|
|
743
|
-
const routing = parseRouting(env.assets?.run_worker_first);
|
|
744
|
-
return routing === void 0 ? [] : [routing];
|
|
745
|
-
})
|
|
746
|
-
};
|
|
747
|
-
}
|
|
748
|
-
const parent = dirname(directory);
|
|
749
|
-
if (parent === directory)
|
|
750
|
-
return { environments: [] };
|
|
751
|
-
directory = parent;
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
function escapeRegExp(value) {
|
|
756
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
757
|
-
}
|
|
758
|
-
function ensureStaticHeader(contents, route, name, value, mode = "default") {
|
|
759
|
-
const eol = contents.includes("\r\n") ? "\r\n" : "\n";
|
|
760
|
-
const routePattern = new RegExp(`^${escapeRegExp(route)}[\\t ]*\\r?$`, "gm");
|
|
761
|
-
const routeMatches = [...contents.matchAll(routePattern)];
|
|
762
|
-
const routeMatch = routeMatches.at(-1);
|
|
763
|
-
if (!routeMatch || routeMatch.index === void 0) {
|
|
764
|
-
const separator = contents.length === 0 ? "" : contents.endsWith(`${eol}${eol}`) ? "" : contents.endsWith(eol) ? eol : `${eol}${eol}`;
|
|
765
|
-
return `${contents}${separator}${route}${eol} ${name}: ${value}${eol}`;
|
|
766
|
-
}
|
|
767
|
-
const routeLineEnd = routeMatch.index + routeMatch[0].length;
|
|
768
|
-
const blockStart = contents[routeLineEnd] === "\n" ? routeLineEnd + 1 : routeLineEnd;
|
|
769
|
-
const nextBlockPattern = /^(?![\t ]|\r?$).+/gm;
|
|
770
|
-
nextBlockPattern.lastIndex = blockStart;
|
|
771
|
-
const nextBlock = nextBlockPattern.exec(contents);
|
|
772
|
-
const blockEnd = nextBlock?.index ?? contents.length;
|
|
773
|
-
const block = contents.slice(blockStart, blockEnd);
|
|
774
|
-
const escapedName = escapeRegExp(name);
|
|
775
|
-
const existingHeaderPattern = new RegExp(
|
|
776
|
-
`^[\\t ]+(?:${escapedName}[\\t ]*:|![\\t ]*${escapedName}[\\t ]*\\r?$)`,
|
|
777
|
-
"im"
|
|
778
|
-
);
|
|
779
|
-
if (existingHeaderPattern.test(block)) {
|
|
780
|
-
if (mode === "append") {
|
|
781
|
-
const removalPattern = new RegExp(`^[\\t ]+![\\t ]*${escapedName}[\\t ]*\\r?$`, "im");
|
|
782
|
-
if (removalPattern.test(block))
|
|
783
|
-
return contents;
|
|
784
|
-
const valuePattern = new RegExp(`^([\\t ]+${escapedName}[\\t ]*:[\\t ]*)([^\\r\\n]*)(\\r?$)`, "im");
|
|
785
|
-
const match = block.match(valuePattern);
|
|
786
|
-
if (match) {
|
|
787
|
-
const merged = block.replace(valuePattern, (_line, prefix2, current, suffix) => {
|
|
788
|
-
const appended = name.toLowerCase() === "link" ? current.includes(value) ? current : [current, value].filter(Boolean).join(", ") : mergeVaryHeader(current, value);
|
|
789
|
-
return `${prefix2}${appended}${suffix}`;
|
|
790
|
-
});
|
|
791
|
-
return `${contents.slice(0, blockStart)}${merged}${contents.slice(blockEnd)}`;
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
return contents;
|
|
795
|
-
}
|
|
796
|
-
const prefix = blockStart === routeLineEnd ? eol : "";
|
|
797
|
-
return `${contents.slice(0, blockStart)}${prefix} ${name}: ${value}${eol}${contents.slice(blockStart)}`;
|
|
798
|
-
}
|
|
799
|
-
function mergeStaticDiscoveryHeaders(contents, baseURL, entries) {
|
|
800
|
-
if (entries.length === 0)
|
|
801
|
-
return contents;
|
|
802
|
-
const route = toDeployedRoute("/*", baseURL);
|
|
803
|
-
const blocks = splitHeaderBlocks(contents);
|
|
804
|
-
const matching = blocks.filter((block) => block.route === route);
|
|
805
|
-
let merged = matching[0]?.text || "";
|
|
806
|
-
for (const block of matching.slice(1)) {
|
|
807
|
-
for (const line of block.text.split(/(?<=\n)/).slice(1)) {
|
|
808
|
-
const header = line.match(/^[\t ]+([^:\s]+):[\t ]*([^\r\n]*)/);
|
|
809
|
-
if (header?.[1]?.toLowerCase() === "link") {
|
|
810
|
-
merged = ensureStaticHeader(merged, route, header[1], header[2], "append");
|
|
811
|
-
} else if (header) {
|
|
812
|
-
const existing = new RegExp(`^[\\t ]+${escapeRegExp(header[1])}[\\t ]*:[^\\r\\n]*(?:\\r?\\n|$)`, "gim");
|
|
813
|
-
merged = ensureStaticHeader(merged.replace(existing, ""), route, header[1], header[2]);
|
|
814
|
-
} else {
|
|
815
|
-
merged += line;
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
if (matching.length > 1) {
|
|
820
|
-
let inserted = false;
|
|
821
|
-
contents = blocks.map((block) => {
|
|
822
|
-
if (block.route !== route)
|
|
823
|
-
return block.text;
|
|
824
|
-
if (inserted)
|
|
825
|
-
return "";
|
|
826
|
-
inserted = true;
|
|
827
|
-
return merged;
|
|
828
|
-
}).join("");
|
|
829
|
-
}
|
|
830
|
-
return entries.reduce((headers, entry) => ensureStaticHeader(headers, route, "Link", entry, "append"), contents);
|
|
831
|
-
}
|
|
832
|
-
function parseHeaderLine(line) {
|
|
833
|
-
const colon = line.indexOf(":");
|
|
834
|
-
if (!/^[\t ]/.test(line) || colon < 0)
|
|
835
|
-
return void 0;
|
|
836
|
-
const name = line.slice(0, colon).trim();
|
|
837
|
-
if (!name || name.startsWith("!") || /\s/.test(name))
|
|
838
|
-
return void 0;
|
|
839
|
-
const eol = line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : "";
|
|
840
|
-
return {
|
|
841
|
-
name,
|
|
842
|
-
value: line.slice(colon + 1, line.length - eol.length).trim(),
|
|
843
|
-
withValue: (value) => `${line.slice(0, colon + 1)} ${value}${eol}`
|
|
844
|
-
};
|
|
845
|
-
}
|
|
846
|
-
const RE_DETACH_LINE = /^[\t ]+![\t ]*([^\s:]+)/;
|
|
847
|
-
function patternToRegExp(pattern) {
|
|
848
|
-
const source = pattern.split(/(\*|:\w+)/).map((part) => part === "*" ? ".*" : part.startsWith(":") ? "[^/]+" : escapeRegExp(part)).join("");
|
|
849
|
-
return new RegExp(`^${source}$`);
|
|
850
|
-
}
|
|
851
|
-
function matchingStaticContentSignals(routeRules, route) {
|
|
852
|
-
return Object.entries(routeRules).flatMap(([pattern, rule]) => {
|
|
853
|
-
if (!patternToRegExp(pattern).test(route))
|
|
854
|
-
return [];
|
|
855
|
-
const headers = rule?.headers;
|
|
856
|
-
return Object.entries(headers || {}).filter(([name]) => name.toLowerCase() === "content-signal").map(([, value]) => value);
|
|
857
|
-
});
|
|
858
|
-
}
|
|
859
|
-
function normalizeStaticContentSignalHeaders(contents, generatedDiscovery = []) {
|
|
860
|
-
const parsed = splitHeaderBlocks(contents);
|
|
861
|
-
if (!parsed.some((block) => /^\s+content-signal\s*:/im.test(block.text)))
|
|
862
|
-
return contents;
|
|
863
|
-
const policyLine = /^[\t ]+(?:content-signal\s*:.*|!\s*content-signal\s*)$/i;
|
|
864
|
-
const hasPolicy = (block) => block.text.split(/\r?\n/).slice(1).some((line) => policyLine.test(line));
|
|
865
|
-
const repeated = /* @__PURE__ */ new Map();
|
|
866
|
-
for (const block of parsed) {
|
|
867
|
-
if (block.route !== null)
|
|
868
|
-
repeated.set(block.route, [...repeated.get(block.route) || [], block]);
|
|
869
|
-
}
|
|
870
|
-
const combined = /* @__PURE__ */ new Set();
|
|
871
|
-
const blocks = parsed.flatMap((block) => {
|
|
872
|
-
const group = block.route === null ? [] : repeated.get(block.route);
|
|
873
|
-
if (group.length < 2 || !group.some(hasPolicy))
|
|
874
|
-
return [block];
|
|
875
|
-
if (combined.has(block.route))
|
|
876
|
-
return [];
|
|
877
|
-
combined.add(block.route);
|
|
878
|
-
const lines = group.at(-1).text.split(/\r?\n/).slice(1).filter((line) => !policyLine.test(line));
|
|
879
|
-
const policy = group.filter(hasPolicy).at(-1).text.split(/\r?\n/).slice(1).filter((line) => policyLine.test(line));
|
|
880
|
-
return [{ route: block.route, text: `${block.route}
|
|
881
|
-
${[...lines, ...policy].join("\n")}
|
|
882
|
-
` }];
|
|
883
|
-
});
|
|
884
|
-
const discoveryLinks = new Set(generatedDiscovery);
|
|
885
|
-
const isGeneratedDiscovery = (line) => {
|
|
886
|
-
if (discoveryLinks.size === 0)
|
|
887
|
-
return false;
|
|
888
|
-
const header = parseHeaderLine(line);
|
|
889
|
-
if (header?.name.toLowerCase() !== "link")
|
|
890
|
-
return false;
|
|
891
|
-
const links = splitLinkEntries(header.value);
|
|
892
|
-
return links.length > 0 && links.every((link) => discoveryLinks.has(link));
|
|
893
|
-
};
|
|
894
|
-
const policyOnly = (block) => hasPolicy(block) && block.text.split(/\r?\n/).slice(1).every((line) => !line.trim() || line.trimStart().startsWith("#") || policyLine.test(line) || isGeneratedDiscovery(line));
|
|
895
|
-
const policyValue = (block) => block.text.match(/^[\t ]+content-signal[\t ]*:(.*)$/im)?.[1]?.trim() ?? null;
|
|
896
|
-
const edges = blocks.map(() => /* @__PURE__ */ new Set());
|
|
897
|
-
const incoming = blocks.map(() => 0);
|
|
898
|
-
const connect = (before, after) => {
|
|
899
|
-
if (!edges[before].has(after)) {
|
|
900
|
-
edges[before].add(after);
|
|
901
|
-
incoming[after]++;
|
|
902
|
-
}
|
|
903
|
-
};
|
|
904
|
-
let previousUnrelated;
|
|
905
|
-
for (let index = 0; index < blocks.length; index++) {
|
|
906
|
-
if (!policyOnly(blocks[index])) {
|
|
907
|
-
if (previousUnrelated !== void 0)
|
|
908
|
-
connect(previousUnrelated, index);
|
|
909
|
-
previousUnrelated = index;
|
|
910
|
-
}
|
|
911
|
-
}
|
|
912
|
-
for (let broad = 0; broad < blocks.length; broad++) {
|
|
913
|
-
const source = blocks[broad];
|
|
914
|
-
if (!hasPolicy(source) || source.route === null)
|
|
915
|
-
continue;
|
|
916
|
-
for (let narrow = 0; narrow < blocks.length; narrow++) {
|
|
917
|
-
const target = blocks[narrow];
|
|
918
|
-
if (broad !== narrow && hasPolicy(target) && target.route !== null && policyValue(source) !== policyValue(target) && coversContentSignalPattern(source.route, target.route)) {
|
|
919
|
-
connect(broad, narrow);
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
const ordered = [];
|
|
924
|
-
const emitted = /* @__PURE__ */ new Set();
|
|
925
|
-
while (ordered.length < blocks.length) {
|
|
926
|
-
const next = incoming.findIndex((count, index) => count === 0 && !emitted.has(index));
|
|
927
|
-
if (next === -1)
|
|
928
|
-
throw new Error("Content-Signal rules conflict with other header ordering. Place broader mixed policy rules before narrower rules.");
|
|
929
|
-
emitted.add(next);
|
|
930
|
-
ordered.push(blocks[next]);
|
|
931
|
-
for (const target of edges[next])
|
|
932
|
-
incoming[target]--;
|
|
933
|
-
}
|
|
934
|
-
return ordered.map((block) => {
|
|
935
|
-
const text = block.text.trimEnd();
|
|
936
|
-
if (!/^\s+content-signal\s*:/im.test(text) || /^\s+!\s*content-signal\s*$/im.test(text))
|
|
937
|
-
return `${text}
|
|
938
|
-
`;
|
|
939
|
-
return `${text.replace(/^(\s+)(content-signal\s*:)/im, "$1! Content-Signal\n$1$2")}
|
|
940
|
-
`;
|
|
941
|
-
}).join("\n");
|
|
942
|
-
}
|
|
943
|
-
function coversPattern(broad, narrow) {
|
|
944
|
-
if (broad === narrow || !broad.startsWith("/") || !narrow.startsWith("/"))
|
|
945
|
-
return false;
|
|
946
|
-
if (!/[*:]/.test(narrow))
|
|
947
|
-
return patternToRegExp(broad).test(narrow);
|
|
948
|
-
return broad.indexOf("*") === broad.length - 1 && !broad.includes(":") && narrow.startsWith(broad.slice(0, -1));
|
|
949
|
-
}
|
|
950
|
-
function coversContentSignalPattern(broad, narrow) {
|
|
951
|
-
if (coversPattern(broad, narrow))
|
|
952
|
-
return true;
|
|
953
|
-
if (broad === narrow || !broad.startsWith("/") || !narrow.startsWith("/") || broad.indexOf("*") !== broad.length - 1 || !broad.includes(":")) {
|
|
954
|
-
return false;
|
|
955
|
-
}
|
|
956
|
-
const prefix = narrow.split("*")[0];
|
|
957
|
-
return !prefix.includes(":") && patternToRegExp(broad).test(prefix);
|
|
958
|
-
}
|
|
959
|
-
function splitLinkEntries(value) {
|
|
960
|
-
const entries = [];
|
|
961
|
-
let current = "";
|
|
962
|
-
let inUrl = false;
|
|
963
|
-
let inQuote = false;
|
|
964
|
-
for (const char of value) {
|
|
965
|
-
if (char === "<" && !inQuote)
|
|
966
|
-
inUrl = true;
|
|
967
|
-
else if (char === ">" && !inQuote)
|
|
968
|
-
inUrl = false;
|
|
969
|
-
else if (char === '"' && !inUrl)
|
|
970
|
-
inQuote = !inQuote;
|
|
971
|
-
if (char === "," && !inUrl && !inQuote) {
|
|
972
|
-
entries.push(current.trim());
|
|
973
|
-
current = "";
|
|
974
|
-
continue;
|
|
975
|
-
}
|
|
976
|
-
current += char;
|
|
977
|
-
}
|
|
978
|
-
entries.push(current.trim());
|
|
979
|
-
return entries.filter(Boolean);
|
|
980
|
-
}
|
|
981
|
-
function headerTokens(name, value) {
|
|
982
|
-
if (name === "link")
|
|
983
|
-
return splitLinkEntries(value);
|
|
984
|
-
if (name === "vary")
|
|
985
|
-
return value.split(",").map((token) => token.trim()).filter(Boolean);
|
|
986
|
-
return [value.trim()];
|
|
987
|
-
}
|
|
988
|
-
function tokenKey(name, token) {
|
|
989
|
-
return name === "vary" ? token.toLowerCase() : token;
|
|
990
|
-
}
|
|
991
|
-
function dedupeStaticHeaders(contents, names) {
|
|
992
|
-
const owned = new Set(names.map((name) => name.toLowerCase()));
|
|
993
|
-
const blocks = splitHeaderBlocks(contents);
|
|
994
|
-
const detached = /* @__PURE__ */ new Set();
|
|
995
|
-
const parsed = blocks.map((block) => {
|
|
996
|
-
const headers = [];
|
|
997
|
-
for (const line of block.text.split(/(?<=\n)/).slice(block.route === null ? 0 : 1)) {
|
|
998
|
-
const detach = line.match(RE_DETACH_LINE);
|
|
999
|
-
if (detach) {
|
|
1000
|
-
detached.add(detach[1].toLowerCase());
|
|
1001
|
-
continue;
|
|
1002
|
-
}
|
|
1003
|
-
const header = parseHeaderLine(line);
|
|
1004
|
-
if (!header)
|
|
1005
|
-
continue;
|
|
1006
|
-
const name = header.name.toLowerCase();
|
|
1007
|
-
if (owned.has(name))
|
|
1008
|
-
headers.push({ name, tokens: headerTokens(name, header.value) });
|
|
1009
|
-
}
|
|
1010
|
-
return headers;
|
|
1011
|
-
});
|
|
1012
|
-
const lastRuleIndex = /* @__PURE__ */ new Map();
|
|
1013
|
-
blocks.forEach((block, index) => {
|
|
1014
|
-
if (block.route !== null)
|
|
1015
|
-
lastRuleIndex.set(block.route, index);
|
|
1016
|
-
});
|
|
1017
|
-
let changed = false;
|
|
1018
|
-
const output = blocks.map((block) => {
|
|
1019
|
-
const route = block.route;
|
|
1020
|
-
if (route === null)
|
|
1021
|
-
return block.text;
|
|
1022
|
-
const provided = /* @__PURE__ */ new Map();
|
|
1023
|
-
lastRuleIndex.forEach((index, pattern) => {
|
|
1024
|
-
if (!coversPattern(pattern, route))
|
|
1025
|
-
return;
|
|
1026
|
-
for (const { name, tokens } of parsed[index]) {
|
|
1027
|
-
if (detached.has(name))
|
|
1028
|
-
continue;
|
|
1029
|
-
const values = provided.get(name) ?? /* @__PURE__ */ new Set();
|
|
1030
|
-
tokens.forEach((token) => values.add(tokenKey(name, token)));
|
|
1031
|
-
provided.set(name, values);
|
|
1032
|
-
}
|
|
1033
|
-
});
|
|
1034
|
-
if (provided.size === 0)
|
|
1035
|
-
return block.text;
|
|
1036
|
-
const [routeLine, ...lines] = block.text.split(/(?<=\n)/);
|
|
1037
|
-
let headerLines = 0;
|
|
1038
|
-
const kept = lines.flatMap((line) => {
|
|
1039
|
-
const header = parseHeaderLine(line);
|
|
1040
|
-
if (!header) {
|
|
1041
|
-
if (RE_DETACH_LINE.test(line))
|
|
1042
|
-
headerLines++;
|
|
1043
|
-
return [line];
|
|
1044
|
-
}
|
|
1045
|
-
headerLines++;
|
|
1046
|
-
const name = header.name.toLowerCase();
|
|
1047
|
-
const covered = provided.get(name);
|
|
1048
|
-
if (!covered)
|
|
1049
|
-
return [line];
|
|
1050
|
-
const tokens = headerTokens(name, header.value);
|
|
1051
|
-
const remaining = tokens.filter((token) => !covered.has(tokenKey(name, token)));
|
|
1052
|
-
if (remaining.length === tokens.length)
|
|
1053
|
-
return [line];
|
|
1054
|
-
changed = true;
|
|
1055
|
-
if (remaining.length > 0)
|
|
1056
|
-
return [header.withValue(remaining.join(", "))];
|
|
1057
|
-
headerLines--;
|
|
1058
|
-
return [];
|
|
1059
|
-
});
|
|
1060
|
-
return headerLines === 0 ? kept.join("") : `${routeLine}${kept.join("")}`;
|
|
1061
|
-
});
|
|
1062
|
-
return changed ? output.join("") : contents;
|
|
1063
|
-
}
|
|
1064
|
-
const CLOUDFLARE_STATIC_HEADER_RULE_LIMIT = 100;
|
|
1065
|
-
const RE_EXACT_MARKDOWN_ROUTE$1 = /^\/[^*\s]*\.md[\t ]*\r?$/;
|
|
1066
|
-
function splitHeaderBlocks(contents) {
|
|
1067
|
-
const blocks = [];
|
|
1068
|
-
let current = { route: null, text: "" };
|
|
1069
|
-
for (const line of contents.split(/(?<=\n)/)) {
|
|
1070
|
-
const isRoute = /^[^\s#]/.test(line);
|
|
1071
|
-
if (isRoute) {
|
|
1072
|
-
blocks.push(current);
|
|
1073
|
-
current = { route: line.trimEnd(), text: "" };
|
|
1074
|
-
}
|
|
1075
|
-
current.text += line;
|
|
1076
|
-
}
|
|
1077
|
-
blocks.push(current);
|
|
1078
|
-
return blocks;
|
|
1079
|
-
}
|
|
1080
|
-
function enforceStaticHeaderBudget(contents, limit) {
|
|
1081
|
-
const blocks = splitHeaderBlocks(contents);
|
|
1082
|
-
const ruleCount = blocks.filter((block) => block.route !== null).length;
|
|
1083
|
-
if (ruleCount <= limit)
|
|
1084
|
-
return { contents, total: ruleCount, dropped: 0 };
|
|
1085
|
-
const kept = blocks.filter((block) => block.route === null || !RE_EXACT_MARKDOWN_ROUTE$1.test(block.route) || /^\s+(?:content-signal\s*:|!\s*content-signal\s*$)/im.test(block.text));
|
|
1086
|
-
return {
|
|
1087
|
-
contents: kept.map((block) => block.text).join(""),
|
|
1088
|
-
total: kept.filter((block) => block.route !== null).length,
|
|
1089
|
-
dropped: ruleCount - kept.filter((block) => block.route !== null).length
|
|
1090
|
-
};
|
|
1091
|
-
}
|
|
1092
|
-
|
|
1093
|
-
const RE_MD_EXT = /\.md$/;
|
|
1094
|
-
function isStaticMarkdownSourceRoute(route) {
|
|
1095
|
-
if (route.includes("*") || route.includes(":"))
|
|
1096
|
-
return false;
|
|
1097
|
-
return hasMarkdownTwin(route.split("?")[0] || route);
|
|
1098
|
-
}
|
|
1099
|
-
function staticDescribedbyEntry(baseURL) {
|
|
1100
|
-
return `<${encodeURI(toDeployedRoute("/llms.txt", baseURL))}>; rel="describedby"`;
|
|
1101
|
-
}
|
|
1102
|
-
function buildStaticMarkdownLinkHeader(route, baseURL, describedby) {
|
|
1103
|
-
const htmlRoute = encodeURI(toDeployedRoute(normalizePagePath(route), baseURL));
|
|
1104
|
-
const parts = [
|
|
1105
|
-
`<${htmlRoute}>; rel="alternate"; type="text/html"`,
|
|
1106
|
-
`<${htmlRoute}>; rel="canonical"`
|
|
1107
|
-
];
|
|
1108
|
-
if (describedby)
|
|
1109
|
-
parts.push(staticDescribedbyEntry(baseURL));
|
|
1110
|
-
return parts.join(", ");
|
|
1111
|
-
}
|
|
1112
|
-
function pageRouteFromMarkdownTwin(fileName) {
|
|
1113
|
-
if (!fileName?.endsWith(".md") || fileName === SITEMAP_MD_ROUTE)
|
|
1114
|
-
return null;
|
|
1115
|
-
const pageRoute = normalizePagePath(fileName.replace(RE_MD_EXT, ""));
|
|
1116
|
-
if (pageRoute === "/index")
|
|
1117
|
-
return "/";
|
|
1118
|
-
return isStaticMarkdownSourceRoute(pageRoute) ? pageRoute : null;
|
|
1119
|
-
}
|
|
1120
|
-
function prerenderedMarkdownHeaderRules(prerenderedRoutes, baseURL, describedby, artifactRoutes, aiTermsLink) {
|
|
1121
|
-
const artifacts = new Set(artifactRoutes);
|
|
1122
|
-
const rules = /* @__PURE__ */ new Map();
|
|
1123
|
-
for (const entry of prerenderedRoutes) {
|
|
1124
|
-
if (entry.route !== void 0 && artifacts.has(entry.route) || entry.fileName !== void 0 && artifacts.has(entry.fileName)) {
|
|
1125
|
-
continue;
|
|
1126
|
-
}
|
|
1127
|
-
const pageRoute = pageRouteFromMarkdownTwin(entry.fileName);
|
|
1128
|
-
if (pageRoute === null)
|
|
1129
|
-
continue;
|
|
1130
|
-
const mdRoute = toMarkdownPath(pageRoute);
|
|
1131
|
-
if (!rules.has(mdRoute)) {
|
|
1132
|
-
rules.set(mdRoute, {
|
|
1133
|
-
route: mdRoute,
|
|
1134
|
-
headers: {
|
|
1135
|
-
"Content-Type": "text/markdown; charset=utf-8",
|
|
1136
|
-
"Vary": "Accept",
|
|
1137
|
-
"Link": [buildStaticMarkdownLinkHeader(pageRoute, baseURL, describedby), aiTermsLink].filter(Boolean).join(", "),
|
|
1138
|
-
...entry.contentSignal !== void 0 && { "Content-Signal": entry.contentSignal }
|
|
1139
|
-
}
|
|
1140
|
-
});
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
return [...rules.values()];
|
|
1144
|
-
}
|
|
1145
|
-
const RE_EXACT_MARKDOWN_ROUTE = /^\/[^*:\s]*\.md$/;
|
|
1146
|
-
function isStaticHeaderRouteRule([, rule]) {
|
|
1147
|
-
return Boolean(rule && "headers" in rule && rule.headers);
|
|
1148
|
-
}
|
|
1149
|
-
function hasContentSignal$1(headers) {
|
|
1150
|
-
return Object.keys(headers || {}).some((name) => name.toLowerCase() === "content-signal");
|
|
1151
|
-
}
|
|
1152
|
-
function planStaticMarkdownHeaderRules(routeRules, rules, limit) {
|
|
1153
|
-
rules = rules.map((rule) => {
|
|
1154
|
-
if (!hasContentSignal$1(rule.headers) || matchingStaticContentSignals(routeRules, rule.route).length === 0)
|
|
1155
|
-
return rule;
|
|
1156
|
-
return { ...rule, headers: Object.fromEntries(Object.entries(rule.headers).filter(([name]) => name.toLowerCase() !== "content-signal")) };
|
|
1157
|
-
});
|
|
1158
|
-
if (limit === null)
|
|
1159
|
-
return { _tag: "apply", rules };
|
|
1160
|
-
const entries = Object.entries(routeRules).filter(isStaticHeaderRouteRule);
|
|
1161
|
-
const registeredMarkdown = entries.map(([route]) => route).filter((route) => RE_EXACT_MARKDOWN_ROUTE.test(route));
|
|
1162
|
-
const other = entries.length - registeredMarkdown.length;
|
|
1163
|
-
const markdown = /* @__PURE__ */ new Set([...registeredMarkdown, ...rules.map((rule) => rule.route)]);
|
|
1164
|
-
const total = other + markdown.size;
|
|
1165
|
-
if (total <= limit)
|
|
1166
|
-
return { _tag: "apply", rules };
|
|
1167
|
-
const policyRules = rules.filter((rule) => hasContentSignal$1(rule.headers));
|
|
1168
|
-
const policyRoutes = /* @__PURE__ */ new Set([
|
|
1169
|
-
...policyRules.map((rule) => rule.route),
|
|
1170
|
-
...registeredMarkdown.filter((route) => hasContentSignal$1(routeRules[route].headers))
|
|
1171
|
-
]);
|
|
1172
|
-
if (other + policyRoutes.size > limit)
|
|
1173
|
-
return { _tag: "blocked", total: other + policyRoutes.size, limit };
|
|
1174
|
-
return { _tag: "skip", drop: registeredMarkdown.filter((route) => !policyRoutes.has(route)), total, dropped: markdown.size - policyRoutes.size, rules: policyRules };
|
|
1175
|
-
}
|
|
1176
|
-
function applyStaticMarkdownHeaderPlan(routeRules, plan) {
|
|
1177
|
-
if (plan._tag === "blocked")
|
|
1178
|
-
throw new Error(`Content-Signal policy rules exceed the static header limit (${plan.total}/${plan.limit}). Reduce per-page policies or use a shared policy.`);
|
|
1179
|
-
if (plan._tag === "skip") {
|
|
1180
|
-
for (const route of plan.drop) {
|
|
1181
|
-
const rule = routeRules[route];
|
|
1182
|
-
if (rule)
|
|
1183
|
-
rule.headers = void 0;
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
const applied = [];
|
|
1187
|
-
for (const { route, headers } of plan.rules) {
|
|
1188
|
-
const existing = routeRules[route];
|
|
1189
|
-
const merged = defu({ headers: { ...headers } }, existing);
|
|
1190
|
-
if (hasContentSignal$1(existing?.headers)) {
|
|
1191
|
-
for (const name of Object.keys(merged.headers)) {
|
|
1192
|
-
if (name.toLowerCase() === "content-signal")
|
|
1193
|
-
delete merged.headers[name];
|
|
1194
|
-
}
|
|
1195
|
-
for (const [name, value] of Object.entries(existing.headers)) {
|
|
1196
|
-
if (name.toLowerCase() === "content-signal")
|
|
1197
|
-
merged.headers[name] = value;
|
|
1198
|
-
}
|
|
1199
|
-
}
|
|
1200
|
-
const vary = Object.entries(existing?.headers || {}).filter(([name]) => name.toLowerCase() === "vary").map(([, value]) => value).join(", ");
|
|
1201
|
-
if (headers.Vary) {
|
|
1202
|
-
for (const name of Object.keys(merged.headers)) {
|
|
1203
|
-
if (name.toLowerCase() === "vary")
|
|
1204
|
-
delete merged.headers[name];
|
|
1205
|
-
}
|
|
1206
|
-
merged.headers.Vary = mergeVaryHeader(vary, headers.Vary);
|
|
1207
|
-
}
|
|
1208
|
-
routeRules[route] = merged;
|
|
1209
|
-
applied.push([route, merged.headers]);
|
|
1210
|
-
}
|
|
1211
|
-
return applied;
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
const MAX_WORKER_FIRST_PATTERNS = 100;
|
|
1215
|
-
const RE_PATTERN_CHARACTERS = /[.+?^${}()|[\]\\]/g;
|
|
1216
|
-
function cloudflarePrerenderedPages(routes, baseURL) {
|
|
1217
|
-
return [...new Set(routes.filter((entry) => !entry.error && entry.fileName?.endsWith(".html") && isStaticMarkdownSourceRoute(entry.route)).map((entry) => normalizePagePath(toDeployedRoute(normalizePagePath(entry.route), baseURL))))];
|
|
1218
|
-
}
|
|
1219
|
-
function matchesPattern(path, pattern) {
|
|
1220
|
-
return new RegExp(`^${pattern.replace(RE_PATTERN_CHARACTERS, "\\$&").replaceAll("*", ".*")}$`).test(path);
|
|
1221
|
-
}
|
|
1222
|
-
function pagePaths(pages) {
|
|
1223
|
-
return pages.flatMap((page) => page === "/" ? ["/"] : [page, `${page}/`]);
|
|
1224
|
-
}
|
|
1225
|
-
function cloudflareStaticFallbackPaths(existing, pages, environments = []) {
|
|
1226
|
-
if (existing === true || existing === false || environments.includes(true))
|
|
1227
|
-
return [];
|
|
1228
|
-
const patterns = [...existing || [], ...environments.flatMap((routing) => Array.isArray(routing) ? routing : [])];
|
|
1229
|
-
return pagePaths(pages).filter((path) => !patterns.some((pattern) => matchesPattern(path, pattern.startsWith("!") ? pattern.slice(1) : pattern)));
|
|
1230
|
-
}
|
|
1231
|
-
function parentDirectories(path) {
|
|
1232
|
-
const segments = path.split("/").filter(Boolean);
|
|
1233
|
-
return segments.slice(0, -1).map((_, index) => `/${segments.slice(0, index + 1).join("/")}/`);
|
|
1234
|
-
}
|
|
1235
|
-
function fitWorkerFirstBudget(paths, budget) {
|
|
1236
|
-
let remaining = [...paths];
|
|
1237
|
-
const globs = [];
|
|
1238
|
-
while (remaining.length + globs.length > budget) {
|
|
1239
|
-
const counts = /* @__PURE__ */ new Map();
|
|
1240
|
-
for (const path of remaining) {
|
|
1241
|
-
for (const directory2 of parentDirectories(path))
|
|
1242
|
-
counts.set(directory2, (counts.get(directory2) ?? 0) + 1);
|
|
1243
|
-
}
|
|
1244
|
-
let best;
|
|
1245
|
-
for (const [directory2, count] of counts) {
|
|
1246
|
-
if (!best || count > best[1] || count === best[1] && directory2.length > best[0].length)
|
|
1247
|
-
best = [directory2, count];
|
|
1248
|
-
}
|
|
1249
|
-
if (!best || best[1] < 2)
|
|
1250
|
-
return void 0;
|
|
1251
|
-
const [directory] = best;
|
|
1252
|
-
globs.push(`${directory}*`);
|
|
1253
|
-
remaining = remaining.filter((path) => !path.startsWith(directory) || path === directory);
|
|
1254
|
-
}
|
|
1255
|
-
return [...remaining, ...globs];
|
|
1256
|
-
}
|
|
1257
|
-
function cloudflareWorkerFirstAdditions(existing, pages) {
|
|
1258
|
-
if (existing === true || existing === false || pages.length === 0)
|
|
1259
|
-
return [];
|
|
1260
|
-
const patterns = existing || [];
|
|
1261
|
-
const paths = cloudflareStaticFallbackPaths(existing, pages).filter((path) => !patterns.includes(path));
|
|
1262
|
-
const additions = fitWorkerFirstBudget(paths, MAX_WORKER_FIRST_PATTERNS - patterns.length);
|
|
1263
|
-
if (!additions) {
|
|
1264
|
-
throw new Error("Cloudflare Markdown negotiation exceeds 100 worker-first patterns, even with directory globs. Configure broader assets.run_worker_first patterns, or disable aiReady.contentNegotiation.");
|
|
1265
|
-
}
|
|
1266
|
-
return additions;
|
|
1267
|
-
}
|
|
1268
|
-
|
|
1269
|
-
const CACHE_GUIDE = "https://nuxtseo.com/docs/ai-ready/guides/markdown#cache-safety";
|
|
1270
|
-
function cacheFix(botNegotiation = false) {
|
|
1271
|
-
const headers = getContentNegotiationVary(botNegotiation).split(",").map((header) => `'${header.trim().toLowerCase()}'`).join(", ");
|
|
1272
|
-
return [
|
|
1273
|
-
...botNegotiation ? [
|
|
1274
|
-
"For lower cache cost, set aiReady: { botNegotiation: false } and keep Accept-only negotiation.",
|
|
1275
|
-
"To retain bot negotiation, include all three inputs in this route's cache key.",
|
|
1276
|
-
"Raw User-Agent variation can create many cache entries."
|
|
1277
|
-
] : [],
|
|
1278
|
-
`Add to this route rule: cache: { varies: [${headers}] }`,
|
|
1279
|
-
"Keep existing cache options and varies entries.",
|
|
1280
|
-
"HTTP Vary alone does not change Nitro's cache key.",
|
|
1281
|
-
"If a CDN ignores Vary, set aiReady: { contentNegotiation: false } and use explicit .md URLs."
|
|
1282
|
-
].join("\n ");
|
|
1283
|
-
}
|
|
1284
|
-
function resolveConfigurationWarnings(input) {
|
|
1285
|
-
const warnings = [];
|
|
1286
|
-
const hostname = input.siteUrl && URL.canParse(input.siteUrl) ? new URL(input.siteUrl).hostname : "";
|
|
1287
|
-
if (input.reportSiteUrl !== false && (!hostname || hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "[::1]")) {
|
|
1288
|
-
warnings.push('Set site.url to the public production URL. Discovery catalogs and canonical Markdown links need a public origin.\n In nuxt.config.ts, set site: { url: "https://your-domain.com" }. Replace the example with your production origin.');
|
|
1289
|
-
}
|
|
1290
|
-
if (input.policy === "disabled") {
|
|
1291
|
-
warnings.push(`contentNegotiation: false disables Accept and bot negotiation.
|
|
1292
|
-
Remove aiReady.contentNegotiation from nuxt.config.ts to restore automatic negotiation.
|
|
1293
|
-
If disabled intentionally, link explicit .md URLs and verify they resolve after deployment.
|
|
1294
|
-
Guide: ${CACHE_GUIDE}`);
|
|
1295
|
-
} else if (input.static) {
|
|
1296
|
-
warnings.push(`Static output cannot run Markdown negotiation middleware.
|
|
1297
|
-
Link the generated .md URLs, or use a server deployment for automatic negotiation.
|
|
1298
|
-
For edge negotiation, preserve these inputs: ${getContentNegotiationVary(input.botNegotiation)}.
|
|
1299
|
-
Guide: ${CACHE_GUIDE}`);
|
|
1300
|
-
}
|
|
1301
|
-
const match = createNitroRouteRuleMatcher({ nitro: { routeRules: input.routeRules } });
|
|
1302
|
-
for (const route of Object.keys(input.routeRules).sort()) {
|
|
1303
|
-
if (!hasMarkdownTwin(route) || route.startsWith("/.well-known/"))
|
|
1304
|
-
continue;
|
|
1305
|
-
const rule = match(route);
|
|
1306
|
-
if (rule.redirect || rule.proxy)
|
|
1307
|
-
continue;
|
|
1308
|
-
if (input.static || input.policy === "disabled")
|
|
1309
|
-
continue;
|
|
1310
|
-
const automatic = resolveContentNegotiation({ policy: "auto", routeRule: rule, botNegotiation: input.botNegotiation });
|
|
1311
|
-
const fixCache = cacheFix(input.botNegotiation);
|
|
1312
|
-
if (automatic._tag === "enabled")
|
|
1313
|
-
continue;
|
|
1314
|
-
if (input.policy === "enabled") {
|
|
1315
|
-
const fix = automatic.source === "isr" ? `ISR cannot use automatic negotiation. Set isr: false on this route, or use explicit .md URLs.${rule.cache ? `
|
|
1316
|
-
${fixCache}` : ""}` : fixCache;
|
|
1317
|
-
warnings.push(`"${route}": contentNegotiation: true overrides cache protection.
|
|
1318
|
-
Remove aiReady.contentNegotiation from nuxt.config.ts to restore automatic cache protection.
|
|
1319
|
-
${fix}
|
|
1320
|
-
Guide: ${CACHE_GUIDE}`);
|
|
1321
|
-
} else if (automatic.source === "isr") {
|
|
1322
|
-
warnings.push(`"${route}": ISR disables automatic Markdown negotiation.
|
|
1323
|
-
To keep ISR, use explicit .md URLs.
|
|
1324
|
-
To use negotiation, set isr: false on this route in nuxt.config.ts.${rule.cache ? `
|
|
1325
|
-
${fixCache}` : ""}
|
|
1326
|
-
Guide: ${CACHE_GUIDE}`);
|
|
1327
|
-
} else {
|
|
1328
|
-
warnings.push(`"${route}": response caching disables automatic Markdown negotiation.
|
|
1329
|
-
In nuxt.config.ts:
|
|
1330
|
-
${fixCache}
|
|
1331
|
-
Guide: ${CACHE_GUIDE}`);
|
|
1332
|
-
}
|
|
1333
|
-
}
|
|
1334
|
-
return warnings;
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
const DEFAULT_CONTENT_SIGNAL = "search=yes, ai-input=yes";
|
|
1338
|
-
function resolveContentSignalPolicy(option) {
|
|
1339
|
-
if (option === false)
|
|
1340
|
-
return { _tag: "Disabled" };
|
|
1341
|
-
if (option === void 0)
|
|
1342
|
-
return { _tag: "Default" };
|
|
1343
|
-
const value = (allowed) => allowed ? "yes" : "no";
|
|
1344
|
-
return {
|
|
1345
|
-
_tag: "Configured",
|
|
1346
|
-
// One comma-separated line: validators reject one line per signal.
|
|
1347
|
-
contentSignal: `ai-train=${value(option.aiTrain)}, search=${value(option.search)}, ai-input=${value(option.aiInput)}`,
|
|
1348
|
-
// Opt-in: Lighthouse's robots-txt audit fails Content-Usage as an unknown directive.
|
|
1349
|
-
...option.contentUsage === true && { contentUsage: `train-ai=${option.aiTrain ? "y" : "n"}` }
|
|
1350
|
-
};
|
|
1351
|
-
}
|
|
1352
|
-
function hasContentSignal(value) {
|
|
1353
|
-
if (Array.isArray(value))
|
|
1354
|
-
return value.some(Boolean);
|
|
1355
|
-
if (value && typeof value === "object")
|
|
1356
|
-
return Object.keys(value).length > 0;
|
|
1357
|
-
return Boolean(value);
|
|
1358
|
-
}
|
|
1359
|
-
function isWildcardGroup(group) {
|
|
1360
|
-
const userAgents = Array.isArray(group.userAgent) ? group.userAgent : [group.userAgent ?? "*"];
|
|
1361
|
-
return userAgents.length === 1 && userAgents[0] === "*";
|
|
1362
|
-
}
|
|
1363
|
-
function wildcardGroup(groups) {
|
|
1364
|
-
const existing = groups.find(isWildcardGroup);
|
|
1365
|
-
if (existing)
|
|
1366
|
-
return existing;
|
|
1367
|
-
const group = { userAgent: ["*"], disallow: [""] };
|
|
1368
|
-
groups.push(group);
|
|
1369
|
-
return group;
|
|
1370
|
-
}
|
|
1371
|
-
function applyContentSignalPolicy(groups, policy) {
|
|
1372
|
-
switch (policy._tag) {
|
|
1373
|
-
case "Disabled":
|
|
1374
|
-
return;
|
|
1375
|
-
case "Default": {
|
|
1376
|
-
if (groups.some((group) => hasContentSignal(group.contentSignal)))
|
|
1377
|
-
return;
|
|
1378
|
-
wildcardGroup(groups).contentSignal = [DEFAULT_CONTENT_SIGNAL];
|
|
1379
|
-
return;
|
|
1380
|
-
}
|
|
1381
|
-
case "Configured": {
|
|
1382
|
-
const group = wildcardGroup(groups);
|
|
1383
|
-
group.contentSignal = [policy.contentSignal];
|
|
1384
|
-
if (policy.contentUsage)
|
|
1385
|
-
group.contentUsage = [policy.contentUsage];
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
const AI_READY_CRON_SCHEDULE = "*/5 * * * *";
|
|
1391
|
-
|
|
1392
|
-
const DATABASE_TYPE_NONE = "none";
|
|
1393
|
-
const DATABASE_DEPENDENT_OPTIONS = ["runtimeSync", "cron"];
|
|
1394
|
-
const DATABASE_CONSUMER_LABELS = {
|
|
1395
|
-
runtimeSync: "runtime indexing (`aiReady.runtimeSync`)",
|
|
1396
|
-
cron: "the indexing cron (`aiReady.cron`)",
|
|
1397
|
-
mcp: "MCP site tools (`@nuxtjs/mcp-toolkit`)",
|
|
1398
|
-
webmcp: "WebMCP site tools (`aiReady.webmcp`)"
|
|
1399
|
-
};
|
|
1400
|
-
const RE_SEMVER = /^v?(\d+)\.(\d+)\.(\d+)(?:-([\da-z-]+(?:\.[\da-z-]+)*))?(?:\+[\da-z-]+(?:\.[\da-z-]+)*)?$/i;
|
|
1401
|
-
const RE_NUMERIC = /^\d+$/;
|
|
1402
|
-
function parseSemVer(input) {
|
|
1403
|
-
const match = RE_SEMVER.exec(input.trim());
|
|
1404
|
-
if (!match)
|
|
1405
|
-
return void 0;
|
|
1406
|
-
return {
|
|
1407
|
-
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
1408
|
-
prerelease: match[4]?.split(".") ?? []
|
|
1409
|
-
};
|
|
1410
|
-
}
|
|
1411
|
-
function compareCore(a, b) {
|
|
1412
|
-
for (let i = 0; i < 3; i++) {
|
|
1413
|
-
if (a[i] !== b[i])
|
|
1414
|
-
return a[i] < b[i] ? -1 : 1;
|
|
1415
|
-
}
|
|
1416
|
-
return 0;
|
|
1417
|
-
}
|
|
1418
|
-
function comparePrerelease(a, b) {
|
|
1419
|
-
if (a.length === 0 && b.length === 0)
|
|
1420
|
-
return 0;
|
|
1421
|
-
if (a.length === 0)
|
|
1422
|
-
return 1;
|
|
1423
|
-
if (b.length === 0)
|
|
1424
|
-
return -1;
|
|
1425
|
-
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
1426
|
-
const left = a[i];
|
|
1427
|
-
const right = b[i];
|
|
1428
|
-
if (left === void 0)
|
|
1429
|
-
return -1;
|
|
1430
|
-
if (right === void 0)
|
|
1431
|
-
return 1;
|
|
1432
|
-
if (left === right)
|
|
1433
|
-
continue;
|
|
1434
|
-
const leftNumeric = RE_NUMERIC.test(left);
|
|
1435
|
-
const rightNumeric = RE_NUMERIC.test(right);
|
|
1436
|
-
if (leftNumeric && rightNumeric)
|
|
1437
|
-
return Number(left) < Number(right) ? -1 : 1;
|
|
1438
|
-
if (leftNumeric !== rightNumeric)
|
|
1439
|
-
return leftNumeric ? -1 : 1;
|
|
1440
|
-
return left < right ? -1 : 1;
|
|
1441
|
-
}
|
|
1442
|
-
return 0;
|
|
1443
|
-
}
|
|
1444
|
-
function matchCaretRange(version, range) {
|
|
1445
|
-
const installed = parseSemVer(version);
|
|
1446
|
-
const minimum = range.trim().startsWith("^") ? parseSemVer(range.trim().slice(1)) : void 0;
|
|
1447
|
-
if (!installed || !minimum)
|
|
1448
|
-
return { _tag: "Unparsed" };
|
|
1449
|
-
const [major, minor, patch] = minimum.core;
|
|
1450
|
-
const ceiling = major > 0 ? [major + 1, 0, 0] : minor > 0 ? [0, minor + 1, 0] : [0, 0, patch + 1];
|
|
1451
|
-
const sameCore = compareCore(installed.core, minimum.core) === 0;
|
|
1452
|
-
const satisfied = (compareCore(installed.core, minimum.core) > 0 || sameCore && comparePrerelease(installed.prerelease, minimum.prerelease) >= 0) && compareCore(installed.core, ceiling) < 0 && (installed.prerelease.length === 0 || sameCore && minimum.prerelease.length > 0);
|
|
1453
|
-
return satisfied ? { _tag: "Satisfied" } : { _tag: "Unsatisfied" };
|
|
1454
|
-
}
|
|
1455
|
-
function checkDrizzleInstall(install, peerRange) {
|
|
1456
|
-
if (install._tag === "Missing")
|
|
1457
|
-
return { _tag: "Missing" };
|
|
1458
|
-
if (!install.version || !peerRange)
|
|
1459
|
-
return void 0;
|
|
1460
|
-
return matchCaretRange(install.version, peerRange)._tag === "Unsatisfied" ? { _tag: "OutOfRange", version: install.version } : void 0;
|
|
1461
|
-
}
|
|
1462
|
-
function formatDrizzleMessage(input) {
|
|
1463
|
-
const consumers = Object.keys(DATABASE_CONSUMER_LABELS).filter((consumer) => input.requested[consumer]);
|
|
1464
|
-
const subject = consumers.length === 0 ? "The `aiReady.database` option turns on the database." : `These features need the database: ${consumers.map((consumer) => DATABASE_CONSUMER_LABELS[consumer]).join(", ")}.`;
|
|
1465
|
-
const version = input.peerRange?.replace(/^\^/, "");
|
|
1466
|
-
const command = `npx nypm add drizzle-orm${version ? `@${version}` : ""}`;
|
|
1467
|
-
const lines = input.problem._tag === "Missing" ? [
|
|
1468
|
-
subject,
|
|
1469
|
-
"The database needs `drizzle-orm`. This app does not install it.",
|
|
1470
|
-
`Install it: ${command}`
|
|
1471
|
-
] : [
|
|
1472
|
-
subject,
|
|
1473
|
-
`The database needs \`drizzle-orm\` ${input.peerRange}. This app installs ${input.problem.version}.`,
|
|
1474
|
-
`Upgrade it: ${command}`
|
|
1475
|
-
];
|
|
1476
|
-
if (consumers.length > 0 && consumers.every((consumer) => consumer === "mcp" || consumer === "webmcp"))
|
|
1477
|
-
lines.push("If you do not need the site tools, set `aiReady.database: false`.");
|
|
1478
|
-
return lines.join("\n");
|
|
1479
|
-
}
|
|
1480
|
-
const DEFAULT_SQLITE_FILENAME = ".data/ai-ready/pages.db";
|
|
1481
|
-
function formatConflictMessage(conflicts) {
|
|
1482
|
-
const names = conflicts.map((option) => `\`aiReady.${option}\``).join(", ");
|
|
1483
|
-
return `The database is disabled, so these options cannot run: ${names}. Remove the listed options, or enable the database.`;
|
|
1484
|
-
}
|
|
1485
|
-
function resolveDatabaseType(options, preset, hasPostgresUrl, logs) {
|
|
1486
|
-
if (options.type && options.type !== DATABASE_TYPE_NONE)
|
|
1487
|
-
return options.type;
|
|
1488
|
-
if (preset.startsWith("cloudflare")) {
|
|
1489
|
-
logs.push({ level: "debug", message: `Auto-detected Cloudflare preset "${preset}", using D1 database` });
|
|
1490
|
-
return "d1";
|
|
1491
|
-
}
|
|
1492
|
-
const isVercel = preset === "vercel" || preset === "vercel-edge";
|
|
1493
|
-
if (isVercel && hasPostgresUrl) {
|
|
1494
|
-
logs.push({ level: "debug", message: `Auto-detected Vercel preset with POSTGRES_URL, using Neon serverless driver` });
|
|
1495
|
-
return "neon";
|
|
1496
|
-
}
|
|
1497
|
-
if (preset === "vercel-edge") {
|
|
1498
|
-
logs.push({
|
|
1499
|
-
level: "warn",
|
|
1500
|
-
message: `Vercel Edge has no filesystem. Set POSTGRES_URL (Vercel Postgres) or configure database.type: 'libsql' for full functionality.`
|
|
1501
|
-
});
|
|
1502
|
-
return "neon";
|
|
1503
|
-
}
|
|
1504
|
-
if (preset === "bun") {
|
|
1505
|
-
logs.push({ level: "debug", message: `Auto-detected Bun preset, using bun:sqlite driver` });
|
|
1506
|
-
return "bun";
|
|
1507
|
-
}
|
|
1508
|
-
return "sqlite";
|
|
1509
|
-
}
|
|
1510
|
-
function resolveDatabaseConfig(input) {
|
|
1511
|
-
const options = input.database === false ? void 0 : input.database;
|
|
1512
|
-
const explicitlyDisabled = input.database === false || options?.type === DATABASE_TYPE_NONE;
|
|
1513
|
-
if (explicitlyDisabled) {
|
|
1514
|
-
const conflicts = DATABASE_DEPENDENT_OPTIONS.filter((option) => input.requested[option]);
|
|
1515
|
-
if (conflicts.length > 0)
|
|
1516
|
-
return { _tag: "Invalid", conflicts, message: formatConflictMessage(conflicts) };
|
|
1517
|
-
return { _tag: "Resolved", database: { _tag: "Disabled" }, logs: [] };
|
|
1518
|
-
}
|
|
1519
|
-
const databaseNeeded = Object.values(input.requested).some(Boolean);
|
|
1520
|
-
if (input.database === void 0 && !databaseNeeded)
|
|
1521
|
-
return { _tag: "Resolved", database: { _tag: "Disabled" }, logs: [] };
|
|
1522
|
-
const logs = [];
|
|
1523
|
-
const config = options || {};
|
|
1524
|
-
const type = resolveDatabaseType(config, input.preset, input.hasPostgresUrl, logs);
|
|
1525
|
-
if (type === "sqlite" || type === "bun") {
|
|
1526
|
-
const filename = config.filename || DEFAULT_SQLITE_FILENAME;
|
|
1527
|
-
return {
|
|
1528
|
-
_tag: "Resolved",
|
|
1529
|
-
logs,
|
|
1530
|
-
database: {
|
|
1531
|
-
_tag: "Enabled",
|
|
1532
|
-
type,
|
|
1533
|
-
filename: isAbsolute(filename) ? filename : join$1(input.rootDir, filename)
|
|
1534
|
-
}
|
|
1535
|
-
};
|
|
1536
|
-
}
|
|
1537
|
-
if (type === "d1") {
|
|
1538
|
-
return {
|
|
1539
|
-
_tag: "Resolved",
|
|
1540
|
-
logs,
|
|
1541
|
-
database: { _tag: "Enabled", type, bindingName: config.bindingName || "DB" }
|
|
1542
|
-
};
|
|
1543
|
-
}
|
|
1544
|
-
if (type === "neon" || type === "postgres") {
|
|
1545
|
-
return {
|
|
1546
|
-
_tag: "Resolved",
|
|
1547
|
-
logs,
|
|
1548
|
-
database: { _tag: "Enabled", type, url: config.url }
|
|
1549
|
-
};
|
|
1550
|
-
}
|
|
1551
|
-
return {
|
|
1552
|
-
_tag: "Resolved",
|
|
1553
|
-
logs,
|
|
1554
|
-
database: { _tag: "Enabled", type: "libsql", url: config.url, authToken: config.authToken }
|
|
1555
|
-
};
|
|
1556
|
-
}
|
|
1557
|
-
|
|
1558
|
-
const CJK_PREFIXES = ["zh", "ja", "ko"];
|
|
1559
|
-
function hasCjkLocale(i18n) {
|
|
1560
|
-
return i18n.locales.some((l) => CJK_PREFIXES.some((p) => l.code.startsWith(p) || l.hreflang.startsWith(p)));
|
|
1561
|
-
}
|
|
1562
|
-
function resolvePagePath(parentPath, routePath) {
|
|
1563
|
-
const normalizedRoutePath = routePath.replace(/:(\w+)\(\)/g, "[$1]");
|
|
1564
|
-
if (normalizedRoutePath.startsWith("/"))
|
|
1565
|
-
return normalizedRoutePath;
|
|
1566
|
-
if (!normalizedRoutePath)
|
|
1567
|
-
return parentPath || "/";
|
|
1568
|
-
return `${parentPath === "/" ? "" : parentPath.replace(/\/$/, "")}/${normalizedRoutePath}`;
|
|
1569
|
-
}
|
|
1570
|
-
function collectPagePaths(routes, parentPath = "") {
|
|
1571
|
-
return routes.reduce((paths, route) => {
|
|
1572
|
-
const path = resolvePagePath(parentPath, route.path);
|
|
1573
|
-
if (route.name)
|
|
1574
|
-
paths.set(route.name, path);
|
|
1575
|
-
if (route.children?.length) {
|
|
1576
|
-
for (const [name, childPath] of collectPagePaths(route.children, path))
|
|
1577
|
-
paths.set(name, childPath);
|
|
1578
|
-
}
|
|
1579
|
-
return paths;
|
|
1580
|
-
}, /* @__PURE__ */ new Map());
|
|
1581
|
-
}
|
|
1582
|
-
function isUnlocalizedLocalePage(page) {
|
|
1583
|
-
return page?._tag === "unlocalized" && typeof page.path === "string";
|
|
1584
|
-
}
|
|
1585
|
-
function materializeI18nPages(i18n, routes) {
|
|
1586
|
-
if (!i18n.pages)
|
|
1587
|
-
return void 0;
|
|
1588
|
-
const pagePaths = collectPagePaths(routes);
|
|
1589
|
-
return Object.fromEntries(Object.entries(i18n.pages).map(([pageName, pageLocales]) => {
|
|
1590
|
-
if (isUnlocalizedLocalePage(pageLocales))
|
|
1591
|
-
return [pageName, pageLocales];
|
|
1592
|
-
const defaultPath = pageLocales?.[i18n.defaultLocale];
|
|
1593
|
-
const fallbackPath = typeof defaultPath === "string" ? defaultPath : pagePaths.get(pageName);
|
|
1594
|
-
const locales = Object.fromEntries(i18n.locales.flatMap((locale) => {
|
|
1595
|
-
const configuredPath = pageLocales?.[locale.code];
|
|
1596
|
-
if (configuredPath !== void 0)
|
|
1597
|
-
return [[locale.code, configuredPath]];
|
|
1598
|
-
return fallbackPath === void 0 ? [] : [[locale.code, fallbackPath]];
|
|
1599
|
-
}));
|
|
1600
|
-
return [pageName, locales];
|
|
1601
|
-
}));
|
|
1602
|
-
}
|
|
1603
|
-
function toRuntimeI18nConfig(auto, routes = []) {
|
|
1604
|
-
const runtime = toRuntimeI18nConfig$1(auto);
|
|
1605
|
-
if (!runtime.pages || !routes.length)
|
|
1606
|
-
return runtime;
|
|
1607
|
-
return { ...runtime, pages: materializeI18nPages(runtime, routes) };
|
|
1608
|
-
}
|
|
1609
|
-
async function detectI18n(opts = {}) {
|
|
1610
|
-
if (opts.autoI18n === false)
|
|
1611
|
-
return null;
|
|
1612
|
-
const auto = await resolveI18nConfig({ warn: (msg) => logger.warn(msg) });
|
|
1613
|
-
if (!auto)
|
|
1614
|
-
return null;
|
|
1615
|
-
if (!auto.locales?.length) {
|
|
1616
|
-
logger.warn("[ai-ready] @nuxtjs/i18n detected but no locales configured. i18n integration disabled.");
|
|
1617
|
-
return null;
|
|
1618
|
-
}
|
|
1619
|
-
logger.debug(`[ai-ready] i18n detected: ${auto.locales.length} locales, strategy=${auto.strategy}, default=${auto.defaultLocale}`);
|
|
1620
|
-
return toRuntimeI18nConfig(auto);
|
|
1621
|
-
}
|
|
1622
|
-
|
|
1623
|
-
function hasConfiguredNuxtModule(modules, name) {
|
|
1624
|
-
return modules.some((entry) => {
|
|
1625
|
-
const module = Array.isArray(entry) ? entry[0] : entry;
|
|
1626
|
-
if (typeof module === "string")
|
|
1627
|
-
return module === name;
|
|
1628
|
-
if ((typeof module === "function" || typeof module === "object" && module !== null) && "meta" in module)
|
|
1629
|
-
return module.meta?.name === name;
|
|
1630
|
-
return false;
|
|
1631
|
-
});
|
|
1632
|
-
}
|
|
1633
|
-
function resolveMcpToolkitState(input) {
|
|
1634
|
-
if (!input.installed)
|
|
1635
|
-
return { _tag: "Absent" };
|
|
1636
|
-
if (input.options === false || input.options?.enabled === false)
|
|
1637
|
-
return { _tag: "Disabled" };
|
|
1638
|
-
if (input.static || input.generating)
|
|
1639
|
-
return { _tag: "Static" };
|
|
1640
|
-
return { _tag: "Enabled", route: input.options?.route || "/mcp" };
|
|
1641
|
-
}
|
|
1642
|
-
|
|
1643
|
-
const MCP_SERVER_CARD_SCHEMA = "https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json";
|
|
1644
|
-
const MCP_SERVER_CARD_NAME_PATTERN = /^[a-z\d.-]+\/[a-z\d._-]+$/i;
|
|
1645
|
-
const allowedConfigKeys = /* @__PURE__ */ new Set([
|
|
1646
|
-
"cacheMaxAge",
|
|
1647
|
-
"description",
|
|
1648
|
-
"name",
|
|
1649
|
-
"title",
|
|
1650
|
-
"websiteUrl"
|
|
1651
|
-
]);
|
|
1652
|
-
function isRecord(value) {
|
|
1653
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1654
|
-
}
|
|
1655
|
-
function isNonEmptyString(value) {
|
|
1656
|
-
return typeof value === "string" && value.trim().length > 0;
|
|
1657
|
-
}
|
|
1658
|
-
function isHttpUrl(value) {
|
|
1659
|
-
return URL.canParse(value) && ["http:", "https:"].includes(new URL(value).protocol);
|
|
1660
|
-
}
|
|
1661
|
-
function isValidCardName(value) {
|
|
1662
|
-
return value.length >= 3 && value.length <= 200 && MCP_SERVER_CARD_NAME_PATTERN.test(value);
|
|
1663
|
-
}
|
|
1664
|
-
function parseMcpServerCardConfig(input) {
|
|
1665
|
-
if (input === false)
|
|
1666
|
-
return { _tag: "Disabled" };
|
|
1667
|
-
if (input !== void 0 && !isRecord(input)) {
|
|
1668
|
-
return {
|
|
1669
|
-
_tag: "Invalid",
|
|
1670
|
-
message: "`aiReady.mcpServerCard` must be false or an options object."
|
|
1671
|
-
};
|
|
1672
|
-
}
|
|
1673
|
-
const config = input || {};
|
|
1674
|
-
const unknownKeys = Object.keys(config).filter((key) => !allowedConfigKeys.has(key));
|
|
1675
|
-
if (unknownKeys.length) {
|
|
1676
|
-
return {
|
|
1677
|
-
_tag: "Invalid",
|
|
1678
|
-
message: `Unknown \`aiReady.mcpServerCard\` option(s): ${unknownKeys.join(", ")}.`
|
|
1679
|
-
};
|
|
1680
|
-
}
|
|
1681
|
-
if (config.name !== void 0 && (!isNonEmptyString(config.name) || !isValidCardName(config.name))) {
|
|
1682
|
-
return {
|
|
1683
|
-
_tag: "Invalid",
|
|
1684
|
-
message: "`aiReady.mcpServerCard.name` must use reverse-DNS/server format."
|
|
1685
|
-
};
|
|
1686
|
-
}
|
|
1687
|
-
for (const key of ["description", "title"]) {
|
|
1688
|
-
if (config[key] !== void 0 && (!isNonEmptyString(config[key]) || config[key].length > 100)) {
|
|
1689
|
-
return {
|
|
1690
|
-
_tag: "Invalid",
|
|
1691
|
-
message: `\`aiReady.mcpServerCard.${key}\` must contain 1 to 100 characters.`
|
|
1692
|
-
};
|
|
1693
|
-
}
|
|
1694
|
-
}
|
|
1695
|
-
if (config.websiteUrl !== void 0 && (!isNonEmptyString(config.websiteUrl) || !isHttpUrl(config.websiteUrl))) {
|
|
1696
|
-
return {
|
|
1697
|
-
_tag: "Invalid",
|
|
1698
|
-
message: "`aiReady.mcpServerCard.websiteUrl` must be an absolute HTTP(S) URL."
|
|
1699
|
-
};
|
|
1700
|
-
}
|
|
1701
|
-
if (config.cacheMaxAge !== void 0 && (typeof config.cacheMaxAge !== "number" || !Number.isInteger(config.cacheMaxAge) || config.cacheMaxAge < 0)) {
|
|
1702
|
-
return {
|
|
1703
|
-
_tag: "Invalid",
|
|
1704
|
-
message: "`aiReady.mcpServerCard.cacheMaxAge` must be a non-negative integer."
|
|
1705
|
-
};
|
|
1706
|
-
}
|
|
1707
|
-
return {
|
|
1708
|
-
_tag: "Enabled",
|
|
1709
|
-
config: {
|
|
1710
|
-
...config,
|
|
1711
|
-
cacheMaxAge: config.cacheMaxAge ?? 3600
|
|
1712
|
-
}
|
|
1713
|
-
};
|
|
1714
|
-
}
|
|
1715
|
-
const MCP_SERVER_CARD_WELL_KNOWN_PATHS = ["/.well-known/mcp/server-card.json", "/.well-known/mcp.json"];
|
|
1716
|
-
function resolveMcpServerCardRoute(mcpRoute) {
|
|
1717
|
-
return `${mcpRoute.replace(/\/+$/, "") || "/mcp"}/server-card`;
|
|
1718
|
-
}
|
|
1719
|
-
function resolveMcpServerCardName(input) {
|
|
1720
|
-
if (input.overrideName) {
|
|
1721
|
-
return isValidCardName(input.overrideName) ? { _tag: "Resolved", name: input.overrideName } : { _tag: "Invalid", message: "The MCP Server Card name must use reverse-DNS/server format." };
|
|
1722
|
-
}
|
|
1723
|
-
const siteHostname = input.siteUrl && URL.canParse(input.siteUrl) ? new URL(input.siteUrl).hostname : void 0;
|
|
1724
|
-
const hostname = siteHostname ? siteHostname.split(".").filter(Boolean).reverse().join(".") : "local.invalid";
|
|
1725
|
-
const routeName = input.route.split("/").filter(Boolean).at(-1)?.normalize("NFKD").replace(/[\u0300-\u036F]/g, "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[._-]+|[._-]+$/g, "") || "mcp";
|
|
1726
|
-
const name = `${hostname}/${routeName}`;
|
|
1727
|
-
return isValidCardName(name) ? { _tag: "Resolved", name } : {
|
|
1728
|
-
_tag: "Invalid",
|
|
1729
|
-
message: "Could not derive a valid MCP Server Card name; configure `aiReady.mcpServerCard.name`."
|
|
1730
|
-
};
|
|
1731
|
-
}
|
|
1732
|
-
function parseSupportedMcpProtocolVersions(source) {
|
|
1733
|
-
const latestMatch = source.match(/LATEST_PROTOCOL_VERSION\s*=\s*['"]([^'"]+)['"]/);
|
|
1734
|
-
const supportedMatch = source.match(/SUPPORTED_PROTOCOL_VERSIONS\s*=\s*\[([\s\S]*?)\]/);
|
|
1735
|
-
if (!latestMatch?.[1] || !supportedMatch?.[1]) {
|
|
1736
|
-
return {
|
|
1737
|
-
_tag: "Invalid",
|
|
1738
|
-
message: "Could not read SUPPORTED_PROTOCOL_VERSIONS from the installed MCP SDK."
|
|
1739
|
-
};
|
|
1740
|
-
}
|
|
1741
|
-
const versionEntryPattern = /(?:exports\.)?LATEST_PROTOCOL_VERSION|(['"])([^'"]+)\1/g;
|
|
1742
|
-
const entriesSource = supportedMatch[1];
|
|
1743
|
-
const protocolVersions = [...entriesSource.matchAll(versionEntryPattern)].map((match) => match[2] || latestMatch[1]).filter((version) => isNonEmptyString(version));
|
|
1744
|
-
const unsupportedSyntax = entriesSource.replace(versionEntryPattern, "").replace(/[\s,]/g, "");
|
|
1745
|
-
if (!protocolVersions.length || unsupportedSyntax) {
|
|
1746
|
-
return {
|
|
1747
|
-
_tag: "Invalid",
|
|
1748
|
-
message: unsupportedSyntax ? "The installed MCP SDK uses an unsupported protocol versions format." : "The installed MCP SDK does not declare any supported protocol versions."
|
|
1749
|
-
};
|
|
1750
|
-
}
|
|
1751
|
-
return { _tag: "Resolved", protocolVersions: [...new Set(protocolVersions)] };
|
|
1752
|
-
}
|
|
1753
|
-
async function resolveInstalledMcpProtocolVersions(input) {
|
|
1754
|
-
const resolutionBases = [.../* @__PURE__ */ new Set([...input.modulesDir, input.rootDir])];
|
|
1755
|
-
const sdkResolutionAttempts = resolutionBases.map(
|
|
1756
|
-
(base) => Promise.resolve().then(() => {
|
|
1757
|
-
const toolkitPackagePath = resolvePackageMetadataPath("@nuxtjs/mcp-toolkit", base, input.modulesDir.includes(base) ? { searchDirectory: base } : void 0);
|
|
1758
|
-
return createRequire(toolkitPackagePath).resolve("@modelcontextprotocol/sdk/types.js");
|
|
1759
|
-
})
|
|
1760
|
-
);
|
|
1761
|
-
return Promise.allSettled(sdkResolutionAttempts).then((results) => {
|
|
1762
|
-
const resolved = results.find((result) => result.status === "fulfilled");
|
|
1763
|
-
if (resolved)
|
|
1764
|
-
return resolved.value;
|
|
1765
|
-
throw new AggregateError(results.map((result) => result.status === "rejected" ? result.reason : void 0), "Could not resolve the MCP Toolkit SDK.");
|
|
1766
|
-
}).then((sdkTypesPath) => readFile(sdkTypesPath, "utf8")).then(parseSupportedMcpProtocolVersions).catch((error) => ({
|
|
1767
|
-
_tag: "Invalid",
|
|
1768
|
-
message: `Could not resolve the MCP SDK protocol versions: ${error instanceof Error ? error.message : String(error)}`
|
|
1769
|
-
}));
|
|
1770
|
-
}
|
|
1771
|
-
function resolveDescription(input) {
|
|
1772
|
-
const candidate = input.override || input.toolkit || input.site;
|
|
1773
|
-
if (candidate && candidate.length <= 100)
|
|
1774
|
-
return candidate;
|
|
1775
|
-
const owner = input.siteName && input.siteName.length <= 75 ? input.siteName : "this site";
|
|
1776
|
-
return `MCP server for ${owner}.`;
|
|
1777
|
-
}
|
|
1778
|
-
function resolveMcpServerCard(input) {
|
|
1779
|
-
const title = input.overrides.title || (input.toolkitTitle && input.toolkitTitle.length <= 100 ? input.toolkitTitle : void 0) || (input.siteName && input.siteName.length <= 100 ? input.siteName : void 0);
|
|
1780
|
-
const card = {
|
|
1781
|
-
$schema: MCP_SERVER_CARD_SCHEMA,
|
|
1782
|
-
name: input.name,
|
|
1783
|
-
version: input.toolkit.version && input.toolkit.version.length <= 255 ? input.toolkit.version : "1.0.0",
|
|
1784
|
-
description: resolveDescription({
|
|
1785
|
-
override: input.overrides.description,
|
|
1786
|
-
toolkit: input.toolkit.description,
|
|
1787
|
-
site: input.siteDescription,
|
|
1788
|
-
siteName: input.siteName
|
|
1789
|
-
})
|
|
1790
|
-
};
|
|
1791
|
-
if (URL.canParse(input.endpoint) && ["http:", "https:"].includes(new URL(input.endpoint).protocol)) {
|
|
1792
|
-
card.remotes = [{
|
|
1793
|
-
type: "streamable-http",
|
|
1794
|
-
url: input.endpoint,
|
|
1795
|
-
supportedProtocolVersions: input.protocolVersions
|
|
1796
|
-
}];
|
|
1797
|
-
}
|
|
1798
|
-
if (title)
|
|
1799
|
-
card.title = title;
|
|
1800
|
-
if (input.overrides.websiteUrl)
|
|
1801
|
-
card.websiteUrl = input.overrides.websiteUrl;
|
|
1802
|
-
const icons = input.toolkit.icons?.map((icon) => URL.canParse(icon.src) ? icon : URL.canParse(input.endpoint) && URL.canParse(icon.src, input.endpoint) ? { ...icon, src: new URL(icon.src, input.endpoint).href } : void 0).filter((icon) => !!icon);
|
|
1803
|
-
if (icons?.length)
|
|
1804
|
-
card.icons = icons;
|
|
1805
|
-
return card;
|
|
1806
|
-
}
|
|
1807
|
-
function createMcpServerCardEtag(card) {
|
|
1808
|
-
return `"${createHash("sha256").update(JSON.stringify(card)).digest("hex")}"`;
|
|
1809
|
-
}
|
|
1810
|
-
|
|
1811
|
-
function opaqueJsonModule(exports) {
|
|
1812
|
-
const encode = (value) => JSON.stringify(Buffer.from(JSON.stringify(value), "utf8").toString("base64"));
|
|
1813
|
-
return [
|
|
1814
|
-
"const decode = value => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0))))",
|
|
1815
|
-
...Object.entries(exports).map(([name, value]) => `export const ${name} = decode(${encode(value)})`)
|
|
1816
|
-
].join("\n");
|
|
1817
|
-
}
|
|
1818
|
-
|
|
1819
|
-
const DEFAULT_MAX_OUTPUT_CHARS = 1500;
|
|
1820
|
-
const DEFAULT_LIST_LIMIT = 20;
|
|
1821
|
-
const DEFAULT_SEARCH_LIMIT = 10;
|
|
1822
|
-
const MAX_TOOL_LIMIT = 50;
|
|
1823
|
-
function detachedSiteTools() {
|
|
1824
|
-
return {
|
|
1825
|
-
listPages: { defaultLimit: DEFAULT_LIST_LIMIT, mcp: { enabled: false }, webmcp: { enabled: false } },
|
|
1826
|
-
searchPages: { defaultLimit: DEFAULT_SEARCH_LIMIT, mcp: { enabled: false }, webmcp: { enabled: false } },
|
|
1827
|
-
getPageMarkdown: { mcp: { enabled: false }, webmcp: { enabled: false } }
|
|
1828
|
-
};
|
|
1829
|
-
}
|
|
1830
|
-
function parsePositiveInteger(value, fallback, name, warnings, max) {
|
|
1831
|
-
if (value === void 0)
|
|
1832
|
-
return fallback;
|
|
1833
|
-
const integer = Math.trunc(value);
|
|
1834
|
-
if (!Number.isFinite(value) || integer < 1) {
|
|
1835
|
-
warnings.push(`\`aiReady.${name}\` must be a positive finite integer. Using ${fallback}.`);
|
|
1836
|
-
return fallback;
|
|
1837
|
-
}
|
|
1838
|
-
if (max && integer > max) {
|
|
1839
|
-
warnings.push(`\`aiReady.${name}\` cannot exceed ${max}. Using ${max}.`);
|
|
1840
|
-
return max;
|
|
1841
|
-
}
|
|
1842
|
-
if (integer !== value)
|
|
1843
|
-
warnings.push(`\`aiReady.${name}\` must be an integer. Using ${integer}.`);
|
|
1844
|
-
return integer;
|
|
1845
|
-
}
|
|
1846
|
-
function resolveWebMcpAttachment(options, path, warnings) {
|
|
1847
|
-
if (options?.enabled === false)
|
|
1848
|
-
return { enabled: false };
|
|
1849
|
-
return {
|
|
1850
|
-
enabled: true,
|
|
1851
|
-
maxOutputChars: parsePositiveInteger(
|
|
1852
|
-
options?.maxOutputChars,
|
|
1853
|
-
DEFAULT_MAX_OUTPUT_CHARS,
|
|
1854
|
-
`${path}.webmcp.maxOutputChars`,
|
|
1855
|
-
warnings
|
|
1856
|
-
),
|
|
1857
|
-
exposedTo: options?.exposedTo === void 0 ? void 0 : [...options.exposedTo]
|
|
1858
|
-
};
|
|
1859
|
-
}
|
|
1860
|
-
function resolveSiteToolsConfig(input, options = {}) {
|
|
1861
|
-
if (options.database?._tag === "Disabled")
|
|
1862
|
-
return { config: detachedSiteTools(), warnings: [] };
|
|
1863
|
-
const warnings = [];
|
|
1864
|
-
return {
|
|
1865
|
-
config: {
|
|
1866
|
-
listPages: {
|
|
1867
|
-
defaultLimit: parsePositiveInteger(
|
|
1868
|
-
input?.listPages?.defaultLimit,
|
|
1869
|
-
DEFAULT_LIST_LIMIT,
|
|
1870
|
-
"tools.listPages.defaultLimit",
|
|
1871
|
-
warnings,
|
|
1872
|
-
MAX_TOOL_LIMIT
|
|
1873
|
-
),
|
|
1874
|
-
mcp: { enabled: input?.listPages?.mcp?.enabled !== false },
|
|
1875
|
-
webmcp: resolveWebMcpAttachment(input?.listPages?.webmcp, "tools.listPages", warnings)
|
|
1876
|
-
},
|
|
1877
|
-
searchPages: {
|
|
1878
|
-
defaultLimit: parsePositiveInteger(
|
|
1879
|
-
input?.searchPages?.defaultLimit,
|
|
1880
|
-
DEFAULT_SEARCH_LIMIT,
|
|
1881
|
-
"tools.searchPages.defaultLimit",
|
|
1882
|
-
warnings,
|
|
1883
|
-
MAX_TOOL_LIMIT
|
|
1884
|
-
),
|
|
1885
|
-
mcp: { enabled: input?.searchPages?.mcp?.enabled !== false },
|
|
1886
|
-
webmcp: resolveWebMcpAttachment(input?.searchPages?.webmcp, "tools.searchPages", warnings)
|
|
1887
|
-
},
|
|
1888
|
-
getPageMarkdown: {
|
|
1889
|
-
mcp: { enabled: input?.getPageMarkdown?.mcp?.enabled !== false },
|
|
1890
|
-
webmcp: resolveWebMcpAttachment(input?.getPageMarkdown?.webmcp, "tools.getPageMarkdown", warnings)
|
|
1891
|
-
}
|
|
1892
|
-
},
|
|
1893
|
-
warnings
|
|
1894
|
-
};
|
|
1895
|
-
}
|
|
1896
|
-
function resolveWebMcpConfig(input, toolsConfig) {
|
|
1897
|
-
if (!input)
|
|
1898
|
-
return { _tag: "Disabled" };
|
|
1899
|
-
const options = input === true ? {} : input;
|
|
1900
|
-
const tools = {};
|
|
1901
|
-
if (options.tools !== false) {
|
|
1902
|
-
if (toolsConfig.listPages.webmcp.enabled) {
|
|
1903
|
-
tools.listPages = {
|
|
1904
|
-
defaultLimit: toolsConfig.listPages.defaultLimit,
|
|
1905
|
-
maxOutputChars: toolsConfig.listPages.webmcp.maxOutputChars,
|
|
1906
|
-
exposedTo: toolsConfig.listPages.webmcp.exposedTo
|
|
1907
|
-
};
|
|
1908
|
-
}
|
|
1909
|
-
if (toolsConfig.searchPages.webmcp.enabled) {
|
|
1910
|
-
tools.searchPages = {
|
|
1911
|
-
defaultLimit: toolsConfig.searchPages.defaultLimit,
|
|
1912
|
-
maxOutputChars: toolsConfig.searchPages.webmcp.maxOutputChars,
|
|
1913
|
-
exposedTo: toolsConfig.searchPages.webmcp.exposedTo
|
|
1914
|
-
};
|
|
1915
|
-
}
|
|
1916
|
-
if (toolsConfig.getPageMarkdown.webmcp.enabled) {
|
|
1917
|
-
tools.getPageMarkdown = {
|
|
1918
|
-
maxOutputChars: toolsConfig.getPageMarkdown.webmcp.maxOutputChars,
|
|
1919
|
-
exposedTo: toolsConfig.getPageMarkdown.webmcp.exposedTo
|
|
1920
|
-
};
|
|
1921
|
-
}
|
|
1922
|
-
}
|
|
1923
|
-
return {
|
|
1924
|
-
_tag: "Enabled",
|
|
1925
|
-
config: {
|
|
1926
|
-
tools,
|
|
1927
|
-
exposedTo: options.exposedTo?.length ? [...options.exposedTo] : void 0
|
|
1928
|
-
}
|
|
1929
|
-
};
|
|
1930
|
-
}
|
|
1931
|
-
|
|
1932
|
-
const MODULE_PACKAGE_NAME = "nuxt-ai-ready";
|
|
1933
|
-
const RE_SITEMAPD_PACKAGE = /[/\\]node_modules[/\\]sitemapd[/\\]/;
|
|
1934
|
-
const module$1 = defineNuxtModule({
|
|
1935
|
-
meta: {
|
|
1936
|
-
name: "nuxt-ai-ready",
|
|
1937
|
-
compatibility: {
|
|
1938
|
-
nuxt: "^4.6.0 || ^5.0.0-0"
|
|
1939
|
-
},
|
|
1940
|
-
configKey: "aiReady"
|
|
1941
|
-
},
|
|
1942
|
-
moduleDependencies: {
|
|
1943
|
-
[fileURLToPath(import.meta.resolve("@nuxtjs/robots"))]: {
|
|
1944
|
-
version: ">=7.0.0"
|
|
1945
|
-
},
|
|
1946
|
-
[fileURLToPath(import.meta.resolve("@nuxtjs/sitemap"))]: {
|
|
1947
|
-
version: ">=9.0.0"
|
|
1948
|
-
},
|
|
1949
|
-
// Keep package-relative resolution until the minimum Nuxt version includes this fix:
|
|
1950
|
-
// https://github.com/nuxt/nuxt/pull/36542
|
|
1951
|
-
[fileURLToPath(import.meta.resolve("nuxt-site-config"))]: {
|
|
1952
|
-
version: ">=5.0.0"
|
|
1953
|
-
},
|
|
1954
|
-
[fileURLToPath(import.meta.resolve("nuxtseo-shared"))]: {
|
|
1955
|
-
version: ">=6.0.0"
|
|
1956
|
-
},
|
|
1957
|
-
"@nuxtjs/mcp-toolkit": {
|
|
1958
|
-
version: ">=0.18.0",
|
|
1959
|
-
optional: true
|
|
1960
|
-
}
|
|
1961
|
-
},
|
|
1962
|
-
defaults() {
|
|
1963
|
-
return {
|
|
1964
|
-
enabled: true,
|
|
1965
|
-
debug: false,
|
|
1966
|
-
mdreamOptions: {
|
|
1967
|
-
minimal: true,
|
|
1968
|
-
clean: true
|
|
1969
|
-
},
|
|
1970
|
-
markdownCacheHeaders: {
|
|
1971
|
-
maxAge: 3600,
|
|
1972
|
-
// 1 hour
|
|
1973
|
-
swr: true
|
|
1974
|
-
},
|
|
1975
|
-
llmsTxtCacheSeconds: 600
|
|
1976
|
-
// 10 minutes
|
|
1977
|
-
};
|
|
1978
|
-
},
|
|
1979
|
-
async setup(config, nuxt) {
|
|
1980
|
-
const moduleEntryUrl = resolveModuleEntryUrl(import.meta.url);
|
|
1981
|
-
const resolveFromModule = createRequire(moduleEntryUrl);
|
|
1982
|
-
const nuxtSeoSharedI18nRuntimePath = resolveFromModule.resolve("nuxtseo-shared/i18n-runtime");
|
|
1983
|
-
const nuxtSeoSharedUtilsPath = resolveFromModule.resolve("nuxtseo-shared/utils");
|
|
1984
|
-
const { resolve: resolve$1 } = createResolver(moduleEntryUrl);
|
|
1985
|
-
const { version, peerDependencies } = await readPackageMetadata(resolve$1("../package.json"));
|
|
1986
|
-
logger.level = config.debug || nuxt.options.debug ? 4 : 3;
|
|
1987
|
-
if (config.enabled === false) {
|
|
1988
|
-
logger.debug("Module is disabled, skipping setup.");
|
|
1989
|
-
return;
|
|
1990
|
-
}
|
|
1991
|
-
setupRuntimeAliases({ namespace: "#ai-ready", app: resolve$1("./runtime/app"), server: resolve$1("./runtime/server") }, nuxt);
|
|
1992
|
-
const agentSkillsConfig = config.agentSkills === false ? false : config.agentSkills ?? {};
|
|
1993
|
-
const agentSkillsError = (issues) => {
|
|
1994
|
-
const details = issues.map((issue) => `${issue.index === void 0 ? "agentSkills" : `agentSkills.skills[${issue.index}]`}.${issue.field}: ${issue.message}`).join("\n");
|
|
1995
|
-
return new Error(`[nuxt-ai-ready] Invalid Agent Skills configuration:
|
|
1996
|
-
${details}`);
|
|
1997
|
-
};
|
|
1998
|
-
let agentSkillsResult = { _tag: "Disabled" };
|
|
1999
|
-
if (agentSkillsConfig !== false) {
|
|
2000
|
-
const { applyRootAlias, prepareAgentSkills, resolveAgentSkillsConfig } = await import('../chunks/agent-skills.mjs');
|
|
2001
|
-
const prepared = await prepareAgentSkills(agentSkillsConfig, {
|
|
2002
|
-
rootDir: nuxt.options.rootDir,
|
|
2003
|
-
scanDirs: getLayerDirectories(nuxt).map((layer) => layer.root),
|
|
2004
|
-
publicDirs: getLayerDirectories(nuxt).map((layer) => layer.public)
|
|
2005
|
-
});
|
|
2006
|
-
if (prepared._tag === "Invalid")
|
|
2007
|
-
throw agentSkillsError(prepared.issues);
|
|
2008
|
-
const payload = { skills: prepared.skills };
|
|
2009
|
-
await nuxt.callHook("ai-ready:agent-skills", payload);
|
|
2010
|
-
const rooted = applyRootAlias(payload.skills, agentSkillsConfig.root);
|
|
2011
|
-
if (rooted._tag === "Invalid")
|
|
2012
|
-
throw agentSkillsError(rooted.issues);
|
|
2013
|
-
agentSkillsResult = await resolveAgentSkillsConfig(
|
|
2014
|
-
{ ...agentSkillsConfig, skills: rooted.skills },
|
|
2015
|
-
nuxt.options.rootDir,
|
|
2016
|
-
{ sitemapMd: config.sitemapMd !== false, publicDirs: getLayerDirectories(nuxt).map((layer) => layer.public) }
|
|
2017
|
-
);
|
|
2018
|
-
if (agentSkillsResult._tag === "Invalid")
|
|
2019
|
-
throw agentSkillsError(agentSkillsResult.issues);
|
|
2020
|
-
if (agentSkillsResult._tag === "Enabled")
|
|
2021
|
-
logger.debug(`Publishing ${agentSkillsResult.index.skills.length} agent skill(s): ${agentSkillsResult.index.skills.map((skill) => skill.name).join(", ")}`);
|
|
2022
|
-
}
|
|
2023
|
-
const mcpServerCardResult = parseMcpServerCardConfig(config.mcpServerCard);
|
|
2024
|
-
if (mcpServerCardResult._tag === "Invalid")
|
|
2025
|
-
throw new Error(`[nuxt-ai-ready] ${mcpServerCardResult.message}`);
|
|
2026
|
-
const rawConfig = nuxt.options.aiReady || {};
|
|
2027
|
-
if ("cacheMaxAgeSeconds" in rawConfig) {
|
|
2028
|
-
logger.warn("`cacheMaxAgeSeconds` is deprecated, use `llmsTxtCacheSeconds` instead.");
|
|
2029
|
-
config.llmsTxtCacheSeconds ??= rawConfig.cacheMaxAgeSeconds;
|
|
2030
|
-
}
|
|
2031
|
-
if (rawConfig.mdreamOptions?.preset) {
|
|
2032
|
-
logger.warn("`mdreamOptions.preset` is deprecated. Use `mdreamOptions: { minimal: true }` instead. See https://github.com/harlan-zw/nuxt-ai-ready/releases/tag/v1.0.0");
|
|
2033
|
-
}
|
|
2034
|
-
const requestedSiteTools = resolveSiteToolsConfig(config.tools);
|
|
2035
|
-
const mcpToolkitState = resolveMcpToolkitState({
|
|
2036
|
-
installed: hasNuxtModule("@nuxtjs/mcp-toolkit") || hasConfiguredNuxtModule(nuxt.options.modules, "@nuxtjs/mcp-toolkit"),
|
|
2037
|
-
options: nuxt.options.mcp,
|
|
2038
|
-
static: nuxt.options.nitro.static === true,
|
|
2039
|
-
generating: nuxt.options._generate === true
|
|
2040
|
-
});
|
|
2041
|
-
const mcpNeedsDatabase = mcpToolkitState._tag === "Enabled" && (config.mcp?.resources !== false || config.mcp?.tools !== false && Object.values(requestedSiteTools.config).some((tool) => tool.mcp.enabled));
|
|
2042
|
-
const webmcpNeedsDatabase = !!config.webmcp && (config.webmcp === true || config.webmcp.tools !== false) && Object.values(requestedSiteTools.config).some((tool) => tool.webmcp.enabled);
|
|
2043
|
-
const databaseRequested = {
|
|
2044
|
-
runtimeSync: !!config.runtimeSync,
|
|
2045
|
-
cron: !!config.cron,
|
|
2046
|
-
mcp: mcpNeedsDatabase,
|
|
2047
|
-
webmcp: webmcpNeedsDatabase
|
|
2048
|
-
};
|
|
2049
|
-
const databaseResolution = resolveDatabaseConfig({
|
|
2050
|
-
database: config.database,
|
|
2051
|
-
rootDir: nuxt.options.rootDir,
|
|
2052
|
-
preset: String(nuxt.options.nitro.preset || ""),
|
|
2053
|
-
// Vercel Postgres sets POSTGRES_URL.
|
|
2054
|
-
hasPostgresUrl: !!(process.env.POSTGRES_URL || process.env.DATABASE_URL || (config.database || void 0)?.url),
|
|
2055
|
-
requested: databaseRequested
|
|
2056
|
-
});
|
|
2057
|
-
if (databaseResolution._tag === "Invalid")
|
|
2058
|
-
throw new Error(`[nuxt-ai-ready] ${databaseResolution.message}`);
|
|
2059
|
-
for (const log of databaseResolution.logs)
|
|
2060
|
-
logger[log.level](log.message);
|
|
2061
|
-
const database = databaseResolution.database;
|
|
2062
|
-
const databaseEnabled = database._tag === "Enabled";
|
|
2063
|
-
if (databaseEnabled) {
|
|
2064
|
-
const drizzle = await tryResolveModule("drizzle-orm", directoryToURL(nuxt.options.rootDir));
|
|
2065
|
-
const peerRange = peerDependencies["drizzle-orm"];
|
|
2066
|
-
const problem = checkDrizzleInstall(drizzle ? { _tag: "Installed", version: (await readPackageMetadata(drizzle)).version } : { _tag: "Missing" }, peerRange);
|
|
2067
|
-
if (problem)
|
|
2068
|
-
throw new Error(`[nuxt-ai-ready] ${formatDrizzleMessage({ problem, requested: databaseRequested, peerRange })}`);
|
|
2069
|
-
}
|
|
2070
|
-
if (!databaseEnabled)
|
|
2071
|
-
logger.debug("Database disabled. Page storage, runtime indexing and site tools are off.");
|
|
2072
|
-
const siteToolsResult = databaseEnabled ? requestedSiteTools : resolveSiteToolsConfig(config.tools, { database });
|
|
2073
|
-
for (const warning of siteToolsResult.warnings)
|
|
2074
|
-
logger.warn(warning);
|
|
2075
|
-
const siteToolsConfig = siteToolsResult.config;
|
|
2076
|
-
const hasMcpSiteTools = Object.values(siteToolsConfig).some((tool) => tool.mcp.enabled);
|
|
2077
|
-
const nitroCompatibility = setupNitroRuntimeCompatibility(nuxt);
|
|
2078
|
-
const siteConfig = useSiteConfig();
|
|
2079
|
-
const aiTermsResult = resolveAiTermsConfig(config.aiTerms, siteConfig.url ? withSiteUrl("/", { withBase: true }) : void 0);
|
|
2080
|
-
if (aiTermsResult._tag === "Invalid") {
|
|
2081
|
-
throw new Error([
|
|
2082
|
-
"[nuxt-ai-ready] Invalid AI Terms configuration:",
|
|
2083
|
-
...aiTermsResult.errors.map((error) => `- ${error}`)
|
|
2084
|
-
].join("\n"));
|
|
2085
|
-
}
|
|
2086
|
-
const aiTermsConfig = aiTermsResult._tag === "Enabled" ? aiTermsResult.config : void 0;
|
|
2087
|
-
const aiTermsLink = aiTermsConfig ? `<${aiTermsConfig.href}>; rel="ai-terms"` : void 0;
|
|
2088
|
-
const apiCatalogResult = resolveApiCatalogConfig(config.apiCatalog, {
|
|
2089
|
-
siteBaseURL: siteConfig.url ? withSiteUrl("/", { withBase: true }) : void 0,
|
|
2090
|
-
generatedEntries: []
|
|
2091
|
-
});
|
|
2092
|
-
const deferredGeneratedApiCatalog = apiCatalogResult._tag === "Invalid" && apiCatalogResult.errors.every((error) => error._tag === "MissingEntries");
|
|
2093
|
-
if (apiCatalogResult._tag === "Invalid" && !deferredGeneratedApiCatalog) {
|
|
2094
|
-
throw new Error([
|
|
2095
|
-
"[nuxt-ai-ready] Invalid API Catalog configuration:",
|
|
2096
|
-
...apiCatalogResult.errors.map((error) => `- ${formatApiCatalogConfigError(error)}`)
|
|
2097
|
-
].join("\n"));
|
|
2098
|
-
}
|
|
2099
|
-
let apiCatalogConfig = apiCatalogResult._tag === "Enabled" ? apiCatalogResult.config : void 0;
|
|
2100
|
-
const configuredMcpOptions = typeof nuxt.options.mcp === "object" && nuxt.options.mcp !== null ? nuxt.options.mcp : {};
|
|
2101
|
-
const configuredMcpTitle = configuredMcpOptions.name;
|
|
2102
|
-
const mcpServerCardNameResult = mcpServerCardResult._tag === "Enabled" ? resolveMcpServerCardName({
|
|
2103
|
-
overrideName: mcpServerCardResult.config.name,
|
|
2104
|
-
route: configuredMcpOptions.route || "/mcp",
|
|
2105
|
-
siteUrl: siteConfig.url || void 0
|
|
2106
|
-
}) : void 0;
|
|
2107
|
-
if (mcpServerCardNameResult?._tag === "Invalid")
|
|
2108
|
-
throw new Error(`[nuxt-ai-ready] ${mcpServerCardNameResult.message}`);
|
|
2109
|
-
const mcpServerCardName = mcpServerCardNameResult?._tag === "Resolved" ? mcpServerCardNameResult.name : void 0;
|
|
2110
|
-
if (mcpServerCardName && nuxt.options.mcp !== false) {
|
|
2111
|
-
nuxt.options.mcp = configuredMcpOptions;
|
|
2112
|
-
nuxt.options.mcp.name = mcpServerCardName;
|
|
2113
|
-
}
|
|
2114
|
-
if (nuxt.options.mcp !== false && config.mcp?.tools !== false && hasMcpSiteTools) {
|
|
2115
|
-
nuxt.options.mcp = configuredMcpOptions;
|
|
2116
|
-
nuxt.options.mcp.instructions ??= "Use this server when you need information from this site's indexed pages. Read the available tool descriptions before choosing a tool.";
|
|
2117
|
-
}
|
|
2118
|
-
const i18nConfig = await detectI18n({ autoI18n: config.autoI18n });
|
|
2119
|
-
if (i18nConfig) {
|
|
2120
|
-
logger.info(`i18n detected: ${i18nConfig.locales.length} locales (default: ${i18nConfig.defaultLocale}, strategy: ${i18nConfig.strategy})`);
|
|
2121
|
-
}
|
|
2122
|
-
const configuredI18nPages = i18nConfig?.pages;
|
|
2123
|
-
if (i18nConfig && configuredI18nPages) {
|
|
2124
|
-
const syncI18nConfig = (target) => {
|
|
2125
|
-
if (target && typeof target === "object")
|
|
2126
|
-
Object.assign(target, { i18n: i18nConfig });
|
|
2127
|
-
};
|
|
2128
|
-
let syncNitroI18nConfig;
|
|
2129
|
-
nuxt.hook("nitro:init", (nitro) => {
|
|
2130
|
-
syncNitroI18nConfig = () => syncI18nConfig(nitro.options.runtimeConfig["nuxt-ai-ready"]);
|
|
2131
|
-
syncNitroI18nConfig();
|
|
2132
|
-
});
|
|
2133
|
-
const removePageCapture = nuxt.hooks.beforeEach((event) => {
|
|
2134
|
-
if (event.name !== "pages:extend")
|
|
2135
|
-
return;
|
|
2136
|
-
const pages = event.args[event.args.length - 1];
|
|
2137
|
-
if (!Array.isArray(pages))
|
|
2138
|
-
return;
|
|
2139
|
-
i18nConfig.pages = materializeI18nPages({ ...i18nConfig, pages: configuredI18nPages }, pages);
|
|
2140
|
-
syncI18nConfig(nuxt.options.runtimeConfig["nuxt-ai-ready"]);
|
|
2141
|
-
syncI18nConfig(nuxt.options.nitro.runtimeConfig?.["nuxt-ai-ready"]);
|
|
2142
|
-
syncNitroI18nConfig?.();
|
|
2143
|
-
removePageCapture();
|
|
2144
|
-
});
|
|
2145
|
-
}
|
|
2146
|
-
const ftsTokenizer = i18nConfig && hasCjkLocale(i18nConfig) ? "trigram" : "unicode61 remove_diacritics 2";
|
|
2147
|
-
nuxt.options.alias["#ai-ready"] = resolve$1("./runtime");
|
|
2148
|
-
addServerImports([
|
|
2149
|
-
"countPages",
|
|
2150
|
-
"indexPage",
|
|
2151
|
-
"indexPageByRoute",
|
|
2152
|
-
"queryPages",
|
|
2153
|
-
"searchPages",
|
|
2154
|
-
"streamPages"
|
|
2155
|
-
].map((name) => ({
|
|
2156
|
-
name,
|
|
2157
|
-
from: resolve$1("./runtime")
|
|
2158
|
-
})));
|
|
2159
|
-
let mcpAvailable = mcpToolkitState._tag === "Enabled";
|
|
2160
|
-
nuxt.hook("mcp:definitions:paths", (paths) => {
|
|
2161
|
-
const mcpRuntimeDir = resolve$1("./runtime/server/mcp");
|
|
2162
|
-
const mcpConfig = config.mcp || {};
|
|
2163
|
-
if (mcpConfig.tools !== false && hasMcpSiteTools)
|
|
2164
|
-
(paths.tools ||= []).push(`${mcpRuntimeDir}/tools`);
|
|
2165
|
-
if (mcpConfig.resources !== false && databaseEnabled)
|
|
2166
|
-
(paths.resources ||= []).push(`${mcpRuntimeDir}/resources`);
|
|
2167
|
-
});
|
|
2168
|
-
const contentSource = await resolveContentSource(config.contentSource !== false);
|
|
2169
|
-
const contentSignalPolicy = resolveContentSignalPolicy(config.contentSignal);
|
|
2170
|
-
if (contentSignalPolicy._tag !== "Disabled") {
|
|
2171
|
-
nuxt.hook("robots:config", (robotsConfig) => {
|
|
2172
|
-
applyContentSignalPolicy(robotsConfig.groups, contentSignalPolicy);
|
|
2173
|
-
});
|
|
2174
|
-
}
|
|
2175
|
-
registerTypeTemplates({ config, nitroCompatibility });
|
|
2176
|
-
const defaultLlmsTxtSections = [];
|
|
2177
|
-
const llmsFullRoute = withSiteUrl("llms-full.txt", { withBase: true });
|
|
2178
|
-
defaultLlmsTxtSections.push({
|
|
2179
|
-
title: "LLM Resources",
|
|
2180
|
-
links: config.llmsFullTxt === false ? [] : [
|
|
2181
|
-
{
|
|
2182
|
-
title: "Full Content",
|
|
2183
|
-
href: llmsFullRoute,
|
|
2184
|
-
description: "Complete page content in markdown format."
|
|
2185
|
-
}
|
|
2186
|
-
]
|
|
2187
|
-
});
|
|
2188
|
-
if (agentSkillsResult._tag === "Enabled" && agentSkillsConfig !== false && agentSkillsConfig.llmsTxt !== false) {
|
|
2189
|
-
const indexUrl = withSiteUrl(AGENT_SKILLS_INDEX_ROUTE.slice(1), { withBase: true });
|
|
2190
|
-
defaultLlmsTxtSections.push({
|
|
2191
|
-
title: "Agent Skills",
|
|
2192
|
-
description: `Skills an agent can install from this site. The index at ${indexUrl} carries a sha256 digest for each one.`,
|
|
2193
|
-
links: [{ title: "Agent Skills index", href: indexUrl, description: "Every published skill and its sha256 digest." }, ...agentSkillsResult.links.map((link) => ({
|
|
2194
|
-
title: link.name,
|
|
2195
|
-
href: link.source === "local" ? withSiteUrl(link.href.slice(1), { withBase: true }) : resolveExternalSkillUrl(link.href, indexUrl),
|
|
2196
|
-
description: link.description
|
|
2197
|
-
}))]
|
|
2198
|
-
});
|
|
2199
|
-
}
|
|
2200
|
-
const directiveConfig = config.llmsTxt === false ? void 0 : config.llmsTxt?.directive;
|
|
2201
|
-
const llmsTxtDirective = {
|
|
2202
|
-
markdown: directiveConfig?.markdown !== false,
|
|
2203
|
-
html: directiveConfig?.html === true
|
|
2204
|
-
};
|
|
2205
|
-
const parsedLlmsTxt = parseLlmsTxtConfig(config.llmsTxt || {});
|
|
2206
|
-
if (parsedLlmsTxt._tag === "Invalid")
|
|
2207
|
-
throw new Error(`[nuxt-ai-ready] ${parsedLlmsTxt.message}`);
|
|
2208
|
-
const publicLlmsTxt = await Promise.all(getLayerDirectories(nuxt).map(
|
|
2209
|
-
(layer) => access(join(layer.public, "llms.txt")).then(() => true).catch((error) => {
|
|
2210
|
-
if (error.code === "ENOENT")
|
|
2211
|
-
return false;
|
|
2212
|
-
throw error;
|
|
2213
|
-
})
|
|
2214
|
-
));
|
|
2215
|
-
const generateLlmsTxt = config.llmsTxt !== false && !publicLlmsTxt.some(Boolean);
|
|
2216
|
-
const mergedLlmsTxt = config.llmsTxt ? {
|
|
2217
|
-
...parsedLlmsTxt.config,
|
|
2218
|
-
markdownLinks: config.llmsTxt.markdownLinks ?? true,
|
|
2219
|
-
directive: llmsTxtDirective,
|
|
2220
|
-
sections: [
|
|
2221
|
-
...defaultLlmsTxtSections,
|
|
2222
|
-
...config.llmsTxt.sections || []
|
|
2223
|
-
],
|
|
2224
|
-
notes: config.llmsTxt.notes
|
|
2225
|
-
} : { markdownLinks: true, directive: llmsTxtDirective, sections: defaultLlmsTxtSections };
|
|
2226
|
-
const llmsTxtPayload = {
|
|
2227
|
-
sections: mergedLlmsTxt.sections || [],
|
|
2228
|
-
notes: typeof mergedLlmsTxt.notes === "string" ? [mergedLlmsTxt.notes] : mergedLlmsTxt.notes || []
|
|
2229
|
-
};
|
|
2230
|
-
await nuxt.callHook("ai-ready:llms-txt", llmsTxtPayload);
|
|
2231
|
-
mergedLlmsTxt.sections = llmsTxtPayload.sections;
|
|
2232
|
-
mergedLlmsTxt.notes = llmsTxtPayload.notes.length > 0 ? llmsTxtPayload.notes : void 0;
|
|
2233
|
-
const parsedHookLlmsTxt = parseLlmsTxtConfig(mergedLlmsTxt);
|
|
2234
|
-
if (parsedHookLlmsTxt._tag === "Invalid")
|
|
2235
|
-
throw new Error(`[nuxt-ai-ready] ${parsedHookLlmsTxt.message}`);
|
|
2236
|
-
const prerenderCacheDir = join(nuxt.options.rootDir, "node_modules/.cache/nuxt-seo/ai-ready/routes");
|
|
2237
|
-
const buildDbPath = join(nuxt.options.buildDir, ".data/ai-ready/build.db");
|
|
2238
|
-
const runtimeSyncConfig = typeof config.runtimeSync === "object" ? config.runtimeSync : {};
|
|
2239
|
-
const runtimeSyncEnabled = !!config.runtimeSync || !!config.cron;
|
|
2240
|
-
const webmcpResult = resolveWebMcpConfig(config.webmcp, siteToolsConfig);
|
|
2241
|
-
const webmcpConfig = webmcpResult._tag === "Enabled" ? webmcpResult.config : null;
|
|
2242
|
-
const isStatic = nuxt.options.nitro.static || nuxt.options._generate || false;
|
|
2243
|
-
const zeroRuntimeMarkdown = config.zeroRuntimeMarkdown === true && !nuxt.options.dev;
|
|
2244
|
-
const hasPrerenderedRoutes = !!(nuxt.options.nitro.prerender?.routes?.length || nuxt.options.nitro.prerender?.crawlLinks);
|
|
2245
|
-
const preparing = nuxt.options._prepare === true;
|
|
2246
|
-
const prerenderEnabled = !preparing && !!(isStatic || hasPrerenderedRoutes);
|
|
2247
|
-
const prerenderMarkdown = prerenderEnabled || zeroRuntimeMarkdown && !preparing;
|
|
2248
|
-
const isSPA = nuxt.options.ssr === false;
|
|
2249
|
-
let apiCatalogRegistered = false;
|
|
2250
|
-
const registerApiCatalog = (catalog) => {
|
|
2251
|
-
if (apiCatalogRegistered)
|
|
2252
|
-
return;
|
|
2253
|
-
apiCatalogRegistered = true;
|
|
2254
|
-
const resources = mergedLlmsTxt.sections?.find((section) => section.title === "LLM Resources");
|
|
2255
|
-
resources?.links?.push({ title: "API catalog", href: catalog.href, description: "The public API and service descriptions." });
|
|
2256
|
-
addServerHandler({ route: API_CATALOG_PATH, handler: resolve$1("./runtime/server/routes/api-catalog"), lazy: true });
|
|
2257
|
-
const apiCatalogLink = `<${catalog.href}>; rel="api-catalog"`;
|
|
2258
|
-
extendRouteRules("/**", {
|
|
2259
|
-
headers: { Link: [apiCatalogLink, aiTermsLink].filter(Boolean).join(", ") }
|
|
2260
|
-
});
|
|
2261
|
-
extendRouteRules(API_CATALOG_PATH, {
|
|
2262
|
-
headers: {
|
|
2263
|
-
"Content-Type": catalog.mediaType,
|
|
2264
|
-
"Link": [apiCatalogLink, aiTermsLink].filter(Boolean).join(", ")
|
|
2265
|
-
}
|
|
2266
|
-
});
|
|
2267
|
-
if (prerenderEnabled) {
|
|
2268
|
-
nuxt.options.nitro.prerender ||= {};
|
|
2269
|
-
nuxt.options.nitro.prerender.routes ||= [];
|
|
2270
|
-
if (!nuxt.options.nitro.prerender.routes.includes(API_CATALOG_PATH))
|
|
2271
|
-
nuxt.options.nitro.prerender.routes.push(API_CATALOG_PATH);
|
|
2272
|
-
}
|
|
2273
|
-
};
|
|
2274
|
-
let seoProModules;
|
|
2275
|
-
const updateSeoProFeatures = (modules) => {
|
|
2276
|
-
const mod = modules.find((m) => m.name === "nuxt-ai-ready");
|
|
2277
|
-
if (mod) {
|
|
2278
|
-
mod.features = {
|
|
2279
|
-
mcp: mcpAvailable,
|
|
2280
|
-
webmcp: !!webmcpConfig,
|
|
2281
|
-
agentSkills: agentSkillsResult._tag === "Enabled",
|
|
2282
|
-
runtimeSync: runtimeSyncEnabled,
|
|
2283
|
-
cron: !!config.cron,
|
|
2284
|
-
apiCatalog: !!apiCatalogConfig,
|
|
2285
|
-
aiTerms: !!aiTermsConfig,
|
|
2286
|
-
database: databaseEnabled ? database.type : false
|
|
2287
|
-
};
|
|
2288
|
-
}
|
|
2289
|
-
};
|
|
2290
|
-
nuxt.hooks.hook("nuxt-seo-pro:modules", (modules) => {
|
|
2291
|
-
seoProModules = modules;
|
|
2292
|
-
updateSeoProFeatures(modules);
|
|
2293
|
-
});
|
|
2294
|
-
nuxt.hook("modules:done", async () => {
|
|
2295
|
-
const finalMcpToolkitState = resolveMcpToolkitState({
|
|
2296
|
-
installed: hasNuxtModule("@nuxtjs/mcp-toolkit") || hasConfiguredNuxtModule(nuxt.options.modules, "@nuxtjs/mcp-toolkit"),
|
|
2297
|
-
options: nuxt.options.mcp,
|
|
2298
|
-
static: nuxt.options.nitro.static === true,
|
|
2299
|
-
generating: nuxt.options._generate === true
|
|
2300
|
-
});
|
|
2301
|
-
mcpAvailable = finalMcpToolkitState._tag === "Enabled";
|
|
2302
|
-
if (finalMcpToolkitState._tag !== "Enabled") {
|
|
2303
|
-
if (deferredGeneratedApiCatalog) {
|
|
2304
|
-
throw new Error([
|
|
2305
|
-
"[nuxt-ai-ready] Invalid API Catalog configuration:",
|
|
2306
|
-
...apiCatalogResult._tag === "Invalid" ? apiCatalogResult.errors.map((error) => `- ${formatApiCatalogConfigError(error)}`) : []
|
|
2307
|
-
].join("\n"));
|
|
2308
|
-
}
|
|
2309
|
-
if (seoProModules)
|
|
2310
|
-
updateSeoProFeatures(seoProModules);
|
|
2311
|
-
return;
|
|
2312
|
-
}
|
|
2313
|
-
if (mcpServerCardResult._tag === "Enabled") {
|
|
2314
|
-
const endpoint = withSiteUrl(finalMcpToolkitState.route, { withBase: true });
|
|
2315
|
-
const mcpLink = {
|
|
2316
|
-
title: "MCP server card",
|
|
2317
|
-
href: withSiteUrl(MCP_SERVER_CARD_WELL_KNOWN_PATHS[0].slice(1), { withBase: true }),
|
|
2318
|
-
description: config.mcp?.tools !== false && hasMcpSiteTools ? `Connect an MCP client to ${endpoint} when you need information from this site's indexed pages.` : `Connect an MCP client to ${endpoint} to use this site's Model Context Protocol server.`
|
|
2319
|
-
};
|
|
2320
|
-
const firstSection = mergedLlmsTxt.sections?.[0];
|
|
2321
|
-
if (firstSection) {
|
|
2322
|
-
firstSection.links ||= [];
|
|
2323
|
-
if (!firstSection.links.some((link) => link.title === mcpLink.title))
|
|
2324
|
-
firstSection.links.push(mcpLink);
|
|
2325
|
-
} else {
|
|
2326
|
-
mergedLlmsTxt.sections = [{ title: "LLM Tools", links: [mcpLink] }];
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
const mcpServerCardRoute = resolveMcpServerCardRoute(finalMcpToolkitState.route);
|
|
2330
|
-
if (siteConfig.url && config.apiCatalog !== false) {
|
|
2331
|
-
const generatedApiCatalog = resolveApiCatalogConfig(config.apiCatalog, {
|
|
2332
|
-
siteBaseURL: withSiteUrl("/", { withBase: true }),
|
|
2333
|
-
generatedEntries: [{
|
|
2334
|
-
anchor: finalMcpToolkitState.route,
|
|
2335
|
-
item: {
|
|
2336
|
-
href: finalMcpToolkitState.route,
|
|
2337
|
-
type: "application/json"
|
|
2338
|
-
},
|
|
2339
|
-
...mcpServerCardResult._tag === "Enabled" && {
|
|
2340
|
-
serviceDesc: {
|
|
2341
|
-
href: mcpServerCardRoute,
|
|
2342
|
-
type: MCP_SERVER_CARD_MEDIA_TYPE
|
|
2343
|
-
}
|
|
2344
|
-
}
|
|
2345
|
-
}]
|
|
2346
|
-
});
|
|
2347
|
-
if (generatedApiCatalog._tag === "Invalid") {
|
|
2348
|
-
throw new Error([
|
|
2349
|
-
"[nuxt-ai-ready] Invalid generated API Catalog configuration:",
|
|
2350
|
-
...generatedApiCatalog.errors.map((error) => `- ${formatApiCatalogConfigError(error)}`)
|
|
2351
|
-
].join("\n"));
|
|
2352
|
-
}
|
|
2353
|
-
if (generatedApiCatalog._tag === "Enabled") {
|
|
2354
|
-
apiCatalogConfig = generatedApiCatalog.config;
|
|
2355
|
-
const runtimeConfig2 = nuxt.options.runtimeConfig["nuxt-ai-ready"];
|
|
2356
|
-
runtimeConfig2.apiCatalog = apiCatalogConfig;
|
|
2357
|
-
registerApiCatalog(apiCatalogConfig);
|
|
2358
|
-
}
|
|
2359
|
-
}
|
|
2360
|
-
if (deferredGeneratedApiCatalog && !apiCatalogConfig) {
|
|
2361
|
-
throw new Error([
|
|
2362
|
-
"[nuxt-ai-ready] Invalid API Catalog configuration:",
|
|
2363
|
-
"- Configure a site URL for automatic MCP discovery, or provide at least one API Catalog entry."
|
|
2364
|
-
].join("\n"));
|
|
2365
|
-
}
|
|
2366
|
-
if (seoProModules)
|
|
2367
|
-
updateSeoProFeatures(seoProModules);
|
|
2368
|
-
if (mcpServerCardResult._tag === "Disabled")
|
|
2369
|
-
return;
|
|
2370
|
-
const toolkitConfig = typeof nuxt.options.mcp === "object" && nuxt.options.mcp !== null ? nuxt.options.mcp : {};
|
|
2371
|
-
const finalMcpServerCardNameResult = mcpServerCardName ? { _tag: "Resolved", name: mcpServerCardName } : resolveMcpServerCardName({
|
|
2372
|
-
overrideName: mcpServerCardResult.config.name,
|
|
2373
|
-
route: finalMcpToolkitState.route,
|
|
2374
|
-
siteUrl: siteConfig.url || void 0
|
|
2375
|
-
});
|
|
2376
|
-
if (finalMcpServerCardNameResult._tag === "Invalid")
|
|
2377
|
-
throw new Error(`[nuxt-ai-ready] ${finalMcpServerCardNameResult.message}`);
|
|
2378
|
-
const protocolVersionsResult = await resolveInstalledMcpProtocolVersions({
|
|
2379
|
-
rootDir: nuxt.options.rootDir,
|
|
2380
|
-
modulesDir: nuxt.options.modulesDir
|
|
2381
|
-
});
|
|
2382
|
-
if (protocolVersionsResult._tag === "Invalid")
|
|
2383
|
-
throw new Error(`[nuxt-ai-ready] ${protocolVersionsResult.message}`);
|
|
2384
|
-
const card = resolveMcpServerCard({
|
|
2385
|
-
protocolVersions: protocolVersionsResult.protocolVersions,
|
|
2386
|
-
endpoint: siteConfig.url ? withSiteUrl(finalMcpToolkitState.route, { withBase: true }) : finalMcpToolkitState.route,
|
|
2387
|
-
name: finalMcpServerCardNameResult.name,
|
|
2388
|
-
toolkitTitle: configuredMcpTitle,
|
|
2389
|
-
siteName: siteConfig.name || void 0,
|
|
2390
|
-
siteDescription: siteConfig.description || void 0,
|
|
2391
|
-
toolkit: {
|
|
2392
|
-
...toolkitConfig
|
|
2393
|
-
},
|
|
2394
|
-
overrides: mcpServerCardResult.config
|
|
2395
|
-
});
|
|
2396
|
-
const runtimeConfig = nuxt.options.runtimeConfig["nuxt-ai-ready"];
|
|
2397
|
-
const etag = createMcpServerCardEtag(card);
|
|
2398
|
-
runtimeConfig.mcpServerCard = {
|
|
2399
|
-
card,
|
|
2400
|
-
cacheMaxAge: mcpServerCardResult.config.cacheMaxAge,
|
|
2401
|
-
etag
|
|
2402
|
-
};
|
|
2403
|
-
const handler = resolve$1("./runtime/server/routes/mcp-server-card");
|
|
2404
|
-
for (const route of [mcpServerCardRoute, ...MCP_SERVER_CARD_WELL_KNOWN_PATHS]) {
|
|
2405
|
-
addServerHandler({ route, method: "get", handler, lazy: true });
|
|
2406
|
-
addServerHandler({ route, method: "head", handler, lazy: true });
|
|
2407
|
-
addServerHandler({ route, method: "options", handler, lazy: true });
|
|
2408
|
-
extendRouteRules(route, {
|
|
2409
|
-
sitemap: false,
|
|
2410
|
-
headers: {
|
|
2411
|
-
"Access-Control-Allow-Headers": "Content-Type, If-None-Match",
|
|
2412
|
-
"Access-Control-Allow-Methods": "GET, HEAD",
|
|
2413
|
-
"Access-Control-Allow-Origin": "*",
|
|
2414
|
-
"Access-Control-Expose-Headers": "ETag",
|
|
2415
|
-
"Cache-Control": `public, max-age=${mcpServerCardResult.config.cacheMaxAge}`,
|
|
2416
|
-
"Content-Type": MCP_SERVER_CARD_MEDIA_TYPE,
|
|
2417
|
-
"ETag": etag
|
|
2418
|
-
}
|
|
2419
|
-
});
|
|
2420
|
-
}
|
|
2421
|
-
if (siteConfig.url) {
|
|
2422
|
-
const document = resolveAiCatalog({
|
|
2423
|
-
siteUrl: siteConfig.url,
|
|
2424
|
-
serverCardName: card.name,
|
|
2425
|
-
serverCardTitle: card.title,
|
|
2426
|
-
serverCardDescription: card.description,
|
|
2427
|
-
serverCardUrl: withSiteUrl(mcpServerCardRoute, { withBase: true })
|
|
2428
|
-
});
|
|
2429
|
-
const aiCatalogEtag = createAiCatalogEtag(document);
|
|
2430
|
-
const aiCatalogCacheMaxAge = mcpServerCardResult.config.cacheMaxAge;
|
|
2431
|
-
runtimeConfig.aiCatalog = {
|
|
2432
|
-
cacheMaxAge: aiCatalogCacheMaxAge,
|
|
2433
|
-
document,
|
|
2434
|
-
etag: aiCatalogEtag
|
|
2435
|
-
};
|
|
2436
|
-
const aiCatalogHandler = resolve$1("./runtime/server/routes/ai-catalog");
|
|
2437
|
-
for (const route of [ARD_PATH, AI_CATALOG_PATH]) {
|
|
2438
|
-
addServerHandler({ route, method: "get", handler: aiCatalogHandler, lazy: true });
|
|
2439
|
-
addServerHandler({ route, method: "head", handler: aiCatalogHandler, lazy: true });
|
|
2440
|
-
addServerHandler({ route, method: "options", handler: aiCatalogHandler, lazy: true });
|
|
2441
|
-
extendRouteRules(route, {
|
|
2442
|
-
sitemap: false,
|
|
2443
|
-
headers: {
|
|
2444
|
-
"Access-Control-Allow-Headers": "Content-Type, If-None-Match",
|
|
2445
|
-
"Access-Control-Allow-Methods": "GET, HEAD",
|
|
2446
|
-
"Access-Control-Allow-Origin": "*",
|
|
2447
|
-
"Access-Control-Expose-Headers": "ETag",
|
|
2448
|
-
"Cache-Control": `public, max-age=${aiCatalogCacheMaxAge}`,
|
|
2449
|
-
"Content-Type": AI_CATALOG_MEDIA_TYPE,
|
|
2450
|
-
"ETag": aiCatalogEtag
|
|
2451
|
-
}
|
|
2452
|
-
});
|
|
2453
|
-
}
|
|
2454
|
-
}
|
|
2455
|
-
});
|
|
2456
|
-
const sitemapConfig = nuxt.options.sitemap;
|
|
2457
|
-
const sitemapRouteRule = nuxt.options.nitro?.routeRules?.["/sitemap.xml"];
|
|
2458
|
-
const sitemapPrerendered = !!(sitemapConfig?.zeroRuntime || sitemapRouteRule?.prerender || process.argv.includes("generate") || process.env.NUXT_GENERATE === "true");
|
|
2459
|
-
const secretPath = join(nuxt.options.rootDir, "node_modules/.cache/nuxt/ai-ready/secret");
|
|
2460
|
-
const appSecret = process.env.NITRO_APP_SECRET ?? process.env.NUXT_APP_SECRET ?? nuxt.options.runtimeConfig.appSecret;
|
|
2461
|
-
const legacySecret = process.env.NUXT_NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? process.env.NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? config.runtimeSyncSecret;
|
|
2462
|
-
if (legacySecret)
|
|
2463
|
-
logger.warn(LEGACY_RUNTIME_SYNC_SECRET_WARNING);
|
|
2464
|
-
const syncSecret = typeof appSecret === "string" && appSecret.length >= 32 ? await deriveRuntimeSyncSecret(appSecret) : appSecret === void 0 || appSecret === "" ? legacySecret : void 0;
|
|
2465
|
-
if (runtimeSyncEnabled && syncSecret) {
|
|
2466
|
-
await mkdir(dirname(secretPath), { recursive: true });
|
|
2467
|
-
const temporaryDir = await mkdtemp(join(dirname(secretPath), "secret-"));
|
|
2468
|
-
try {
|
|
2469
|
-
const temporaryPath = join(temporaryDir, "token");
|
|
2470
|
-
await writeFile(temporaryPath, syncSecret, { mode: 384 });
|
|
2471
|
-
await rename(temporaryPath, secretPath);
|
|
2472
|
-
} finally {
|
|
2473
|
-
await rm(temporaryDir, { recursive: true, force: true });
|
|
2474
|
-
}
|
|
2475
|
-
} else {
|
|
2476
|
-
await rm(secretPath, { force: true });
|
|
2477
|
-
}
|
|
2478
|
-
let cloudflareFallbackPaths = [];
|
|
2479
|
-
let prerenderedMarkdownHeaders = [];
|
|
2480
|
-
let prerenderedMarkdownPaths = [];
|
|
2481
|
-
nuxt.hooks.hook("nitro:config", (nitroConfig) => {
|
|
2482
|
-
if (getNitroVersion(nuxt) === 3) {
|
|
2483
|
-
const nativeConfig = nitroConfig;
|
|
2484
|
-
if (nativeConfig.noExternals !== true) {
|
|
2485
|
-
nativeConfig.noExternals = [
|
|
2486
|
-
...(nativeConfig.noExternals || []).filter((entry) => entry !== MODULE_PACKAGE_NAME),
|
|
2487
|
-
resolve$1("./runtime")
|
|
2488
|
-
];
|
|
2489
|
-
}
|
|
2490
|
-
} else {
|
|
2491
|
-
const externals = nitroConfig.externals ||= {};
|
|
2492
|
-
externals.inline ||= [];
|
|
2493
|
-
externals.inline.push(resolve$1("./runtime"));
|
|
2494
|
-
}
|
|
2495
|
-
nitroConfig.experimental = nitroConfig.experimental || {};
|
|
2496
|
-
nitroConfig.experimental.asyncContext = true;
|
|
2497
|
-
const preset = String(nitroConfig.preset || "");
|
|
2498
|
-
const isEdgePreset = ["cloudflare", "vercel-edge", "netlify-edge", "deno"].some((p) => preset.startsWith(p));
|
|
2499
|
-
if (isEdgePreset)
|
|
2500
|
-
nitroConfig.experimental.wasm = true;
|
|
2501
|
-
if (nitroCompatibility._tag === "nitro-v3") {
|
|
2502
|
-
const nitro3Config = nitroConfig;
|
|
2503
|
-
if (nitro3Config.noExternals !== true)
|
|
2504
|
-
nitro3Config.noExternals = [...nitro3Config.noExternals || [], RE_SITEMAPD_PACKAGE];
|
|
2505
|
-
if (!isEdgePreset) {
|
|
2506
|
-
nitro3Config.traceDeps ||= [];
|
|
2507
|
-
nitro3Config.traceDeps.push("mdream*");
|
|
2508
|
-
}
|
|
2509
|
-
} else {
|
|
2510
|
-
const externals = nitroConfig.externals ||= {};
|
|
2511
|
-
externals.inline ||= [];
|
|
2512
|
-
externals.inline.push("sitemapd");
|
|
2513
|
-
}
|
|
2514
|
-
if (!isEdgePreset && nitroCompatibility._tag === "nitro-v2") {
|
|
2515
|
-
const externals = nitroConfig.externals ||= {};
|
|
2516
|
-
externals.external ||= [];
|
|
2517
|
-
externals.external.push("mdream");
|
|
2518
|
-
const rollupExternal = (nitroConfig.rollupConfig ||= {}).external ||= [];
|
|
2519
|
-
if (Array.isArray(rollupExternal))
|
|
2520
|
-
rollupExternal.push("node:sqlite");
|
|
2521
|
-
}
|
|
2522
|
-
if (config.cron && !nuxt.options.dev) {
|
|
2523
|
-
const preset2 = String(nitroConfig.preset || "");
|
|
2524
|
-
const isVercel = preset2 === "vercel" || preset2 === "vercel-edge";
|
|
2525
|
-
const isCloudflarePages = preset2 === "cloudflare-pages" || preset2 === "cloudflare_pages";
|
|
2526
|
-
if (isCloudflarePages) {
|
|
2527
|
-
logger.warn("Cloudflare Pages does not support cron. Use external cron to call /__ai-ready/cron instead.");
|
|
2528
|
-
} else if (isVercel) {
|
|
2529
|
-
nitroConfig.vercel = nitroConfig.vercel || {};
|
|
2530
|
-
nitroConfig.vercel.config = nitroConfig.vercel.config || {};
|
|
2531
|
-
nitroConfig.vercel.config.crons = nitroConfig.vercel.config.crons || [];
|
|
2532
|
-
nitroConfig.vercel.config.crons.push({
|
|
2533
|
-
schedule: AI_READY_CRON_SCHEDULE,
|
|
2534
|
-
path: "/__ai-ready/cron"
|
|
2535
|
-
});
|
|
2536
|
-
} else {
|
|
2537
|
-
nitroConfig.experimental.tasks = true;
|
|
2538
|
-
nitroConfig.tasks = nitroConfig.tasks || {};
|
|
2539
|
-
nitroConfig.tasks["ai-ready:cron"] = {
|
|
2540
|
-
handler: resolve$1("./runtime/server/tasks/ai-ready-cron")
|
|
2541
|
-
};
|
|
2542
|
-
nitroConfig.scheduledTasks = nitroConfig.scheduledTasks || {};
|
|
2543
|
-
nitroConfig.scheduledTasks[AI_READY_CRON_SCHEDULE] = nitroConfig.scheduledTasks[AI_READY_CRON_SCHEDULE] || [];
|
|
2544
|
-
nitroConfig.scheduledTasks[AI_READY_CRON_SCHEDULE].push("ai-ready:cron");
|
|
2545
|
-
const isCloudflareWorkers = preset2.startsWith("cloudflare");
|
|
2546
|
-
if (isCloudflareWorkers) {
|
|
2547
|
-
nitroConfig.cloudflare = nitroConfig.cloudflare || {};
|
|
2548
|
-
nitroConfig.cloudflare.deployConfig = true;
|
|
2549
|
-
nitroConfig.cloudflare.wrangler = nitroConfig.cloudflare.wrangler || {};
|
|
2550
|
-
nitroConfig.cloudflare.wrangler.triggers = nitroConfig.cloudflare.wrangler.triggers || {};
|
|
2551
|
-
nitroConfig.cloudflare.wrangler.triggers.crons = nitroConfig.cloudflare.wrangler.triggers.crons || [];
|
|
2552
|
-
if (!nitroConfig.cloudflare.wrangler.triggers.crons.includes(AI_READY_CRON_SCHEDULE)) {
|
|
2553
|
-
nitroConfig.cloudflare.wrangler.triggers.crons.push(AI_READY_CRON_SCHEDULE);
|
|
2554
|
-
}
|
|
2555
|
-
}
|
|
2556
|
-
}
|
|
2557
|
-
}
|
|
2558
|
-
nitroConfig.virtual = nitroConfig.virtual || {};
|
|
2559
|
-
nitroConfig.virtual["#ai-ready-virtual/i18n-runtime.mjs"] = () => {
|
|
2560
|
-
const runtimeConfig = nitroConfig.runtimeConfig?.["nuxt-ai-ready"];
|
|
2561
|
-
return runtimeConfig?.i18n ? `export { computeLocaleAlternates, localePath, resolveI18nDomain, resolveLocaleAlternates, resolveLocaleFromRoute } from ${JSON.stringify(nuxtSeoSharedI18nRuntimePath)}` : `
|
|
2562
|
-
const unavailable = () => {
|
|
2563
|
-
throw new Error('[nuxt-ai-ready] i18n runtime called without i18n configuration.')
|
|
2564
|
-
}
|
|
2565
|
-
export { unavailable as computeLocaleAlternates, unavailable as localePath, unavailable as resolveI18nDomain, unavailable as resolveLocaleAlternates, unavailable as resolveLocaleFromRoute }
|
|
2566
|
-
`;
|
|
2567
|
-
};
|
|
2568
|
-
nitroConfig.virtual["#ai-ready-virtual/site-tools.mjs"] = `export default ${JSON.stringify(siteToolsConfig)}`;
|
|
2569
|
-
nitroConfig.virtual["#ai-ready-virtual/agent-skills.mjs"] = agentSkillsResult._tag === "Enabled" ? opaqueJsonModule({ agentSkillsIndex: agentSkillsResult.index, localAgentSkillArtifacts: agentSkillsResult.localArtifacts }) : "export const agentSkillsIndex = null\nexport const localAgentSkillArtifacts = {}";
|
|
2570
|
-
const markdownLinkAvailabilityPath = join(dirname(buildDbPath), MARKDOWN_LINK_AVAILABILITY_FILE);
|
|
2571
|
-
nitroConfig.virtual["#ai-ready-virtual/read-page-data.mjs"] = createBuildPageDataVirtual({
|
|
2572
|
-
buildDbPath,
|
|
2573
|
-
markdownLinkAvailabilityPath,
|
|
2574
|
-
dev: nuxt.options.dev
|
|
2575
|
-
});
|
|
2576
|
-
nitroConfig.virtual["#ai-ready-virtual/page-data.mjs"] = `export const pages = []
|
|
2577
|
-
export const errorRoutes = []`;
|
|
2578
|
-
nitroConfig.virtual["#ai-ready-virtual/cloudflare-fallback-paths.mjs"] = () => `export default new Set(${JSON.stringify(cloudflareFallbackPaths)})`;
|
|
2579
|
-
nitroConfig.virtual["#ai-ready-virtual/prerendered-markdown-headers.mjs"] = () => `export default new Map(${JSON.stringify(prerenderedMarkdownHeaders)})`;
|
|
2580
|
-
nitroConfig.virtual["#ai-ready-virtual/prerendered-markdown-paths.mjs"] = () => zeroRuntimeMarkdown ? `export default new Set(${JSON.stringify(prerenderedMarkdownPaths.map(decodePath))})` : "export default null";
|
|
2581
|
-
nitroConfig.virtual["#ai-ready-virtual/render-markdown.mjs"] = zeroRuntimeMarkdown ? "export const renderMarkdown = undefined" : `export { renderMarkdown } from '#ai-ready/server/middleware/render-markdown'`;
|
|
2582
|
-
nitroConfig.virtual["#ai-ready-virtual/logger.mjs"] = `
|
|
2583
|
-
import { createModuleLogger } from ${JSON.stringify(nuxtSeoSharedUtilsPath)}
|
|
2584
|
-
export const logger = createModuleLogger('nuxt-ai-ready', ${!!config.debug})
|
|
2585
|
-
`;
|
|
2586
|
-
const providerMap = {
|
|
2587
|
-
sqlite: "#ai-ready/server/db/drizzle/providers/node-sqlite",
|
|
2588
|
-
bun: "#ai-ready/server/db/drizzle/providers/bun",
|
|
2589
|
-
d1: "#ai-ready/server/db/drizzle/providers/d1",
|
|
2590
|
-
libsql: "#ai-ready/server/db/drizzle/providers/libsql",
|
|
2591
|
-
neon: "#ai-ready/server/db/drizzle/providers/neon",
|
|
2592
|
-
postgres: "#ai-ready/server/db/drizzle/providers/postgres"
|
|
2593
|
-
};
|
|
2594
|
-
nitroConfig.virtual["#ai-ready-virtual/db-provider.mjs"] = database._tag === "Enabled" ? `export { createClient } from '${providerMap[database.type] || providerMap.sqlite}'` : `export function createClient() {
|
|
2595
|
-
throw new Error('[nuxt-ai-ready] The database is disabled. Set \`aiReady.database\` to store pages at runtime.')
|
|
2596
|
-
}`;
|
|
2597
|
-
const databaseRuntime = "#ai-ready-virtual/database-runtime.mjs";
|
|
2598
|
-
if (database._tag === "Disabled") {
|
|
2599
|
-
const databaseExports = [
|
|
2600
|
-
"useDrizzle",
|
|
2601
|
-
"useRawDb",
|
|
2602
|
-
"completeCronRun",
|
|
2603
|
-
"countPages",
|
|
2604
|
-
"deleteInfoValue",
|
|
2605
|
-
"getAllPages",
|
|
2606
|
-
"getContentHashes",
|
|
2607
|
-
"getInfoValue",
|
|
2608
|
-
"getNextSitemapToCrawl",
|
|
2609
|
-
"getPageByRoute",
|
|
2610
|
-
"getPageLastmods",
|
|
2611
|
-
"getPendingPages",
|
|
2612
|
-
"getRecentCronRuns",
|
|
2613
|
-
"getSitemapStatus",
|
|
2614
|
-
"initSchema",
|
|
2615
|
-
"markPageIndexed",
|
|
2616
|
-
"markRoutesPending",
|
|
2617
|
-
"markSitemapCrawled",
|
|
2618
|
-
"markSitemapCrawlPartial",
|
|
2619
|
-
"markSitemapError",
|
|
2620
|
-
"markSitemapSeeded",
|
|
2621
|
-
"resetSitemapErrors",
|
|
2622
|
-
"searchPages",
|
|
2623
|
-
"seedRoutes",
|
|
2624
|
-
"setInfoValue",
|
|
2625
|
-
"startCronRun",
|
|
2626
|
-
"syncSitemaps",
|
|
2627
|
-
"upsertPage"
|
|
2628
|
-
];
|
|
2629
|
-
nitroConfig.virtual[databaseRuntime] = `
|
|
2630
|
-
async function unavailable() {
|
|
2631
|
-
throw new Error('[nuxt-ai-ready] The database is disabled. Set \`aiReady.database\` to store pages at runtime.')
|
|
2632
|
-
}
|
|
2633
|
-
export { ${databaseExports.map((name) => `unavailable as ${name}`).join(", ")} }
|
|
2634
|
-
export async function closeDrizzle() {}
|
|
2635
|
-
export async function finishDrizzleResponse() {}
|
|
2636
|
-
export function trackDrizzleWork(event, work) { return work }
|
|
2637
|
-
`;
|
|
2638
|
-
} else {
|
|
2639
|
-
nitroConfig.virtual[databaseRuntime] = `export * from '#ai-ready/server/db/drizzle'`;
|
|
2640
|
-
}
|
|
2641
|
-
const schemaPath = database._tag === "Enabled" && (database.type === "neon" || database.type === "postgres") ? "#ai-ready/server/db/schema/postgres" : "#ai-ready/server/db/schema/sqlite";
|
|
2642
|
-
nitroConfig.virtual["#ai-ready-virtual/db-schema.mjs"] = database._tag === "Enabled" ? `export * from '${schemaPath}'` : "export {}";
|
|
2643
|
-
nitroConfig.virtual["#ai-ready-virtual/devtools-meta.mjs"] = `export const devtoolsMeta = ${JSON.stringify({
|
|
2644
|
-
contentSignal: config.contentSignal ?? { search: true, aiInput: true },
|
|
2645
|
-
mcp: { enabled: mcpAvailable, tools: mcpAvailable && config.mcp?.tools !== false && hasMcpSiteTools, resources: mcpAvailable && config.mcp?.resources !== false },
|
|
2646
|
-
cron: !!config.cron
|
|
2647
|
-
})}`;
|
|
2648
|
-
nitroConfig.virtual["#ai-ready-virtual/content-lookup.mjs"] = contentLookupModule(contentSource);
|
|
2649
|
-
nitroConfig.virtual["#ai-ready-virtual/sitemap-config.mjs"] = `export { default } from '#sitemap-virtual/static-config.mjs'`;
|
|
2650
|
-
});
|
|
2651
|
-
nuxt.options.runtimeConfig["nuxt-ai-ready"] = {
|
|
2652
|
-
version: version || "0.0.0",
|
|
2653
|
-
debug: config.debug || false,
|
|
2654
|
-
debugCron: config.debugCron || false,
|
|
2655
|
-
contentNegotiation: config.contentNegotiation === void 0 ? "auto" : config.contentNegotiation ? "enabled" : "disabled",
|
|
2656
|
-
botNegotiation: config.botNegotiation === true,
|
|
2657
|
-
zeroRuntimeMarkdown,
|
|
2658
|
-
mdreamOptions: config.mdreamOptions || {},
|
|
2659
|
-
sitemapMd: config.sitemapMd !== false,
|
|
2660
|
-
describedby: config.describedby !== false,
|
|
2661
|
-
markdownCacheHeaders: defu$1(config.markdownCacheHeaders, {
|
|
2662
|
-
maxAge: 3600,
|
|
2663
|
-
swr: true
|
|
2664
|
-
}),
|
|
2665
|
-
llmsTxt: mergedLlmsTxt,
|
|
2666
|
-
llmsFullTxt: config.llmsFullTxt !== false,
|
|
2667
|
-
llmsTxtCacheSeconds: config.llmsTxtCacheSeconds ?? 600,
|
|
2668
|
-
prerenderCacheDir,
|
|
2669
|
-
database,
|
|
2670
|
-
runtimeSync: {
|
|
2671
|
-
enabled: runtimeSyncEnabled,
|
|
2672
|
-
ttl: runtimeSyncConfig.ttl ?? 3600,
|
|
2673
|
-
batchSize: runtimeSyncConfig.batchSize ?? 50,
|
|
2674
|
-
pruneTtl: runtimeSyncConfig.pruneTtl ?? 0
|
|
2675
|
-
},
|
|
2676
|
-
runtimeSyncSecret: legacySecret || "",
|
|
2677
|
-
sitemapPrerendered,
|
|
2678
|
-
i18n: i18nConfig,
|
|
2679
|
-
ftsTokenizer,
|
|
2680
|
-
apiCatalog: apiCatalogConfig,
|
|
2681
|
-
aiTerms: aiTermsConfig
|
|
2682
|
-
};
|
|
2683
|
-
if (prerenderMarkdown) {
|
|
2684
|
-
addServerHandler({
|
|
2685
|
-
middleware: true,
|
|
2686
|
-
env: "prerender",
|
|
2687
|
-
handler: resolve$1("./runtime/server/middleware/markdown.prerender")
|
|
2688
|
-
});
|
|
2689
|
-
const htmlCapturePlugin = resolve$1("./runtime/server/plugins/html-capture.prerender");
|
|
2690
|
-
const policyCapturePlugin = resolve$1(getNitroVersion(nuxt) === 3 ? "./runtime/server/plugins/content-signal-capture-nitro3.prerender" : "./runtime/server/plugins/content-signal-capture.prerender");
|
|
2691
|
-
nuxt.hook("nitro:init", (nitro) => {
|
|
2692
|
-
nitro.hooks.hook("prerender:config", (prerenderConfig) => {
|
|
2693
|
-
prerenderConfig.plugins = [...prerenderConfig.plugins || [], htmlCapturePlugin, policyCapturePlugin];
|
|
2694
|
-
});
|
|
2695
|
-
});
|
|
2696
|
-
addPlugin({
|
|
2697
|
-
mode: "server",
|
|
2698
|
-
src: resolve$1("./runtime/app/plugins/md-hints.prerender")
|
|
2699
|
-
});
|
|
2700
|
-
}
|
|
2701
|
-
addServerHandler({
|
|
2702
|
-
middleware: true,
|
|
2703
|
-
handler: resolve$1("./runtime/server/middleware/markdown")
|
|
2704
|
-
});
|
|
2705
|
-
if (getNitroVersion(nuxt) === 3) {
|
|
2706
|
-
extendRouteRules("/**.md", { cache: false });
|
|
2707
|
-
}
|
|
2708
|
-
addNitroPlugin(resolve$1(getNitroVersion(nuxt) === 3 ? "./runtime/server/plugins/link-header-nitro3" : "./runtime/server/plugins/link-header"));
|
|
2709
|
-
addNitroPlugin(resolve$1("./runtime/server/plugins/markdown-negotiation"));
|
|
2710
|
-
if (llmsTxtDirective.html)
|
|
2711
|
-
addNitroPlugin(resolve$1("./runtime/server/plugins/llms-txt-directive-html"));
|
|
2712
|
-
addPlugin({
|
|
2713
|
-
mode: "server",
|
|
2714
|
-
src: resolve$1("./runtime/app/plugins/md-alternate.server")
|
|
2715
|
-
});
|
|
2716
|
-
if (generateLlmsTxt) {
|
|
2717
|
-
addServerHandler({ middleware: true, method: void 0, handler: resolve$1("./runtime/server/routes/llms.txt.get"), lazy: true });
|
|
2718
|
-
}
|
|
2719
|
-
if (config.llmsFullTxt !== false)
|
|
2720
|
-
addServerHandler({ route: "/llms-full.txt", method: void 0, handler: resolve$1("./runtime/server/routes/llms-full.txt.get"), lazy: true });
|
|
2721
|
-
if (config.sitemapMd !== false) {
|
|
2722
|
-
addServerHandler({ route: SITEMAP_MD_ROUTE, method: void 0, handler: resolve$1("./runtime/server/routes/sitemap.md.get"), lazy: true });
|
|
2723
|
-
}
|
|
2724
|
-
if (agentSkillsResult._tag === "Enabled") {
|
|
2725
|
-
addServerHandler({ route: AGENT_SKILLS_INDEX_ROUTE, handler: resolve$1("./runtime/server/routes/agent-skills-index"), lazy: true });
|
|
2726
|
-
for (const route of Object.keys(agentSkillsResult.localArtifacts)) {
|
|
2727
|
-
addServerHandler({ route, handler: resolve$1("./runtime/server/routes/agent-skills-artifact"), lazy: true });
|
|
2728
|
-
extendRouteRules(route, {
|
|
2729
|
-
headers: {
|
|
2730
|
-
"Content-Type": "text/markdown; charset=utf-8",
|
|
2731
|
-
"Cache-Control": AGENT_SKILLS_CACHE_CONTROL,
|
|
2732
|
-
"Access-Control-Allow-Origin": "*"
|
|
2733
|
-
}
|
|
2734
|
-
});
|
|
2735
|
-
}
|
|
2736
|
-
extendRouteRules(AGENT_SKILLS_INDEX_ROUTE, {
|
|
2737
|
-
headers: {
|
|
2738
|
-
"Content-Type": "application/json; charset=utf-8",
|
|
2739
|
-
"Cache-Control": AGENT_SKILLS_CACHE_CONTROL,
|
|
2740
|
-
"Access-Control-Allow-Origin": "*"
|
|
2741
|
-
}
|
|
2742
|
-
});
|
|
2743
|
-
const generating = nuxt.options.nitro.static === true || nuxt.options._generate === true;
|
|
2744
|
-
if (generating) {
|
|
2745
|
-
nuxt.options.nitro.prerender = nuxt.options.nitro.prerender || {};
|
|
2746
|
-
nuxt.options.nitro.prerender.routes = nuxt.options.nitro.prerender.routes || [];
|
|
2747
|
-
const agentSkillRoutes = [
|
|
2748
|
-
AGENT_SKILLS_INDEX_ROUTE,
|
|
2749
|
-
...Object.keys(agentSkillsResult.localArtifacts)
|
|
2750
|
-
];
|
|
2751
|
-
for (const route of agentSkillRoutes) {
|
|
2752
|
-
if (!nuxt.options.nitro.prerender.routes.includes(route))
|
|
2753
|
-
nuxt.options.nitro.prerender.routes.push(route);
|
|
2754
|
-
}
|
|
2755
|
-
}
|
|
2756
|
-
}
|
|
2757
|
-
if (webmcpConfig) {
|
|
2758
|
-
addImports(["useWebMcpSupported", "useWebMcpTool"].map((name) => ({
|
|
2759
|
-
name,
|
|
2760
|
-
from: resolve$1("./runtime/app/composables/webmcp")
|
|
2761
|
-
})));
|
|
2762
|
-
nuxt.options.runtimeConfig.public["nuxt-ai-ready"] = {
|
|
2763
|
-
webmcp: webmcpConfig
|
|
2764
|
-
};
|
|
2765
|
-
addPlugin({ mode: "client", src: resolve$1("./runtime/app/plugins/webmcp.client") });
|
|
2766
|
-
if (Object.keys(webmcpConfig.tools).length) {
|
|
2767
|
-
addServerHandler({ route: "/__ai-ready/pages", handler: resolve$1("./runtime/server/routes/__ai-ready/pages.get"), lazy: true });
|
|
2768
|
-
}
|
|
2769
|
-
}
|
|
2770
|
-
if (nuxt.options.dev || config.debug) {
|
|
2771
|
-
addServerHandler({ route: "/__ai-ready__/debug.json", handler: resolve$1("./runtime/server/routes/__ai-ready/devtools.get"), lazy: true });
|
|
2772
|
-
}
|
|
2773
|
-
if (config.debug) {
|
|
2774
|
-
addServerHandler({ route: "/__ai-ready-debug", handler: resolve$1("./runtime/server/routes/__ai-ready-debug.get"), lazy: true });
|
|
2775
|
-
}
|
|
2776
|
-
if (runtimeSyncEnabled) {
|
|
2777
|
-
addServerHandler({ route: "/__ai-ready/status", handler: resolve$1("./runtime/server/routes/__ai-ready/status.get"), lazy: true });
|
|
2778
|
-
addServerHandler({ route: "/__ai-ready/poll", method: "post", handler: resolve$1("./runtime/server/routes/__ai-ready/poll.post"), lazy: true });
|
|
2779
|
-
addServerHandler({ route: "/__ai-ready/prune", method: "post", handler: resolve$1("./runtime/server/routes/__ai-ready/prune.post"), lazy: true });
|
|
2780
|
-
addServerHandler({ route: "/__ai-ready/restore", method: "post", handler: resolve$1("./runtime/server/routes/__ai-ready/restore.post"), lazy: true });
|
|
2781
|
-
addServerHandler({ route: "/__ai-ready/reindex", method: "post", handler: resolve$1("./runtime/server/routes/__ai-ready/reindex.post"), lazy: true });
|
|
2782
|
-
addNitroPlugin(resolve$1("./runtime/server/plugins/sitemap-seeder"));
|
|
2783
|
-
}
|
|
2784
|
-
if (config.cron && !nuxt.options.dev) {
|
|
2785
|
-
addServerHandler({ route: "/__ai-ready/cron", handler: resolve$1("./runtime/server/routes/__ai-ready/cron.get"), lazy: true });
|
|
2786
|
-
}
|
|
2787
|
-
if (aiTermsConfig) {
|
|
2788
|
-
addServerHandler({ route: AI_TERMS_PATH, handler: resolve$1("./runtime/server/routes/ai-terms"), lazy: true });
|
|
2789
|
-
addNitroPlugin(resolve$1("./runtime/server/plugins/ai-terms"));
|
|
2790
|
-
extendRouteRules("/**", {
|
|
2791
|
-
headers: {
|
|
2792
|
-
Link: [apiCatalogConfig && `<${apiCatalogConfig.href}>; rel="api-catalog"`, aiTermsLink].filter(Boolean).join(", ")
|
|
2793
|
-
}
|
|
2794
|
-
});
|
|
2795
|
-
extendRouteRules(AI_TERMS_PATH, {
|
|
2796
|
-
headers: {
|
|
2797
|
-
"Content-Type": "application/json; charset=utf-8",
|
|
2798
|
-
"Access-Control-Allow-Origin": "*",
|
|
2799
|
-
"Cache-Control": "public, max-age=3600"
|
|
2800
|
-
}
|
|
2801
|
-
});
|
|
2802
|
-
nuxt.hook("prerender:routes", ({ routes }) => {
|
|
2803
|
-
if (prerenderEnabled || routes.size > 0)
|
|
2804
|
-
routes.add(AI_TERMS_PATH);
|
|
2805
|
-
});
|
|
2806
|
-
}
|
|
2807
|
-
if (apiCatalogConfig)
|
|
2808
|
-
registerApiCatalog(apiCatalogConfig);
|
|
2809
|
-
if (!nuxt.options.dev && !nuxt.options._prepare) {
|
|
2810
|
-
if (isSPA && !hasPrerenderedRoutes) {
|
|
2811
|
-
logger.warn("SPA mode detected without prerendering. llms-full.txt will not be generated.");
|
|
2812
|
-
} else if (!isStatic && !hasPrerenderedRoutes && !zeroRuntimeMarkdown) {
|
|
2813
|
-
logger.info("SSR-only mode: llms-full.txt requires prerendering. Runtime markdown conversion available.");
|
|
2814
|
-
}
|
|
2815
|
-
}
|
|
2816
|
-
if (prerenderMarkdown) {
|
|
2817
|
-
const { setupPrerenderHandler } = await import('../chunks/prerender.mjs');
|
|
2818
|
-
setupPrerenderHandler({ ...config, llmsTxt: generateLlmsTxt ? config.llmsTxt : false }, buildDbPath, {
|
|
2819
|
-
name: siteConfig.name,
|
|
2820
|
-
url: siteConfig.url ? withSiteUrl("/", { withBase: true }) : void 0,
|
|
2821
|
-
description: siteConfig.description
|
|
2822
|
-
}, mergedLlmsTxt, {
|
|
2823
|
-
ftsTokenizer,
|
|
2824
|
-
i18n: i18nConfig,
|
|
2825
|
-
artifactRoutes: agentSkillsResult._tag === "Enabled" ? Object.keys(agentSkillsResult.localArtifacts) : [],
|
|
2826
|
-
runtimeDatabase: database._tag,
|
|
2827
|
-
onMarkdownPaths: zeroRuntimeMarkdown ? (paths) => {
|
|
2828
|
-
prerenderedMarkdownPaths = paths;
|
|
2829
|
-
} : void 0
|
|
2830
|
-
});
|
|
2831
|
-
}
|
|
2832
|
-
if (databaseEnabled) {
|
|
2833
|
-
addNitroPlugin(resolve$1(getNitroVersion(nuxt) === 3 ? "./runtime/server/plugins/db-lifecycle-nitro3" : "./runtime/server/plugins/db-lifecycle"));
|
|
2834
|
-
}
|
|
2835
|
-
if (nuxt.options.dev) {
|
|
2836
|
-
const { setupDevToolsUI } = await import('nuxtseo-shared/devtools');
|
|
2837
|
-
setupDevToolsUI({
|
|
2838
|
-
route: "/__nuxt-ai-ready",
|
|
2839
|
-
name: "nuxt-ai-ready",
|
|
2840
|
-
title: "AI Ready",
|
|
2841
|
-
icon: "carbon:ai-label"
|
|
2842
|
-
}, resolve$1, nuxt);
|
|
2843
|
-
}
|
|
2844
|
-
for (const route of [generateLlmsTxt && "/llms.txt", generateLlmsTxt && "/llms/**", config.llmsFullTxt !== false && "/llms-full.txt"].filter((route2) => Boolean(route2))) {
|
|
2845
|
-
extendRouteRules(route, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
|
|
2846
|
-
}
|
|
2847
|
-
if (config.sitemapMd !== false) {
|
|
2848
|
-
extendRouteRules(SITEMAP_MD_ROUTE, { headers: { "Content-Type": "text/markdown; charset=utf-8" } });
|
|
2849
|
-
}
|
|
2850
|
-
const staticBaseURL = nuxt.options.app.baseURL || "/";
|
|
2851
|
-
const emittedWarnings = /* @__PURE__ */ new Set();
|
|
2852
|
-
const warnConfiguration = (nitro) => {
|
|
2853
|
-
if (preparing)
|
|
2854
|
-
return;
|
|
2855
|
-
const nuxtSeoReportsSiteUrl = nuxt.options.dev && !isAgent && !isCI && nuxt.options._installedModules.some(({ meta }) => meta.name === "nuxtseo" && !meta.disabled);
|
|
2856
|
-
const warnings = resolveConfigurationWarnings({
|
|
2857
|
-
policy: nuxt.options.runtimeConfig["nuxt-ai-ready"].contentNegotiation,
|
|
2858
|
-
botNegotiation: config.botNegotiation === true,
|
|
2859
|
-
static: nitro.options.static === true || isStatic,
|
|
2860
|
-
siteUrl: siteConfig.url || void 0,
|
|
2861
|
-
reportSiteUrl: !nuxtSeoReportsSiteUrl,
|
|
2862
|
-
routeRules: nitro.options.routeRules
|
|
2863
|
-
});
|
|
2864
|
-
for (const warning of warnings) {
|
|
2865
|
-
if (!emittedWarnings.has(warning)) {
|
|
2866
|
-
emittedWarnings.add(warning);
|
|
2867
|
-
logger.warn(warning);
|
|
2868
|
-
}
|
|
2869
|
-
}
|
|
2870
|
-
};
|
|
2871
|
-
nuxt.hook("nitro:init", (nitro) => {
|
|
2872
|
-
warnConfiguration(nitro);
|
|
2873
|
-
nitro.hooks.hook(getNitroVersion(nuxt) === 3 ? "build:reload" : "rollup:reload", () => warnConfiguration(nitro));
|
|
2874
|
-
});
|
|
2875
|
-
nuxt.hook("nitro:build:before", warnConfiguration);
|
|
2876
|
-
let sharedMarkdownRuleNoted = false;
|
|
2877
|
-
const noteSharedMarkdownRule = (total, dropped) => {
|
|
2878
|
-
if (sharedMarkdownRuleNoted)
|
|
2879
|
-
return;
|
|
2880
|
-
sharedMarkdownRuleNoted = true;
|
|
2881
|
-
logger.info(`Cloudflare allows ${CLOUDFLARE_STATIC_HEADER_RULE_LIMIT} _headers rules. One rule per Markdown page would make ${total}. The ${dropped} Markdown pages share the /*.md rule, which sends no per-page canonical Link header.`);
|
|
2882
|
-
};
|
|
2883
|
-
nuxt.hooks.hook("nitro:build:before", (nitro) => {
|
|
2884
|
-
const isCloudflarePreset = String(nitro.options.preset || "").startsWith("cloudflare");
|
|
2885
|
-
const applyMarkdownHeaders = () => {
|
|
2886
|
-
const plan = planStaticMarkdownHeaderRules(
|
|
2887
|
-
nitro.options.routeRules,
|
|
2888
|
-
prerenderedMarkdownHeaderRules(
|
|
2889
|
-
nitro._prerenderedRoutes || [],
|
|
2890
|
-
staticBaseURL,
|
|
2891
|
-
config.describedby !== false,
|
|
2892
|
-
agentSkillsResult._tag === "Enabled" ? Object.keys(agentSkillsResult.localArtifacts) : [],
|
|
2893
|
-
isCloudflarePreset ? void 0 : aiTermsLink
|
|
2894
|
-
),
|
|
2895
|
-
isCloudflarePreset ? CLOUDFLARE_STATIC_HEADER_RULE_LIMIT : null
|
|
2896
|
-
);
|
|
2897
|
-
const headers = applyStaticMarkdownHeaderPlan(nitro.options.routeRules, plan);
|
|
2898
|
-
if (plan._tag === "skip")
|
|
2899
|
-
noteSharedMarkdownRule(plan.total, plan.dropped);
|
|
2900
|
-
return headers;
|
|
2901
|
-
};
|
|
2902
|
-
let prerenderFinished = false;
|
|
2903
|
-
nitro.hooks.hook("prerender:done", async () => {
|
|
2904
|
-
if (["cloudflare", "cloudflare-module", "cloudflare-durable"].includes(String(nitro.options.preset)) && !nitro.options.static && config.contentNegotiation === true) {
|
|
2905
|
-
const pages = cloudflarePrerenderedPages(nitro._prerenderedRoutes || [], staticBaseURL);
|
|
2906
|
-
const cloudflare = nitro.options.cloudflare ||= {};
|
|
2907
|
-
const wrangler = cloudflare.wrangler ||= {};
|
|
2908
|
-
const assets = wrangler.assets ||= {};
|
|
2909
|
-
const fileRouting = await readCloudflareAssetRouting(nitro.options.rootDir);
|
|
2910
|
-
const routing = defu$1({ value: assets.run_worker_first }, { value: fileRouting.root }).value;
|
|
2911
|
-
const additions = cloudflareWorkerFirstAdditions(routing, pages);
|
|
2912
|
-
const environmentConfig = wrangler;
|
|
2913
|
-
const configuredEnvironments = Object.values(environmentConfig.env || {}).flatMap((env) => env.assets?.run_worker_first === void 0 ? [] : [env.assets.run_worker_first]);
|
|
2914
|
-
cloudflareFallbackPaths = cloudflareStaticFallbackPaths(routing, pages, [...fileRouting.environments, ...configuredEnvironments]);
|
|
2915
|
-
if (additions.length > 0)
|
|
2916
|
-
assets.run_worker_first = [...Array.isArray(assets.run_worker_first) ? assets.run_worker_first : [], ...additions];
|
|
2917
|
-
}
|
|
2918
|
-
prerenderFinished = true;
|
|
2919
|
-
});
|
|
2920
|
-
const bundlerHooks = new Set(nitroCompatibility._tag === "nitro-v2" ? ["rollup:before"] : ["build:config", "vite:compile:before"]);
|
|
2921
|
-
nitro.hooks.afterEach(({ name }) => {
|
|
2922
|
-
if (nitro.options.static) {
|
|
2923
|
-
if (name === "prerender:done")
|
|
2924
|
-
applyMarkdownHeaders();
|
|
2925
|
-
return;
|
|
2926
|
-
}
|
|
2927
|
-
if (!prerenderFinished || !bundlerHooks.has(name))
|
|
2928
|
-
return;
|
|
2929
|
-
prerenderFinished = false;
|
|
2930
|
-
const runtimeRouteRules = { ...nitro.options.runtimeConfig.nitro.routeRules };
|
|
2931
|
-
const headers = applyMarkdownHeaders();
|
|
2932
|
-
const matchRouteRules = createNitroRouteRuleMatcher({ nitro: { routeRules: runtimeRouteRules } });
|
|
2933
|
-
prerenderedMarkdownHeaders = [];
|
|
2934
|
-
for (const [path, values] of headers) {
|
|
2935
|
-
const rule = matchRouteRules(path);
|
|
2936
|
-
if (rule.redirect || rule.proxy) {
|
|
2937
|
-
const deploymentRule = nitro.options.routeRules[path];
|
|
2938
|
-
const runtimeRule = runtimeRouteRules[path];
|
|
2939
|
-
runtimeRouteRules[path] = {
|
|
2940
|
-
...deploymentRule,
|
|
2941
|
-
...runtimeRule,
|
|
2942
|
-
headers: defu$1(values, runtimeRule?.headers)
|
|
2943
|
-
};
|
|
2944
|
-
} else {
|
|
2945
|
-
prerenderedMarkdownHeaders.push([decodePath(path), values]);
|
|
2946
|
-
}
|
|
2947
|
-
}
|
|
2948
|
-
nitro.options.runtimeConfig.nitro.routeRules = runtimeRouteRules;
|
|
2949
|
-
});
|
|
2950
|
-
nitro.hooks.hook("compiled", async () => {
|
|
2951
|
-
const generatedHeadersPath = join(nitro.options.output.publicDir, "_headers");
|
|
2952
|
-
let headersPath = generatedHeadersPath;
|
|
2953
|
-
let staticDiscoverySupported = isCloudflarePreset;
|
|
2954
|
-
if (isCloudflarePreset) {
|
|
2955
|
-
const wranglerPath = join(nitro.options.output.serverDir, "wrangler.json");
|
|
2956
|
-
const wrangler = await readFile(wranglerPath, "utf8").then((contents) => JSON.parse(contents)).catch((error) => {
|
|
2957
|
-
if (error.code === "ENOENT")
|
|
2958
|
-
return void 0;
|
|
2959
|
-
throw error;
|
|
2960
|
-
});
|
|
2961
|
-
const assetsDirectory = wrangler?.assets?.directory || wrangler?.pages_build_output_dir;
|
|
2962
|
-
const assetsRoot = assetsDirectory ? resolve(dirname(wranglerPath), assetsDirectory) : String(nitro.options.preset).startsWith("cloudflare-pages") ? nitro.options.output.dir : resolve(nitro.options.output.publicDir, ...staticBaseURL.split("/").filter(Boolean).map(() => ".."));
|
|
2963
|
-
const assetPath = relative(nitro.options.output.dir, assetsRoot);
|
|
2964
|
-
if (assetPath === ".." || assetPath.startsWith("../")) {
|
|
2965
|
-
staticDiscoverySupported = false;
|
|
2966
|
-
logger.warn("Skipped shared discovery headers because Cloudflare assets are outside the Nitro output directory.");
|
|
2967
|
-
} else {
|
|
2968
|
-
headersPath = join(assetsRoot, "_headers");
|
|
2969
|
-
}
|
|
2970
|
-
}
|
|
2971
|
-
logger.debug(`Checking for _headers file: ${headersPath}`);
|
|
2972
|
-
const exists = await access(headersPath).then(() => true).catch(() => false);
|
|
2973
|
-
if (exists || isCloudflarePreset) {
|
|
2974
|
-
const readHeaders = (path) => readFile(path, "utf8").catch((error) => {
|
|
2975
|
-
if (error.code === "ENOENT")
|
|
2976
|
-
return "";
|
|
2977
|
-
throw error;
|
|
2978
|
-
});
|
|
2979
|
-
const rootHeaders = exists ? await readHeaders(headersPath) : "";
|
|
2980
|
-
const generatedHeaders = generatedHeadersPath === headersPath ? "" : await readHeaders(generatedHeadersPath);
|
|
2981
|
-
const headers = [rootHeaders, generatedHeaders].filter(Boolean).join("\n");
|
|
2982
|
-
const markdownPattern = isCloudflarePreset ? toDeployedRoute("/*.md", staticBaseURL) : "/*.md";
|
|
2983
|
-
let mergedHeaders = ensureStaticHeader(
|
|
2984
|
-
headers,
|
|
2985
|
-
markdownPattern,
|
|
2986
|
-
"Content-Type",
|
|
2987
|
-
"text/markdown; charset=utf-8"
|
|
2988
|
-
);
|
|
2989
|
-
mergedHeaders = ensureStaticHeader(mergedHeaders, markdownPattern, "Vary", "Accept", "append");
|
|
2990
|
-
if (config.describedby !== false) {
|
|
2991
|
-
mergedHeaders = ensureStaticHeader(
|
|
2992
|
-
mergedHeaders,
|
|
2993
|
-
markdownPattern,
|
|
2994
|
-
"Link",
|
|
2995
|
-
staticDescribedbyEntry(nitro.options.baseURL || "/")
|
|
2996
|
-
);
|
|
2997
|
-
}
|
|
2998
|
-
if (isCloudflarePreset) {
|
|
2999
|
-
const hasArtifact = (route) => access(join(nitro.options.output.publicDir, route)).then(() => true).catch((error) => {
|
|
3000
|
-
if (error.code === "ENOENT")
|
|
3001
|
-
return false;
|
|
3002
|
-
throw error;
|
|
3003
|
-
});
|
|
3004
|
-
const discovery = [];
|
|
3005
|
-
if (staticDiscoverySupported && config.describedby !== false && await hasArtifact("/llms.txt"))
|
|
3006
|
-
discovery.push(staticDescribedbyEntry(staticBaseURL));
|
|
3007
|
-
if (staticDiscoverySupported && apiCatalogConfig && await hasArtifact(API_CATALOG_PATH))
|
|
3008
|
-
discovery.push(`<${encodeURI(apiCatalogConfig.href)}>; rel="api-catalog"`);
|
|
3009
|
-
if (staticDiscoverySupported && aiTermsLink && await hasArtifact(AI_TERMS_PATH))
|
|
3010
|
-
discovery.push(aiTermsLink);
|
|
3011
|
-
mergedHeaders = mergeStaticDiscoveryHeaders(mergedHeaders, staticBaseURL, discovery);
|
|
3012
|
-
mergedHeaders = dedupeStaticHeaders(mergedHeaders, ["Content-Type", "Link", "Vary"]);
|
|
3013
|
-
mergedHeaders = normalizeStaticContentSignalHeaders(mergedHeaders, aiTermsLink ? [...discovery, aiTermsLink] : discovery);
|
|
3014
|
-
const budget = enforceStaticHeaderBudget(mergedHeaders, CLOUDFLARE_STATIC_HEADER_RULE_LIMIT);
|
|
3015
|
-
if (budget.dropped > 0) {
|
|
3016
|
-
mergedHeaders = budget.contents;
|
|
3017
|
-
noteSharedMarkdownRule(budget.total + budget.dropped, budget.dropped);
|
|
3018
|
-
}
|
|
3019
|
-
if (budget.total > CLOUDFLARE_STATIC_HEADER_RULE_LIMIT && /^\s+(?:content-signal\s*:|!\s*content-signal\s*$)/im.test(budget.contents))
|
|
3020
|
-
throw new Error(`Content-Signal policy rules exceed Cloudflare's ${CLOUDFLARE_STATIC_HEADER_RULE_LIMIT}-rule limit. Reduce per-page policies or use a shared policy.`);
|
|
3021
|
-
if (budget.total > CLOUDFLARE_STATIC_HEADER_RULE_LIMIT)
|
|
3022
|
-
logger.warn(`_headers still has ${budget.total} rules after dropping the .md rules. Cloudflare will reject the deploy until the other rules fit under ${CLOUDFLARE_STATIC_HEADER_RULE_LIMIT}.`);
|
|
3023
|
-
}
|
|
3024
|
-
if (mergedHeaders !== rootHeaders || !exists) {
|
|
3025
|
-
await writeFile(headersPath, mergedHeaders);
|
|
3026
|
-
logger.debug("Merged .md charset header into _headers");
|
|
3027
|
-
}
|
|
3028
|
-
}
|
|
3029
|
-
});
|
|
3030
|
-
});
|
|
3031
|
-
}
|
|
3032
|
-
});
|
|
3033
|
-
|
|
3034
|
-
export { AGENT_SKILLS_SCHEMA as A, MARKDOWN_LINK_AVAILABILITY_FILE as M, module$1 as a, logger as l, matchingStaticContentSignals as m };
|