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