nuxt-ai-ready 3.5.0 → 3.6.0

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.
Files changed (41) hide show
  1. package/dist/chunks/agent-skills.mjs +5 -3
  2. package/dist/chunks/prerender.mjs +48 -24
  3. package/dist/cli.mjs +5 -5
  4. package/dist/module.d.mts +4 -0
  5. package/dist/module.json +2 -2
  6. package/dist/module.mjs +5 -3
  7. package/dist/runtime/ai-terms.d.ts +76 -0
  8. package/dist/runtime/ai-terms.js +1 -0
  9. package/dist/runtime/app/plugins/md-alternate.server.js +11 -3
  10. package/dist/runtime/llms-txt-utils.js +7 -9
  11. package/dist/runtime/server/db/schema/postgres.d.ts +8 -0
  12. package/dist/runtime/server/db/schema/sqlite.d.ts +8 -0
  13. package/dist/runtime/server/middleware/markdown.js +13 -175
  14. package/dist/runtime/server/middleware/render-markdown.d.ts +2 -0
  15. package/dist/runtime/server/middleware/render-markdown.js +163 -0
  16. package/dist/runtime/server/plugins/ai-terms.d.ts +2 -0
  17. package/dist/runtime/server/plugins/ai-terms.js +11 -0
  18. package/dist/runtime/server/plugins/markdown-negotiation.js +11 -1
  19. package/dist/runtime/server/routes/ai-terms.d.ts +2 -0
  20. package/dist/runtime/server/routes/ai-terms.js +22 -0
  21. package/dist/runtime/server/routes/api-catalog.js +6 -2
  22. package/dist/runtime/server/routes/llms.txt.get.js +3 -0
  23. package/dist/runtime/server/utils/auth.d.ts +1 -3
  24. package/dist/runtime/server/utils/auth.js +55 -25
  25. package/dist/runtime/server/utils/cloudflare-prerendered.d.ts +1 -1
  26. package/dist/runtime/server/utils/cloudflare-prerendered.js +17 -15
  27. package/dist/runtime/server/utils/link-header.d.ts +4 -0
  28. package/dist/runtime/server/utils/link-header.js +6 -2
  29. package/dist/runtime/server/utils/negotiation-decision.d.ts +4 -0
  30. package/dist/runtime/server/utils/negotiation-decision.js +8 -1
  31. package/dist/runtime/server/utils/negotiation-response.d.ts +3 -1
  32. package/dist/runtime/server/utils/negotiation-response.js +31 -9
  33. package/dist/runtime/sync-secret.d.ts +1 -0
  34. package/dist/runtime/sync-secret.js +2 -1
  35. package/dist/runtime/types.d.ts +12 -0
  36. package/dist/shared/{nuxt-ai-ready.BaNK8yfw.mjs → nuxt-ai-ready.Bzx0dNWj.mjs} +324 -36
  37. package/dist/shared/{nuxt-ai-ready.B3hAuOLQ.mjs → nuxt-ai-ready.DCd-1s1G.mjs} +1 -1
  38. package/dist/types.d.mts +2 -0
  39. package/package.json +36 -36
  40. package/skills/nuxt-ai-ready/SKILL.md +52 -96
  41. package/dist/cli.d.mts +0 -1
@@ -1,181 +1,19 @@
1
- import { createError, defineEventHandler, getRequestURL, setHeader, setResponseStatus } from "#nuxtseo/h3";
2
- import { useNitroApp, useRuntimeConfig } from "#nuxtseo/nitro";
3
- import { resolveLocaleAlternateUrl } from "../../i18n-url.js";
4
- import { insertLlmsTxtDirective } from "../../llms-txt-directive.js";
5
- import { absoluteMarkdownLinks } from "../../markdown-links.js";
6
- import { logger } from "../logger.js";
7
- import { computeLocaleAlternates, resolveLocaleFromRoute } from "../utils/i18n.js";
8
- import { resolveMarkdownRedirect } from "../utils/markdown-redirect.js";
9
- import { INTERNAL_HEADER } from "../utils/negotiation-decision.js";
10
- import { applyNegotiation, buildNegotiationContext, decideNegotiation, ensureSiteConfig, setMarkdownHeaders } from "../utils/negotiation-response.js";
11
- import { appendSitemapSection, isSitemapMdRequest, SITEMAP_MD_ROUTE } from "../utils/sitemap-md.js";
12
- function notFoundMarkdown(ctx, canonicalUrl, build) {
13
- const { path, config, resolveUrl, routeContext } = ctx;
14
- const body = [
15
- `# Page not found`,
16
- ``,
17
- `No content is available at \`${path}\`.`,
18
- ``,
19
- `Try one of these resources:`,
20
- ``,
21
- `- [Sitemap](${resolveUrl("/sitemap.xml")})`,
22
- `- [llms.txt](${resolveUrl("/llms.txt")})`,
23
- ...config.llmsFullTxt === false ? [] : [`- [llms-full.txt](${resolveUrl("/llms-full.txt")})`],
24
- ``
25
- ].join("\n");
26
- const i18n = config.i18n;
27
- const locale = i18n ? resolveLocaleFromRoute(path, i18n, routeContext).locale : void 0;
28
- const alternates = i18n ? computeLocaleAlternates(path, i18n, routeContext).map((a) => ({
29
- hreflang: a.hreflang,
30
- href: resolveLocaleAlternateUrl(a, resolveUrl)
31
- })) : void 0;
32
- const frontmatter = build({
33
- title: "Page not found",
34
- description: `No content is available at ${path}.`,
35
- canonical_url: canonicalUrl,
36
- locale,
37
- alternates
38
- });
39
- return `${frontmatter}
40
- ${body}`;
41
- }
1
+ import { createError, defineEventHandler } from "#nuxtseo/h3";
2
+ import { useRuntimeConfig } from "#nuxtseo/nitro";
3
+ import { applyNegotiation, decideNegotiation } from "../utils/negotiation-response.js";
4
+ import { isSitemapMdRequest } from "../utils/sitemap-md.js";
42
5
  export default defineEventHandler(async (event) => {
43
- const runtimeConfig = useRuntimeConfig(event);
44
- if (isSitemapMdRequest(event.path, runtimeConfig.app.baseURL, runtimeConfig["nuxt-ai-ready"]?.sitemapMd !== false))
45
- return;
6
+ if (event.path.split("?")[0]?.endsWith("/sitemap.md")) {
7
+ const runtimeConfig = useRuntimeConfig(event);
8
+ if (isSitemapMdRequest(event.path, runtimeConfig.app.baseURL, runtimeConfig["nuxt-ai-ready"]?.sitemapMd !== false))
9
+ return;
10
+ }
46
11
  const decision = decideNegotiation(event, "middleware");
12
+ if (decision._tag === "missing-markdown")
13
+ throw createError({ statusCode: 404, statusMessage: "Markdown page not found" });
47
14
  const negotiationResponse = await applyNegotiation(event, decision);
48
15
  if (decision._tag !== "render")
49
16
  return negotiationResponse;
50
- await ensureSiteConfig(event);
51
- const ctx = buildNegotiationContext(event, decision.path);
52
- const { path, config, resolvePath, resolveUrl, routeContext } = ctx;
53
- const canonicalUrl = resolveUrl(path);
54
- const finalizeMarkdown = (markdown) => {
55
- const withSitemap = config.sitemapMd === false ? markdown : appendSitemapSection(markdown, resolvePath(SITEMAP_MD_ROUTE));
56
- const llmsTxt = config.llmsTxt;
57
- const withDirective = llmsTxt?.directive?.markdown === false ? withSitemap : insertLlmsTxtDirective(withSitemap, resolveUrl("/llms.txt"));
58
- return absoluteMarkdownLinks(withDirective, canonicalUrl);
59
- };
60
- const [
61
- { tryGetContentMarkdown },
62
- { fetchRawWithEvent },
63
- { buildFrontmatter, layerFrontmatter }
64
- ] = await Promise.all([
65
- import("../utils/content.js"),
66
- import("../utils/fetch.js"),
67
- import("../utils/frontmatter.js")
68
- ]);
69
- const sourceContext = { route: path, event, source: null };
70
- await useNitroApp().hooks.callHook("ai-ready:markdown:source", sourceContext);
71
- if (sourceContext.source) {
72
- const { markdown, title, description, updatedAt } = sourceContext.source;
73
- const responseMarkdown = layerFrontmatter({
74
- title: title ?? path,
75
- description,
76
- canonical_url: canonicalUrl,
77
- last_updated: updatedAt
78
- }, markdown);
79
- setMarkdownHeaders(event, ctx);
80
- return finalizeMarkdown(responseMarkdown);
81
- }
82
- const contentPage = await tryGetContentMarkdown(event, path).catch((e) => {
83
- logger.debug(`[markdown] Content lookup failed for ${path}`, e);
84
- return null;
85
- });
86
- if (contentPage) {
87
- logger.debug(`[markdown] Serving content source for ${path} (${contentPage.markdown.length} bytes)`);
88
- const frontmatter = buildFrontmatter({
89
- title: contentPage.title,
90
- description: contentPage.description,
91
- canonical_url: canonicalUrl,
92
- last_updated: contentPage.updatedAt
93
- });
94
- setMarkdownHeaders(event, ctx);
95
- return finalizeMarkdown(`${frontmatter}
96
- ${contentPage.markdown}`);
97
- }
98
- const origin = getRequestURL(event).origin;
99
- const siteUrl = resolveUrl("/");
100
- const redirectOptions = {
101
- pageUrl: `${origin}${resolvePath(path)}`,
102
- origins: URL.canParse(siteUrl) ? [new URL(siteUrl).origin] : []
103
- };
104
- let htmlPath = resolvePath(path);
105
- let response = null;
106
- for (let attempt = 0; attempt < 2; attempt++) {
107
- logger.debug(`[markdown] Fetching HTML for ${htmlPath}`);
108
- response = await fetchRawWithEvent(event, htmlPath, {
109
- headers: { [INTERNAL_HEADER]: "1" },
110
- redirect: "manual"
111
- }).catch((e) => {
112
- logger.error(`Failed to fetch HTML for ${htmlPath}`, e);
113
- return null;
114
- });
115
- const location = response && response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
116
- if (!response || !location)
117
- break;
118
- const redirect = resolveMarkdownRedirect(location, redirectOptions);
119
- if (redirect._tag === "follow" && attempt === 0) {
120
- htmlPath = redirect.path;
121
- continue;
122
- }
123
- setHeader(event, "location", redirect._tag === "redirect" ? redirect.location : location);
124
- return createError({
125
- statusCode: response.status,
126
- statusMessage: response.statusText
127
- });
128
- }
129
- if (!response) {
130
- throw createError({
131
- statusCode: 502,
132
- statusMessage: "Bad Gateway"
133
- });
134
- }
135
- if (!response.ok && response.status !== 404)
136
- return response;
137
- if (response.status === 404) {
138
- setMarkdownHeaders(event, ctx, response.headers);
139
- setResponseStatus(event, 404);
140
- return notFoundMarkdown(ctx, canonicalUrl, buildFrontmatter);
141
- }
142
- const contentType = response.headers.get("content-type") || "";
143
- if (!contentType.includes("text/html")) {
144
- setMarkdownHeaders(event, ctx, response.headers);
145
- setResponseStatus(event, 404);
146
- return notFoundMarkdown(ctx, canonicalUrl, buildFrontmatter);
147
- }
148
- const html = await response.text();
149
- logger.debug(`[markdown] Fetched HTML for ${path} (${html.length} bytes)`);
150
- const [
151
- { queryPages },
152
- { convertHtmlToMarkdown, extractLastUpdated }
153
- ] = await Promise.all([
154
- import("../db/queries.js"),
155
- import("../utils.js")
156
- ]);
157
- const dbPage = await queryPages(event, { route: path }).catch((err) => {
158
- logger.debug(`[markdown] DB lookup failed for ${path}:`, err);
159
- return void 0;
160
- });
161
- const lastUpdated = dbPage?.updatedAt || extractLastUpdated(html);
162
- const additionalFrontmatter = {
163
- canonical_url: canonicalUrl
164
- };
165
- if (lastUpdated)
166
- additionalFrontmatter.last_updated = lastUpdated;
167
- if (config.i18n) {
168
- additionalFrontmatter.locale = resolveLocaleFromRoute(path, config.i18n, routeContext).locale;
169
- }
170
- const result = await convertHtmlToMarkdown(
171
- html,
172
- canonicalUrl,
173
- config.mdreamOptions,
174
- {
175
- hooks: { route: path, event, isPrerender: false },
176
- additionalFrontmatter
177
- }
178
- );
179
- setMarkdownHeaders(event, ctx, response.headers);
180
- return finalizeMarkdown(result.markdown);
17
+ const { renderMarkdown } = await import("#ai-ready-virtual/render-markdown.mjs");
18
+ return renderMarkdown?.(event, decision.path);
181
19
  });
@@ -0,0 +1,2 @@
1
+ import type { H3Event } from '#nuxtseo/h3';
2
+ export declare function renderMarkdown(event: H3Event, markdownPath: string): Promise<any>;
@@ -0,0 +1,163 @@
1
+ import { createError, getRequestURL, setHeader, setResponseStatus } from "#nuxtseo/h3";
2
+ import { useNitroApp } from "#nuxtseo/nitro";
3
+ import { resolveLocaleAlternateUrl } from "../../i18n-url.js";
4
+ import { insertLlmsTxtDirective } from "../../llms-txt-directive.js";
5
+ import { absoluteMarkdownLinks } from "../../markdown-links.js";
6
+ import { logger } from "../logger.js";
7
+ import { convertHtmlToMarkdown, extractLastUpdated } from "../utils.js";
8
+ import { tryGetContentMarkdown } from "../utils/content.js";
9
+ import { fetchRawWithEvent } from "../utils/fetch.js";
10
+ import { buildFrontmatter, layerFrontmatter } from "../utils/frontmatter.js";
11
+ import { computeLocaleAlternates, resolveLocaleFromRoute } from "../utils/i18n.js";
12
+ import { resolveMarkdownRedirect } from "../utils/markdown-redirect.js";
13
+ import { INTERNAL_HEADER } from "../utils/negotiation-decision.js";
14
+ import { buildNegotiationContext, ensureSiteConfig, setMarkdownHeaders } from "../utils/negotiation-response.js";
15
+ import { appendSitemapSection, SITEMAP_MD_ROUTE } from "../utils/sitemap-md.js";
16
+ function notFoundMarkdown(ctx, canonicalUrl, build) {
17
+ const { path, config, resolveUrl, routeContext } = ctx;
18
+ const body = [
19
+ `# Page not found`,
20
+ ``,
21
+ `No content is available at \`${path}\`.`,
22
+ ``,
23
+ `Try one of these resources:`,
24
+ ``,
25
+ `- [Sitemap](${resolveUrl("/sitemap.xml")})`,
26
+ `- [llms.txt](${resolveUrl("/llms.txt")})`,
27
+ ...config.llmsFullTxt === false ? [] : [`- [llms-full.txt](${resolveUrl("/llms-full.txt")})`],
28
+ ``
29
+ ].join("\n");
30
+ const i18n = config.i18n;
31
+ const locale = i18n ? resolveLocaleFromRoute(path, i18n, routeContext).locale : void 0;
32
+ const alternates = i18n ? computeLocaleAlternates(path, i18n, routeContext).map((a) => ({
33
+ hreflang: a.hreflang,
34
+ href: resolveLocaleAlternateUrl(a, resolveUrl)
35
+ })) : void 0;
36
+ const frontmatter = build({
37
+ title: "Page not found",
38
+ description: `No content is available at ${path}.`,
39
+ canonical_url: canonicalUrl,
40
+ locale,
41
+ alternates
42
+ });
43
+ return `${frontmatter}
44
+ ${body}`;
45
+ }
46
+ export async function renderMarkdown(event, markdownPath) {
47
+ await ensureSiteConfig(event);
48
+ const ctx = buildNegotiationContext(event, markdownPath);
49
+ const { path, config, resolvePath, resolveUrl, routeContext } = ctx;
50
+ const canonicalUrl = resolveUrl(path);
51
+ const finalizeMarkdown = (markdown) => {
52
+ const withSitemap = config.sitemapMd === false ? markdown : appendSitemapSection(markdown, resolvePath(SITEMAP_MD_ROUTE));
53
+ const llmsTxt = config.llmsTxt;
54
+ const withDirective = llmsTxt?.directive?.markdown === false ? withSitemap : insertLlmsTxtDirective(withSitemap, resolveUrl("/llms.txt"));
55
+ return absoluteMarkdownLinks(withDirective, canonicalUrl);
56
+ };
57
+ const sourceContext = { route: path, event, source: null };
58
+ await useNitroApp().hooks.callHook("ai-ready:markdown:source", sourceContext);
59
+ if (sourceContext.source) {
60
+ const { markdown, title, description, updatedAt } = sourceContext.source;
61
+ const responseMarkdown = layerFrontmatter({
62
+ title: title ?? path,
63
+ description,
64
+ canonical_url: canonicalUrl,
65
+ last_updated: updatedAt
66
+ }, markdown);
67
+ setMarkdownHeaders(event, ctx);
68
+ return finalizeMarkdown(responseMarkdown);
69
+ }
70
+ const contentPage = await tryGetContentMarkdown(event, path).catch((e) => {
71
+ logger.debug(`[markdown] Content lookup failed for ${path}`, e);
72
+ return null;
73
+ });
74
+ if (contentPage) {
75
+ logger.debug(`[markdown] Serving content source for ${path} (${contentPage.markdown.length} bytes)`);
76
+ const frontmatter = buildFrontmatter({
77
+ title: contentPage.title,
78
+ description: contentPage.description,
79
+ canonical_url: canonicalUrl,
80
+ last_updated: contentPage.updatedAt
81
+ });
82
+ setMarkdownHeaders(event, ctx);
83
+ return finalizeMarkdown(`${frontmatter}
84
+ ${contentPage.markdown}`);
85
+ }
86
+ const origin = getRequestURL(event).origin;
87
+ const siteUrl = resolveUrl("/");
88
+ const redirectOptions = {
89
+ pageUrl: `${origin}${resolvePath(path)}`,
90
+ origins: URL.canParse(siteUrl) ? [new URL(siteUrl).origin] : []
91
+ };
92
+ let htmlPath = resolvePath(path);
93
+ let response = null;
94
+ for (let attempt = 0; attempt < 2; attempt++) {
95
+ logger.debug(`[markdown] Fetching HTML for ${htmlPath}`);
96
+ response = await fetchRawWithEvent(event, htmlPath, {
97
+ headers: { [INTERNAL_HEADER]: "1" },
98
+ redirect: "manual"
99
+ }).catch((e) => {
100
+ logger.error(`Failed to fetch HTML for ${htmlPath}`, e);
101
+ return null;
102
+ });
103
+ const location = response && response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
104
+ if (!response || !location)
105
+ break;
106
+ const redirect = resolveMarkdownRedirect(location, redirectOptions);
107
+ if (redirect._tag === "follow" && attempt === 0) {
108
+ htmlPath = redirect.path;
109
+ continue;
110
+ }
111
+ setHeader(event, "location", redirect._tag === "redirect" ? redirect.location : location);
112
+ return createError({
113
+ statusCode: response.status,
114
+ statusMessage: response.statusText
115
+ });
116
+ }
117
+ if (!response) {
118
+ throw createError({
119
+ statusCode: 502,
120
+ statusMessage: "Bad Gateway"
121
+ });
122
+ }
123
+ if (!response.ok && response.status !== 404)
124
+ return response;
125
+ if (response.status === 404) {
126
+ setMarkdownHeaders(event, ctx, response.headers);
127
+ setResponseStatus(event, 404);
128
+ return notFoundMarkdown(ctx, canonicalUrl, buildFrontmatter);
129
+ }
130
+ const contentType = response.headers.get("content-type") || "";
131
+ if (!contentType.includes("text/html")) {
132
+ setMarkdownHeaders(event, ctx, response.headers);
133
+ setResponseStatus(event, 404);
134
+ return notFoundMarkdown(ctx, canonicalUrl, buildFrontmatter);
135
+ }
136
+ const html = await response.text();
137
+ logger.debug(`[markdown] Fetched HTML for ${path} (${html.length} bytes)`);
138
+ const { queryPages } = await import("../db/queries.js");
139
+ const dbPage = await queryPages(event, { route: path }).catch((err) => {
140
+ logger.debug(`[markdown] DB lookup failed for ${path}:`, err);
141
+ return void 0;
142
+ });
143
+ const lastUpdated = dbPage?.updatedAt || extractLastUpdated(html);
144
+ const additionalFrontmatter = {
145
+ canonical_url: canonicalUrl
146
+ };
147
+ if (lastUpdated)
148
+ additionalFrontmatter.last_updated = lastUpdated;
149
+ if (config.i18n) {
150
+ additionalFrontmatter.locale = resolveLocaleFromRoute(path, config.i18n, routeContext).locale;
151
+ }
152
+ const result = await convertHtmlToMarkdown(
153
+ html,
154
+ canonicalUrl,
155
+ config.mdreamOptions,
156
+ {
157
+ hooks: { route: path, event, isPrerender: false },
158
+ additionalFrontmatter
159
+ }
160
+ );
161
+ setMarkdownHeaders(event, ctx, response.headers);
162
+ return finalizeMarkdown(result.markdown);
163
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,11 @@
1
+ import { defineNitroPlugin, useRuntimeConfig } from "#nuxtseo/nitro";
2
+ export default defineNitroPlugin((nitro) => {
3
+ nitro.hooks.hook("robots:robots-txt", (context) => {
4
+ const href = useRuntimeConfig()["nuxt-ai-ready"].aiTerms?.href;
5
+ if (href)
6
+ context.robotsTxt = `${context.robotsTxt.trimEnd()}
7
+
8
+ AI-Terms: ${href}
9
+ `;
10
+ });
11
+ });
@@ -1,4 +1,6 @@
1
- import { defineEventHandler } from "#nuxtseo/h3";
1
+ import { decodePath, withoutBase, withoutTrailingSlash } from "ufo";
2
+ import prerenderedMarkdownHeaders from "#ai-ready-virtual/prerendered-markdown-headers.mjs";
3
+ import { defineEventHandler, getRequestURL, setHeader } from "#nuxtseo/h3";
2
4
  import { defineNitroPlugin, useRuntimeConfig } from "#nuxtseo/nitro";
3
5
  import { logger } from "../logger.js";
4
6
  import { serveCloudflarePrerenderedPage } from "../utils/cloudflare-prerendered.js";
@@ -23,6 +25,14 @@ function resolveH3Runtime(candidate) {
23
25
  return { _tag: "unsupported" };
24
26
  }
25
27
  const negotiationHandler = defineEventHandler(async (event) => {
28
+ if (prerenderedMarkdownHeaders.size && (event.path.includes(".md") || event.path.includes("%"))) {
29
+ const path = decodePath(withoutTrailingSlash(withoutBase(getRequestURL(event).pathname, useRuntimeConfig().app.baseURL)));
30
+ const headers = prerenderedMarkdownHeaders.get(path);
31
+ if (headers) {
32
+ for (const [name, value] of Object.entries(headers))
33
+ setHeader(event, name, value);
34
+ }
35
+ }
26
36
  const decision = decideNegotiation(event, "early");
27
37
  const response = await applyNegotiation(event, decision);
28
38
  if (response !== void 0 || decision._tag !== "html")
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/server").EventHandler<import("../../ai-terms.js").AiTermsDocument | null | undefined>;
2
+ export default _default;
@@ -0,0 +1,22 @@
1
+ import { createError, defineEventHandler, setResponseStatus, useRuntimeConfig } from "nuxt/server";
2
+ export default defineEventHandler((event) => {
3
+ event.res.headers.set("Access-Control-Allow-Origin", "*");
4
+ event.res.headers.set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
5
+ event.res.headers.set("Access-Control-Allow-Headers", "AI-Purpose");
6
+ if (event.req.method === "OPTIONS") {
7
+ setResponseStatus(event, 204);
8
+ return null;
9
+ }
10
+ if (!["GET", "HEAD"].includes(event.req.method)) {
11
+ event.res.headers.set("Allow", "GET, HEAD, OPTIONS");
12
+ throw createError({ status: 405, statusText: "Method Not Allowed" });
13
+ }
14
+ const config = useRuntimeConfig()["nuxt-ai-ready"].aiTerms;
15
+ if (!config)
16
+ throw createError({ status: 404, message: "AI Terms is not configured." });
17
+ event.res.headers.set("Content-Type", "application/json; charset=utf-8");
18
+ event.res.headers.set("Cache-Control", "public, max-age=3600");
19
+ if (event.req.method === "HEAD")
20
+ return;
21
+ return config.document;
22
+ });
@@ -11,11 +11,15 @@ export default defineEventHandler((event) => {
11
11
  }
12
12
  if (!["GET", "HEAD"].includes(event.req.method))
13
13
  throw createError({ status: 405, statusText: "Method Not Allowed" });
14
- const config = useRuntimeConfig()["nuxt-ai-ready"].apiCatalog;
14
+ const runtimeConfig = useRuntimeConfig()["nuxt-ai-ready"];
15
+ const config = runtimeConfig.apiCatalog;
15
16
  if (!config)
16
17
  throw createError({ status: 404, message: "API catalog is not configured" });
17
18
  event.res.headers.set("content-type", config.mediaType);
18
- event.res.headers.set("link", `<${config.href}>; rel="api-catalog"`);
19
+ event.res.headers.set("link", [
20
+ `<${config.href}>; rel="api-catalog"`,
21
+ runtimeConfig.aiTerms && `<${runtimeConfig.aiTerms.href}>; rel="ai-terms"`
22
+ ].filter(Boolean).join(", "));
19
23
  if (event.req.method === "HEAD")
20
24
  return;
21
25
  return config.document;
@@ -20,6 +20,9 @@ function getBuildLlmsTxtCached(maxAge) {
20
20
  return cached;
21
21
  }
22
22
  export default eventHandler(async (event) => {
23
+ const requestPath = event.path.split("?")[0];
24
+ if (!requestPath.endsWith("/llms.txt") && !/\/llms\/[^/]+\.txt$/i.test(requestPath))
25
+ return;
23
26
  const runtimeConfig = useRuntimeConfig(event);
24
27
  const path = toLogicalRoute(event.path.split("?")[0], runtimeConfig.app.baseURL);
25
28
  if (path !== "/llms.txt" && !/^\/llms\/[^/]+\.txt$/i.test(path))
@@ -1,7 +1,5 @@
1
1
  import type { H3Event } from '#nuxtseo/h3';
2
2
  /**
3
- * Verify the request has a valid Authorization: Bearer token.
4
- * Throws 401 if the token is missing or invalid.
5
- * Legacy tokens remain valid when no application secret is configured.
3
+ * Verify the runtime sync token. Throws 401 if the token is missing or invalid.
6
4
  */
7
5
  export declare function requireAuth(event: H3Event): Promise<void>;
@@ -2,40 +2,70 @@ import { deriveSecret } from "nuxt/server";
2
2
  import { logger } from "#ai-ready-virtual/logger.mjs";
3
3
  import { createError, getHeader, getQuery } from "#nuxtseo/h3";
4
4
  import { useRuntimeConfig } from "#nuxtseo/nitro";
5
- import { deriveRuntimeSyncSecret, LEGACY_RUNTIME_SYNC_SECRET_WARNING, RUNTIME_SYNC_SECRET_PURPOSE } from "../../sync-secret.js";
5
+ import { APPLICATION_SECRET_ERROR, deriveRuntimeSyncSecret, LEGACY_RUNTIME_SYNC_SECRET_WARNING, RUNTIME_SYNC_SECRET_PURPOSE } from "../../sync-secret.js";
6
6
  import { getCfEnv } from "./cloudflare.js";
7
+ const HMAC = { name: "HMAC", hash: "SHA-256" };
8
+ let tokenVerifier;
7
9
  let warnedLegacy = false;
8
- export async function requireAuth(event) {
10
+ function encodeToken(token) {
11
+ return Uint16Array.from({ length: token.length }, (_, index) => token.charCodeAt(index));
12
+ }
13
+ async function createTokenVerifier(token) {
14
+ const { subtle } = globalThis.crypto;
15
+ const key = await subtle.generateKey(HMAC, false, ["sign", "verify"]);
16
+ const signature = await subtle.sign(HMAC, key, encodeToken(token));
17
+ return { length: token.length, key, signature };
18
+ }
19
+ function resolveToken(source, mode) {
20
+ if (tokenVerifier?.source === source && tokenVerifier.mode === mode)
21
+ return tokenVerifier.promise;
22
+ const token = mode === "nuxt" ? deriveSecret(RUNTIME_SYNC_SECRET_PURPOSE) : mode === "binding" ? deriveRuntimeSyncSecret(source) : Promise.resolve(source);
23
+ const entry = {
24
+ source,
25
+ mode,
26
+ promise: token.then(createTokenVerifier)
27
+ };
28
+ tokenVerifier = entry;
29
+ entry.promise = entry.promise.catch((cause) => {
30
+ if (tokenVerifier === entry)
31
+ tokenVerifier = void 0;
32
+ throw cause;
33
+ });
34
+ return entry.promise;
35
+ }
36
+ async function resolveExpectedToken(event) {
9
37
  const bindings = getCfEnv(event);
10
- const config = useRuntimeConfig(event);
11
- const root = bindings?.NUXT_APP_SECRET === void 0 ? config.appSecret : bindings.NUXT_APP_SECRET;
12
- let secret;
13
- if (root !== void 0 && root !== "") {
14
- secret = await (bindings?.NUXT_APP_SECRET === void 0 ? deriveSecret(RUNTIME_SYNC_SECRET_PURPOSE) : deriveRuntimeSyncSecret(root)).catch((cause) => {
15
- throw createError({ statusCode: 500, message: "Set NUXT_APP_SECRET to a string with at least 32 characters.", cause });
16
- });
17
- } else {
18
- const moduleConfig = config["nuxt-ai-ready"];
19
- const legacy = bindings?.NUXT_NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? bindings?.NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? globalThis.process?.env?.NUXT_NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? globalThis.process?.env?.NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? moduleConfig.runtimeSyncSecret;
20
- if (typeof legacy !== "string" || !legacy) {
21
- throw createError({ statusCode: 500, message: "Set NUXT_APP_SECRET to a string with at least 32 characters." });
22
- }
38
+ const bindingRoot = bindings?.NUXT_APP_SECRET;
39
+ const configuredRoot = bindingRoot === void 0 ? useRuntimeConfig(event).appSecret : bindingRoot;
40
+ if (configuredRoot === void 0 || configuredRoot === "") {
41
+ const moduleConfig = useRuntimeConfig(event)["nuxt-ai-ready"];
42
+ const legacy = bindings?.NUXT_NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? bindings?.NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? globalThis.process?.env?.NUXT_NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? globalThis.process?.env?.NUXT_AI_READY_RUNTIME_SYNC_SECRET ?? moduleConfig?.runtimeSyncSecret;
43
+ if (typeof legacy !== "string" || !legacy)
44
+ throw createError({ statusCode: 500, message: APPLICATION_SECRET_ERROR });
23
45
  if (!warnedLegacy) {
24
46
  warnedLegacy = true;
25
47
  logger.warn(LEGACY_RUNTIME_SYNC_SECRET_WARNING);
26
48
  }
27
- secret = legacy;
49
+ return resolveToken(legacy, "legacy");
28
50
  }
51
+ const mode = bindingRoot === void 0 ? "nuxt" : "binding";
52
+ const root = mode === "nuxt" ? useRuntimeConfig().appSecret : bindingRoot;
53
+ if (typeof root !== "string" || root.length < 32)
54
+ throw createError({ statusCode: 500, message: APPLICATION_SECRET_ERROR });
55
+ return resolveToken(root, mode).catch((cause) => {
56
+ throw createError({ statusCode: 500, message: APPLICATION_SECRET_ERROR, cause });
57
+ });
58
+ }
59
+ export async function requireAuth(event) {
60
+ const secret = await resolveExpectedToken(event);
29
61
  const authHeader = getHeader(event, "authorization");
30
- let token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : void 0;
31
- if (!token) {
32
- const query = getQuery(event);
33
- if (query.secret) {
34
- token = String(query.secret);
35
- logger.warn("Using `?secret=` query parameter is deprecated. Use `Authorization: Bearer <token>` header instead. See https://github.com/harlan-zw/nuxt-ai-ready/releases/tag/v1.0.0");
36
- }
37
- }
38
- if (!token || token !== secret) {
62
+ const bearer = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : void 0;
63
+ const querySecret = bearer ? void 0 : getQuery(event).secret;
64
+ const received = bearer || (querySecret ? String(querySecret) : "");
65
+ if (received.length !== secret.length || !await globalThis.crypto.subtle.verify(HMAC, secret.key, secret.signature, encodeToken(received))) {
39
66
  throw createError({ statusCode: 401, message: "Unauthorized" });
40
67
  }
68
+ if (querySecret) {
69
+ logger.warn("Using `?secret=` is deprecated. Use the Authorization header with a bearer token.");
70
+ }
41
71
  }
@@ -1,3 +1,3 @@
1
1
  import type { H3Event } from '#nuxtseo/h3';
2
2
  /** Serve the original static HTML after negotiation, without rendering it again. */
3
- export declare function serveCloudflarePrerenderedPage(event: H3Event): Promise<Response | undefined>;
3
+ export declare function serveCloudflarePrerenderedPage(event: H3Event): Promise<Response> | undefined;
@@ -1,23 +1,25 @@
1
+ import cloudflareFallbackPaths from "#ai-ready-virtual/cloudflare-fallback-paths.mjs";
1
2
  import { getRequestHeaders, getRequestURL, getResponseHeaders } from "#nuxtseo/h3";
2
- import { useRuntimeConfig } from "#nuxtseo/nitro";
3
3
  import { mergeVaryHeader } from "../../cache-control.js";
4
- export async function serveCloudflarePrerenderedPage(event) {
5
- if (event.method !== "GET" && event.method !== "HEAD")
4
+ export function serveCloudflarePrerenderedPage(event) {
5
+ if (!cloudflareFallbackPaths.size)
6
6
  return;
7
- const config = useRuntimeConfig(event)["nuxt-ai-ready"];
8
- const url = getRequestURL(event);
9
- if (!config.cloudflarePrerenderedPages?.includes(url.pathname))
7
+ if (event.method !== "GET" && event.method !== "HEAD")
10
8
  return;
11
9
  const assets = event.context.cloudflare?.env?.ASSETS;
12
10
  if (!assets)
13
11
  return;
14
- const response = await assets.fetch(new Request(url, { method: event.method, headers: getRequestHeaders(event) }));
15
- const headers = new Headers(response.headers);
16
- for (const [name, value] of Object.entries(getResponseHeaders(event))) {
17
- if (value === void 0)
18
- continue;
19
- const header = Array.isArray(value) ? value.join(", ") : String(value);
20
- headers.set(name, name.toLowerCase() === "vary" ? mergeVaryHeader(headers.get(name) ?? void 0, header) : header);
21
- }
22
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
12
+ const url = getRequestURL(event);
13
+ if (!cloudflareFallbackPaths.has(url.pathname))
14
+ return;
15
+ return assets.fetch(new Request(url, { method: event.method, headers: getRequestHeaders(event) })).then((response) => {
16
+ const headers = new Headers(response.headers);
17
+ for (const [name, value] of Object.entries(getResponseHeaders(event))) {
18
+ if (value === void 0)
19
+ continue;
20
+ const header = Array.isArray(value) ? value.join(", ") : String(value);
21
+ headers.set(name, name.toLowerCase() === "vary" ? mergeVaryHeader(headers.get(name) ?? void 0, header) : header);
22
+ }
23
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
24
+ });
23
25
  }
@@ -13,7 +13,11 @@ interface LinkHeaderConfig {
13
13
  apiCatalog?: {
14
14
  href: string;
15
15
  };
16
+ aiTerms?: {
17
+ href: string;
18
+ };
16
19
  describedby?: boolean;
20
+ markdownAvailable?: false;
17
21
  i18n?: RuntimeI18nConfig | null;
18
22
  }
19
23
  export declare function buildLinkHeader(path: string, variant: 'html' | 'markdown', config: LinkHeaderConfig, resolveUrl?: LinkUrlResolver, routeContext?: RuntimeRouteContext): string;
@@ -17,8 +17,10 @@ function resolveHeaderUrl(path, resolveUrl) {
17
17
  function buildBaseParts(path, variant, config, resolveUrl) {
18
18
  const parts = [];
19
19
  if (variant === "html") {
20
- const href = resolveHeaderUrl(toMarkdownPath(path), resolveUrl);
21
- parts.push(`<${encodePathForHeader(href)}>; rel="alternate"; type="text/markdown"`);
20
+ if (config.markdownAvailable !== false) {
21
+ const href = resolveHeaderUrl(toMarkdownPath(path), resolveUrl);
22
+ parts.push(`<${encodePathForHeader(href)}>; rel="alternate"; type="text/markdown"`);
23
+ }
22
24
  } else {
23
25
  const href = resolveHeaderUrl(path, resolveUrl);
24
26
  parts.push(`<${encodePathForHeader(href)}>; rel="alternate"; type="text/html"`);
@@ -28,6 +30,8 @@ function buildBaseParts(path, variant, config, resolveUrl) {
28
30
  const href = resolveHeaderUrl(LLMS_TXT_PATH, resolveUrl);
29
31
  parts.push(`<${encodePathForHeader(href)}>; rel="describedby"`);
30
32
  }
33
+ if (config.aiTerms)
34
+ parts.push(`<${config.aiTerms.href}>; rel="ai-terms"`);
31
35
  return parts;
32
36
  }
33
37
  function appendLocaleParts(parts, path, variant, config, resolveUrl, routeContext) {