nuxt-ai-ready 3.6.0 → 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 +20 -24
- 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
|
@@ -6,316 +6,355 @@ import { parseSitemapCrawlState, serializeSitemapCrawlState } from "../utils/sit
|
|
|
6
6
|
import { deriveLocale, parseSourceLastmod, SEED_REFRESH_WINDOW_MS } from "./seed.js";
|
|
7
7
|
import { LIKE_ESCAPE, likeSubstring, maxRowsPerInsert, normalizeRoute, normalizeRouteKey, toFtsMatchQuery } from "./shared.js";
|
|
8
8
|
export { resolveSeedRefreshWindowMs, SEED_REFRESH_WINDOW_MS } from "./seed.js";
|
|
9
|
+
/** Try to get the current H3Event from context or use provided event */
|
|
9
10
|
function getEventFromContext(providedEvent) {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
11
|
+
if (providedEvent) return providedEvent;
|
|
12
|
+
try {
|
|
13
|
+
return useEvent();
|
|
14
|
+
} catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
17
|
}
|
|
18
18
|
let devNoticeShown = false;
|
|
19
19
|
let schemaInitializationState = { _tag: "Uninitialized" };
|
|
20
20
|
let dumpSyncState = { _tag: "Pending" };
|
|
21
21
|
function syncBuildDump(event) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
dumpSyncState = { _tag: "Syncing", promise };
|
|
36
|
-
return promise;
|
|
22
|
+
if (dumpSyncState._tag === "Synced") return Promise.resolve();
|
|
23
|
+
if (dumpSyncState._tag === "Syncing") return dumpSyncState.promise;
|
|
24
|
+
const promise = checkAndHandleStale(event).then(() => {
|
|
25
|
+
dumpSyncState = { _tag: "Synced" };
|
|
26
|
+
}, (error) => {
|
|
27
|
+
dumpSyncState = { _tag: "Pending" };
|
|
28
|
+
throw error;
|
|
29
|
+
});
|
|
30
|
+
dumpSyncState = {
|
|
31
|
+
_tag: "Syncing",
|
|
32
|
+
promise
|
|
33
|
+
};
|
|
34
|
+
return promise;
|
|
37
35
|
}
|
|
38
36
|
const RE_FTS_CHARS = /[*:^"()]/g;
|
|
37
|
+
/** Get database, with dev mode notice and prerender handling */
|
|
39
38
|
async function getDb(event) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
39
|
+
if (import.meta.dev) {
|
|
40
|
+
if (!devNoticeShown) {
|
|
41
|
+
logger.info("Page data unavailable in dev. Run `nuxi generate` for full metadata.");
|
|
42
|
+
devNoticeShown = true;
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
// During prerender, read from build-time SQLite via virtual module
|
|
47
|
+
if (import.meta.prerender) {
|
|
48
|
+
return getPrerenderDb();
|
|
49
|
+
}
|
|
50
|
+
// Runtime: use raw database executor
|
|
51
|
+
const resolvedEvent = getEventFromContext(event);
|
|
52
|
+
// `aiReady.database: false` ships no driver. Callers treat a null database
|
|
53
|
+
// as "no page data", the same as dev, so llms.txt degrades to the sitemap.
|
|
54
|
+
const cfg = useRuntimeConfig();
|
|
55
|
+
const database = cfg["nuxt-ai-ready"]?.database?._tag;
|
|
56
|
+
if (database === "Disabled") return null;
|
|
57
|
+
const db = await useRawDb(resolvedEvent);
|
|
58
|
+
if (schemaInitializationState._tag === "Uninitialized") {
|
|
59
|
+
const promise = initSchema(resolvedEvent).then(() => {
|
|
60
|
+
schemaInitializationState = { _tag: "Initialized" };
|
|
61
|
+
}).catch((error) => {
|
|
62
|
+
schemaInitializationState = { _tag: "Uninitialized" };
|
|
63
|
+
throw error;
|
|
64
|
+
});
|
|
65
|
+
schemaInitializationState = {
|
|
66
|
+
_tag: "Initializing",
|
|
67
|
+
promise
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (schemaInitializationState._tag === "Initializing") await schemaInitializationState.promise;
|
|
71
|
+
if (database === "Enabled") await syncBuildDump(resolvedEvent);
|
|
72
|
+
return db;
|
|
70
73
|
}
|
|
74
|
+
/** Get prerender database adapter (reads from build-time SQLite) */
|
|
71
75
|
async function getPrerenderDb() {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
76
|
+
const m = await import("#ai-ready-virtual/read-page-data.mjs");
|
|
77
|
+
const data = await m.readPageDataFromFilesystem();
|
|
78
|
+
// Create a minimal adapter that returns the cached data
|
|
79
|
+
const pages = data.pages || [];
|
|
80
|
+
const errorRoutes = new Set(data.errorRoutes || []);
|
|
81
|
+
// Helper to check if SQL requests markdown field
|
|
82
|
+
const wantsMarkdown = (sql) => sql.includes("SELECT *") || sql.toLowerCase().includes("markdown");
|
|
83
|
+
return {
|
|
84
|
+
dialect: "sqlite",
|
|
85
|
+
all: async (sql, params = []) => {
|
|
86
|
+
// Parse basic queries
|
|
87
|
+
const isErrorQuery = sql.includes("is_error = 1") || params.includes(1) && sql.includes("is_error");
|
|
88
|
+
const excludeErrors = sql.includes("is_error = 0");
|
|
89
|
+
const includeMarkdown = wantsMarkdown(sql);
|
|
90
|
+
const admittedRoutes = sql.includes("WHERE route IN (") ? new Set(params) : undefined;
|
|
91
|
+
if (isErrorQuery) {
|
|
92
|
+
return [...errorRoutes].map((route) => ({
|
|
93
|
+
route,
|
|
94
|
+
title: "",
|
|
95
|
+
description: "",
|
|
96
|
+
...includeMarkdown ? { markdown: "" } : {},
|
|
97
|
+
headings: "[]",
|
|
98
|
+
keywords: "[]",
|
|
99
|
+
updated_at: "",
|
|
100
|
+
is_error: 1,
|
|
101
|
+
indexed: 0,
|
|
102
|
+
locale: ""
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
const filtered = pages.filter((p) => (!excludeErrors || !errorRoutes.has(p.route)) && (!admittedRoutes || admittedRoutes.has(p.route)));
|
|
106
|
+
const rows = filtered.map((p) => ({
|
|
107
|
+
route: p.route,
|
|
108
|
+
title: p.title,
|
|
109
|
+
description: p.description,
|
|
110
|
+
...includeMarkdown ? { markdown: p.markdown } : {},
|
|
111
|
+
headings: p.headings,
|
|
112
|
+
keywords: JSON.stringify(p.keywords),
|
|
113
|
+
updated_at: p.updatedAt,
|
|
114
|
+
is_error: errorRoutes.has(p.route) ? 1 : 0,
|
|
115
|
+
indexed: 1,
|
|
116
|
+
locale: p.locale || ""
|
|
117
|
+
}));
|
|
118
|
+
if (admittedRoutes && !excludeErrors) {
|
|
119
|
+
for (const route of errorRoutes) {
|
|
120
|
+
if (admittedRoutes.has(route)) {
|
|
121
|
+
rows.push({
|
|
122
|
+
route,
|
|
123
|
+
title: "",
|
|
124
|
+
description: "",
|
|
125
|
+
headings: [],
|
|
126
|
+
keywords: "[]",
|
|
127
|
+
updated_at: "",
|
|
128
|
+
is_error: 1,
|
|
129
|
+
indexed: 0,
|
|
130
|
+
locale: ""
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return rows;
|
|
136
|
+
},
|
|
137
|
+
first: async (sql, params = []) => {
|
|
138
|
+
if (sql.includes("WHERE route = ?")) {
|
|
139
|
+
const route = params[0];
|
|
140
|
+
const page = pages.find((p) => p.route === route);
|
|
141
|
+
if (!page) return undefined;
|
|
142
|
+
const includeMarkdown = wantsMarkdown(sql);
|
|
143
|
+
return {
|
|
144
|
+
route: page.route,
|
|
145
|
+
title: page.title,
|
|
146
|
+
description: page.description,
|
|
147
|
+
...includeMarkdown ? { markdown: page.markdown } : {},
|
|
148
|
+
headings: page.headings,
|
|
149
|
+
keywords: JSON.stringify(page.keywords),
|
|
150
|
+
updated_at: page.updatedAt,
|
|
151
|
+
is_error: errorRoutes.has(page.route) ? 1 : 0,
|
|
152
|
+
indexed: 1,
|
|
153
|
+
locale: page.locale || ""
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
return undefined;
|
|
157
|
+
},
|
|
158
|
+
exec: async (_query, _params = []) => {
|
|
159
|
+
// No-op for prerender (read-only)
|
|
160
|
+
},
|
|
161
|
+
batch: async (_queries) => {
|
|
162
|
+
// No-op for prerender (read-only)
|
|
163
|
+
}
|
|
164
|
+
};
|
|
146
165
|
}
|
|
166
|
+
/** Read only admitted page metadata. Each query fits D1's 100 parameter limit. */
|
|
147
167
|
export async function queryPageMetadata(event, routes) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
168
|
+
if (!routes.length) return [];
|
|
169
|
+
const db = await getDb(event);
|
|
170
|
+
if (!db) return [];
|
|
171
|
+
const unique = [...new Set(routes)];
|
|
172
|
+
const pages = [];
|
|
173
|
+
for (let i = 0; i < unique.length; i += 100) {
|
|
174
|
+
const batch = unique.slice(i, i + 100);
|
|
175
|
+
const rows = await db.all(`SELECT route, title, description, is_error, locale FROM ai_ready_pages WHERE route IN (${batch.map(() => "?").join(", ")})`, batch);
|
|
176
|
+
pages.push(...rows.map((row) => ({
|
|
177
|
+
route: row.route,
|
|
178
|
+
title: row.title,
|
|
179
|
+
description: row.description,
|
|
180
|
+
isError: row.is_error === 1,
|
|
181
|
+
locale: row.locale || ""
|
|
182
|
+
})));
|
|
183
|
+
}
|
|
184
|
+
return pages;
|
|
164
185
|
}
|
|
165
186
|
function buildWhereClause(where) {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
+
const conditions = [];
|
|
188
|
+
const params = [];
|
|
189
|
+
if (where?.pending !== undefined) {
|
|
190
|
+
conditions.push("indexed = ?");
|
|
191
|
+
params.push(where.pending ? 0 : 1);
|
|
192
|
+
}
|
|
193
|
+
if (where?.hasError !== undefined) {
|
|
194
|
+
conditions.push("is_error = ?");
|
|
195
|
+
params.push(where.hasError ? 1 : 0);
|
|
196
|
+
}
|
|
197
|
+
if (where?.source) {
|
|
198
|
+
conditions.push("source = ?");
|
|
199
|
+
params.push(where.source);
|
|
200
|
+
}
|
|
201
|
+
// Default: exclude errors unless explicitly querying errors
|
|
202
|
+
if (where?.hasError === undefined) {
|
|
203
|
+
conditions.push("is_error = 0");
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
sql: conditions.length ? `WHERE ${conditions.join(" AND ")}` : "",
|
|
207
|
+
params
|
|
208
|
+
};
|
|
187
209
|
}
|
|
188
210
|
function safeJsonParse(json, fallback) {
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
}
|
|
211
|
+
if (!json) return fallback;
|
|
212
|
+
try {
|
|
213
|
+
return JSON.parse(json);
|
|
214
|
+
} catch {
|
|
215
|
+
return fallback;
|
|
216
|
+
}
|
|
196
217
|
}
|
|
197
218
|
function toNumber(value, fallback = 0) {
|
|
198
|
-
|
|
219
|
+
return value === null || value === undefined ? fallback : Number(value);
|
|
199
220
|
}
|
|
200
221
|
function toNullableNumber(value) {
|
|
201
|
-
|
|
222
|
+
return value === null || value === undefined ? null : Number(value);
|
|
202
223
|
}
|
|
203
224
|
function rowToEntry(row) {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
225
|
+
return {
|
|
226
|
+
route: row.route,
|
|
227
|
+
title: row.title,
|
|
228
|
+
description: row.description,
|
|
229
|
+
headings: safeJsonParse(row.headings, []),
|
|
230
|
+
keywords: safeJsonParse(row.keywords, []),
|
|
231
|
+
updatedAt: row.updated_at,
|
|
232
|
+
isError: row.is_error === 1,
|
|
233
|
+
locale: row.locale || ""
|
|
234
|
+
};
|
|
214
235
|
}
|
|
215
236
|
function rowToData(row) {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
237
|
+
return {
|
|
238
|
+
...rowToEntry(row),
|
|
239
|
+
markdown: row.markdown
|
|
240
|
+
};
|
|
220
241
|
}
|
|
242
|
+
/**
|
|
243
|
+
* Get lastmod (updatedAt) for all indexed pages
|
|
244
|
+
* Returns a Map for O(1) lookup when enriching sitemaps
|
|
245
|
+
*/
|
|
221
246
|
export async function getPageLastmods(event) {
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
return map;
|
|
247
|
+
const db = await getDb(event);
|
|
248
|
+
if (!db) return new Map();
|
|
249
|
+
const rows = await db.all("SELECT route, updated_at FROM ai_ready_pages WHERE indexed = 1 AND is_error = 0");
|
|
250
|
+
const map = new Map();
|
|
251
|
+
for (const row of rows) {
|
|
252
|
+
if (row.route && row.updated_at) {
|
|
253
|
+
map.set(row.route, row.updated_at);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return map;
|
|
235
257
|
}
|
|
236
258
|
export async function queryPages(event, options = {}) {
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
259
|
+
const { route, includeMarkdown, where, limit, offset } = options;
|
|
260
|
+
const db = await getDb(event);
|
|
261
|
+
if (!db) {
|
|
262
|
+
return route ? undefined : [];
|
|
263
|
+
}
|
|
264
|
+
// Project only the columns actually needed. markdown is by far the largest
|
|
265
|
+
// column, so meta-only consumers shouldn't pay to transfer it across the wire.
|
|
266
|
+
const cols = includeMarkdown ? "*" : "route, title, description, headings, keywords, updated_at, is_error, locale";
|
|
267
|
+
// Single page lookup
|
|
268
|
+
if (route) {
|
|
269
|
+
const row = await db.first(`SELECT ${cols} FROM ai_ready_pages WHERE route = ?`, [route]);
|
|
270
|
+
if (!row) return undefined;
|
|
271
|
+
return includeMarkdown ? rowToData(row) : rowToEntry(row);
|
|
272
|
+
}
|
|
273
|
+
// Build query. A deterministic order keeps concurrent runs and offset
|
|
274
|
+
// pagination stable when SQLite would otherwise return rows in scan order.
|
|
275
|
+
const { sql: whereClause, params } = buildWhereClause(where);
|
|
276
|
+
let sql = `SELECT ${cols} FROM ai_ready_pages ${whereClause} ORDER BY route`;
|
|
277
|
+
if (limit) {
|
|
278
|
+
sql += ` LIMIT ?`;
|
|
279
|
+
params.push(limit);
|
|
280
|
+
if (offset) {
|
|
281
|
+
sql += ` OFFSET ?`;
|
|
282
|
+
params.push(offset);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
const rows = await db.all(sql, params);
|
|
286
|
+
return includeMarkdown ? rows.map(rowToData) : rows.map(rowToEntry);
|
|
260
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Stream pages using cursor-based pagination
|
|
290
|
+
* Yields pages one batch at a time to avoid loading all into memory
|
|
291
|
+
*/
|
|
261
292
|
export async function* streamPages(event, options = {}) {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
if (rows.length < batchSize)
|
|
279
|
-
break;
|
|
280
|
-
lastRoute = rows[rows.length - 1].route;
|
|
281
|
-
}
|
|
293
|
+
const db = await getDb(event);
|
|
294
|
+
if (!db) return;
|
|
295
|
+
const batchSize = options.batchSize || 50;
|
|
296
|
+
let lastRoute;
|
|
297
|
+
// Keyset (cursor) pagination on the route index. `OFFSET` re-scans from the
|
|
298
|
+
// start on every page, so it degrades to O(N) across a large table.
|
|
299
|
+
while (true) {
|
|
300
|
+
const where = `WHERE is_error = 0${lastRoute ? " AND route > ?" : ""}`;
|
|
301
|
+
const rows = await db.all(`SELECT * FROM ai_ready_pages ${where} ORDER BY route LIMIT ?`, lastRoute ? [lastRoute, batchSize] : [batchSize]);
|
|
302
|
+
if (rows.length === 0) break;
|
|
303
|
+
for (const row of rows) {
|
|
304
|
+
yield rowToData(row);
|
|
305
|
+
}
|
|
306
|
+
if (rows.length < batchSize) break;
|
|
307
|
+
lastRoute = rows[rows.length - 1].route;
|
|
308
|
+
}
|
|
282
309
|
}
|
|
310
|
+
/**
|
|
311
|
+
* Count pages matching criteria
|
|
312
|
+
*/
|
|
283
313
|
export async function countPages(event, options = {}) {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
`SELECT COUNT(*) as count FROM ai_ready_pages ${whereClause}`,
|
|
290
|
-
params
|
|
291
|
-
);
|
|
292
|
-
return toNumber(row?.count);
|
|
314
|
+
const db = await getDb(event);
|
|
315
|
+
if (!db) return 0;
|
|
316
|
+
const { sql: whereClause, params } = buildWhereClause(options.where);
|
|
317
|
+
const row = await db.first(`SELECT COUNT(*) as count FROM ai_ready_pages ${whereClause}`, params);
|
|
318
|
+
return toNumber(row?.count);
|
|
293
319
|
}
|
|
320
|
+
/**
|
|
321
|
+
* Full-text search using FTS5 or PostgreSQL ILIKE
|
|
322
|
+
* Note: FTS is only available at runtime, not during prerender
|
|
323
|
+
*/
|
|
294
324
|
export async function searchPages(event, query, options = {}) {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
return db.all(`
|
|
325
|
+
// FTS not available in dev or prerender
|
|
326
|
+
if (import.meta.dev || import.meta.prerender) return [];
|
|
327
|
+
const db = await getDb(event);
|
|
328
|
+
if (!db) return [];
|
|
329
|
+
const { limit = 10 } = options;
|
|
330
|
+
// Sanitize and prepare query for FTS5
|
|
331
|
+
const sanitized = query.replace(RE_FTS_CHARS, " ").trim();
|
|
332
|
+
if (!sanitized) return [];
|
|
333
|
+
if (db.dialect === "postgres") {
|
|
334
|
+
const searchTerm = likeSubstring(sanitized);
|
|
335
|
+
return db.all(`
|
|
307
336
|
SELECT route, title, description, 0 AS score
|
|
308
337
|
FROM ai_ready_pages
|
|
309
338
|
WHERE is_error = 0
|
|
310
339
|
AND (title ILIKE ? ESCAPE ? OR description ILIKE ? ESCAPE ? OR markdown ILIKE ? ESCAPE ? OR headings ILIKE ? ESCAPE ?)
|
|
311
340
|
ORDER BY route
|
|
312
341
|
LIMIT ?
|
|
313
|
-
`, [
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
342
|
+
`, [
|
|
343
|
+
searchTerm,
|
|
344
|
+
LIKE_ESCAPE,
|
|
345
|
+
searchTerm,
|
|
346
|
+
LIKE_ESCAPE,
|
|
347
|
+
searchTerm,
|
|
348
|
+
LIKE_ESCAPE,
|
|
349
|
+
searchTerm,
|
|
350
|
+
LIKE_ESCAPE,
|
|
351
|
+
limit
|
|
352
|
+
]);
|
|
353
|
+
}
|
|
354
|
+
const ftsQuery = toFtsMatchQuery(query);
|
|
355
|
+
if (!ftsQuery) return [];
|
|
356
|
+
// BM25 weights: route, title, description, markdown, headings, keywords
|
|
357
|
+
return db.all(`
|
|
319
358
|
SELECT p.route, p.title, p.description, bm25(ai_ready_pages_fts, 5.0, 3.0, 1.0, 0.5, 2.0, 2.0) as score
|
|
320
359
|
FROM ai_ready_pages_fts
|
|
321
360
|
JOIN ai_ready_pages p ON ai_ready_pages_fts.rowid = p.id
|
|
@@ -324,19 +363,27 @@ export async function searchPages(event, query, options = {}) {
|
|
|
324
363
|
LIMIT ?
|
|
325
364
|
`, [ftsQuery, limit]);
|
|
326
365
|
}
|
|
366
|
+
/**
|
|
367
|
+
* Insert or update a page
|
|
368
|
+
*/
|
|
327
369
|
export async function upsertPage(event, page) {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
370
|
+
const db = await getDb(event);
|
|
371
|
+
if (!db) return;
|
|
372
|
+
const route = normalizeRoute(page.route);
|
|
373
|
+
const routeKey = normalizeRouteKey(route);
|
|
374
|
+
const keywordsJson = JSON.stringify(page.keywords);
|
|
375
|
+
const indexedAt = Date.now();
|
|
376
|
+
const source = page.source || "runtime";
|
|
377
|
+
const lastSeenAt = source === "runtime" ? indexedAt : null;
|
|
378
|
+
const locale = deriveLocale(event, route, page.locale);
|
|
379
|
+
// upsertPage never sees the page's own URL, so a locale without an explicit
|
|
380
|
+
// value is derived from the triggering request or site host. Cron and poll
|
|
381
|
+
// requests can arrive on any domain, so a host-derived locale is only a
|
|
382
|
+
// default for new rows: on conflict the stored locale (seeded from each
|
|
383
|
+
// sitemap entry's URL) is never rewritten by the triggering host. Callers
|
|
384
|
+
// that state the locale explicitly remain authoritative.
|
|
385
|
+
const localeTrusted = page.locale !== undefined;
|
|
386
|
+
await db.exec(`
|
|
340
387
|
INSERT INTO ai_ready_pages (route, route_key, title, description, markdown, headings, keywords, content_hash, updated_at, indexed_at, is_error, indexed, source, last_seen_at, locale)
|
|
341
388
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
342
389
|
ON CONFLICT(route) DO UPDATE SET
|
|
@@ -353,73 +400,121 @@ export async function upsertPage(event, page) {
|
|
|
353
400
|
source = excluded.source,
|
|
354
401
|
last_seen_at = excluded.last_seen_at${localeTrusted ? `,
|
|
355
402
|
locale = excluded.locale` : ""}
|
|
356
|
-
`, [
|
|
403
|
+
`, [
|
|
404
|
+
route,
|
|
405
|
+
routeKey,
|
|
406
|
+
page.title,
|
|
407
|
+
page.description,
|
|
408
|
+
page.markdown,
|
|
409
|
+
page.headings,
|
|
410
|
+
keywordsJson,
|
|
411
|
+
page.contentHash || null,
|
|
412
|
+
page.updatedAt,
|
|
413
|
+
indexedAt,
|
|
414
|
+
page.isError ? 1 : 0,
|
|
415
|
+
page.isError ? 0 : 1,
|
|
416
|
+
source,
|
|
417
|
+
lastSeenAt,
|
|
418
|
+
locale
|
|
419
|
+
]);
|
|
357
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* Check if a page is fresh (within TTL)
|
|
423
|
+
*/
|
|
358
424
|
export async function isPageFresh(event, route, ttlSeconds) {
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
return false;
|
|
367
|
-
const age = (Date.now() - toNumber(row.indexed_at)) / 1e3;
|
|
368
|
-
return age < ttlSeconds;
|
|
425
|
+
if (ttlSeconds <= 0) return false;
|
|
426
|
+
const db = await getDb(event);
|
|
427
|
+
if (!db) return false;
|
|
428
|
+
const row = await db.first("SELECT indexed_at FROM ai_ready_pages WHERE route = ?", [route]);
|
|
429
|
+
if (!row) return false;
|
|
430
|
+
const age = (Date.now() - toNumber(row.indexed_at)) / 1e3;
|
|
431
|
+
return age < ttlSeconds;
|
|
369
432
|
}
|
|
433
|
+
/**
|
|
434
|
+
* Fetch a page's index bookkeeping in one lightweight query.
|
|
435
|
+
* Combines the freshness, existence, and prior-hash lookups that the indexing
|
|
436
|
+
* hot path needs into a single indexed row read (avoids `SELECT *` and two
|
|
437
|
+
* extra round-trips per page).
|
|
438
|
+
*/
|
|
370
439
|
export async function getPageIndexState(event, route) {
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
contentHash: row.content_hash,
|
|
381
|
-
updatedAt: row.updated_at || "",
|
|
382
|
-
source: row.source === "runtime" ? "runtime" : "prerender"
|
|
383
|
-
} : void 0;
|
|
440
|
+
const db = await getDb(event);
|
|
441
|
+
if (!db) return undefined;
|
|
442
|
+
const row = await db.first("SELECT indexed_at, content_hash, updated_at, source FROM ai_ready_pages WHERE route = ?", [route]);
|
|
443
|
+
return row ? {
|
|
444
|
+
indexedAt: toNumber(row.indexed_at),
|
|
445
|
+
contentHash: row.content_hash,
|
|
446
|
+
updatedAt: row.updated_at || "",
|
|
447
|
+
source: row.source === "runtime" ? "runtime" : "prerender"
|
|
448
|
+
} : undefined;
|
|
384
449
|
}
|
|
450
|
+
/**
|
|
451
|
+
* Get existing content hash for a page (for change detection)
|
|
452
|
+
* @internal
|
|
453
|
+
*/
|
|
385
454
|
export async function getPageHash(event, route) {
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
return row?.content_hash || null;
|
|
455
|
+
const db = await getDb(event);
|
|
456
|
+
if (!db) return null;
|
|
457
|
+
const row = await db.first("SELECT content_hash FROM ai_ready_pages WHERE route = ?", [route]);
|
|
458
|
+
return row?.content_hash || null;
|
|
391
459
|
}
|
|
460
|
+
// ============================================================================
|
|
461
|
+
// Sitemap Seeding & Pruning
|
|
462
|
+
// ============================================================================
|
|
392
463
|
function chunk(items, size) {
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
return result;
|
|
464
|
+
const result = [];
|
|
465
|
+
for (let i = 0; i < items.length; i += size) result.push(items.slice(i, i + size));
|
|
466
|
+
return result;
|
|
397
467
|
}
|
|
468
|
+
/**
|
|
469
|
+
* Seed routes from sitemap (insert with indexed=0 if not exists)
|
|
470
|
+
*/
|
|
398
471
|
export async function seedRoutes(event, routes, options = {}) {
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
472
|
+
const db = await getDb(event);
|
|
473
|
+
if (!db || routes.length === 0) return 0;
|
|
474
|
+
// Inlined as a literal: a bind param would push a full chunk past D1's
|
|
475
|
+
// 100-parameter cap. Truncating a finite number keeps it injection-safe.
|
|
476
|
+
const refreshWindowMs = Math.max(0, Math.trunc(Number.isFinite(options.refreshWindowMs) ? options.refreshWindowMs : SEED_REFRESH_WINDOW_MS));
|
|
477
|
+
const nowMs = Date.now();
|
|
478
|
+
// Resolve + dedupe rows up front (pure, no IO). Deduping by route avoids
|
|
479
|
+
// SQLite's "ON CONFLICT cannot affect row a second time" error when a
|
|
480
|
+
// multi-row INSERT contains the same route twice.
|
|
481
|
+
const byRoute = new Map();
|
|
482
|
+
for (const entry of routes) {
|
|
483
|
+
// Canonicalise before keying the map: '' and '/' are one page, so leaving
|
|
484
|
+
// them distinct here defeats the dedupe and collides on route_key instead.
|
|
485
|
+
const route = normalizeRoute(typeof entry === "string" ? entry : entry.route);
|
|
486
|
+
const explicitLocale = typeof entry === "string" ? undefined : entry.locale;
|
|
487
|
+
const entryUrl = typeof entry === "string" ? undefined : entry.url;
|
|
488
|
+
byRoute.set(route, {
|
|
489
|
+
route,
|
|
490
|
+
routeKey: normalizeRouteKey(route),
|
|
491
|
+
locale: deriveLocale(event, route, explicitLocale, entryUrl),
|
|
492
|
+
sourceLastmod: parseSourceLastmod(typeof entry === "string" ? undefined : entry.lastmod)
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
// Batch into multi-row INSERTs. Each statement is a DB round-trip (a network
|
|
496
|
+
// call on D1), so one INSERT per route times out large sitemaps. The chunk
|
|
497
|
+
// size is derived from the 5 bind params per row so each statement stays
|
|
498
|
+
// within D1's 100-parameter cap even if a column is added. The statements
|
|
499
|
+
// then go through `db.batch` so all round-trips collapse into one
|
|
500
|
+
// driver-level batch request.
|
|
501
|
+
//
|
|
502
|
+
// The DO UPDATE is guarded so an unchanged row is not rewritten on every
|
|
503
|
+
// crawl. Without the guard each run bumped last_seen_at on every row and
|
|
504
|
+
// its index entries, which cost millions of D1 row writes a month.
|
|
505
|
+
const rowsPerInsert = maxRowsPerInsert(5);
|
|
506
|
+
const stmts = [];
|
|
507
|
+
for (const batch of chunk([...byRoute.values()], rowsPerInsert)) {
|
|
508
|
+
const valuesSql = batch.map(() => `(?, ?, '', '', '', '[]', '[]', '', ?, 0, 0, 0, 'runtime', ?, ?)`).join(", ");
|
|
509
|
+
const params = batch.flatMap((r) => [
|
|
510
|
+
r.route,
|
|
511
|
+
r.routeKey,
|
|
512
|
+
r.sourceLastmod,
|
|
513
|
+
nowMs,
|
|
514
|
+
r.locale
|
|
515
|
+
]);
|
|
516
|
+
stmts.push({
|
|
517
|
+
sql: `
|
|
423
518
|
INSERT INTO ai_ready_pages (route, route_key, title, description, markdown, headings, keywords, updated_at, source_lastmod, indexed_at, is_error, indexed, source, last_seen_at, locale)
|
|
424
519
|
VALUES ${valuesSql}
|
|
425
520
|
ON CONFLICT(route) DO UPDATE SET
|
|
@@ -435,77 +530,81 @@ export async function seedRoutes(event, routes, options = {}) {
|
|
|
435
530
|
OR ai_ready_pages.locale IS DISTINCT FROM excluded.locale
|
|
436
531
|
OR (excluded.source_lastmod IS NOT NULL AND ai_ready_pages.source_lastmod IS DISTINCT FROM excluded.source_lastmod)
|
|
437
532
|
`,
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
533
|
+
params
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
await db.batch(stmts);
|
|
537
|
+
return byRoute.size;
|
|
443
538
|
}
|
|
539
|
+
/** Remove a page after its route returns HTTP 410. */
|
|
444
540
|
export async function prunePage(event, route) {
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
await db.exec("DELETE FROM ai_ready_pages WHERE route = ?", [normalizeRoute(route)]);
|
|
541
|
+
const db = await getDb(event);
|
|
542
|
+
if (!db) return;
|
|
543
|
+
await db.exec("DELETE FROM ai_ready_pages WHERE route = ?", [normalizeRoute(route)]);
|
|
449
544
|
}
|
|
545
|
+
/**
|
|
546
|
+
* Prune routes not seen in sitemap for longer than threshold
|
|
547
|
+
* Only prunes routes with source='runtime' (never prerendered pages)
|
|
548
|
+
*
|
|
549
|
+
* `seedRoutes` lets `last_seen_at` lag a sighting by up to `refreshWindowMs`,
|
|
550
|
+
* so the threshold moves back by that window. A live route is then never
|
|
551
|
+
* pruned. Pass the window the seeder used; the default is the largest one.
|
|
552
|
+
*/
|
|
450
553
|
export async function pruneStaleRoutes(event, staleThresholdSeconds, protectedSince, refreshWindowMs = SEED_REFRESH_WINDOW_MS) {
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
if (count > 0) {
|
|
462
|
-
await db.exec("DELETE FROM ai_ready_pages WHERE source = ? AND last_seen_at < ?", ["runtime", threshold]);
|
|
463
|
-
}
|
|
464
|
-
return count;
|
|
554
|
+
const db = await getDb(event);
|
|
555
|
+
if (!db) return 0;
|
|
556
|
+
const staleThreshold = Date.now() - staleThresholdSeconds * 1e3;
|
|
557
|
+
const threshold = (protectedSince === undefined ? staleThreshold : Math.min(staleThreshold, protectedSince)) - refreshWindowMs;
|
|
558
|
+
const countRow = await db.first("SELECT COUNT(*) as count FROM ai_ready_pages WHERE source = ? AND last_seen_at < ?", ["runtime", threshold]);
|
|
559
|
+
const count = toNumber(countRow?.count);
|
|
560
|
+
if (count > 0) {
|
|
561
|
+
await db.exec("DELETE FROM ai_ready_pages WHERE source = ? AND last_seen_at < ?", ["runtime", threshold]);
|
|
562
|
+
}
|
|
563
|
+
return count;
|
|
465
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* Get stale routes that would be pruned (for preview)
|
|
567
|
+
*/
|
|
466
568
|
export async function getStaleRoutes(event, staleThresholdSeconds, refreshWindowMs = SEED_REFRESH_WINDOW_MS) {
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
"SELECT route FROM ai_ready_pages WHERE source = ? AND last_seen_at < ?",
|
|
473
|
-
["runtime", threshold]
|
|
474
|
-
);
|
|
475
|
-
return rows.map((r) => r.route);
|
|
569
|
+
const db = await getDb(event);
|
|
570
|
+
if (!db) return [];
|
|
571
|
+
const threshold = Date.now() - staleThresholdSeconds * 1e3 - refreshWindowMs;
|
|
572
|
+
const rows = await db.all("SELECT route FROM ai_ready_pages WHERE source = ? AND last_seen_at < ?", ["runtime", threshold]);
|
|
573
|
+
return rows.map((r) => r.route);
|
|
476
574
|
}
|
|
477
575
|
function rowToCronRun(row) {
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
576
|
+
return {
|
|
577
|
+
id: row.id,
|
|
578
|
+
startedAt: toNumber(row.started_at),
|
|
579
|
+
finishedAt: toNullableNumber(row.finished_at),
|
|
580
|
+
durationMs: toNullableNumber(row.duration_ms),
|
|
581
|
+
pagesIndexed: toNumber(row.pages_indexed),
|
|
582
|
+
pagesRemaining: toNumber(row.pages_remaining),
|
|
583
|
+
errors: safeJsonParse(row.errors, []),
|
|
584
|
+
status: row.status
|
|
585
|
+
};
|
|
488
586
|
}
|
|
587
|
+
/**
|
|
588
|
+
* Start a cron run and return its ID
|
|
589
|
+
*/
|
|
489
590
|
export async function startCronRun(event) {
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
"INSERT INTO ai_ready_cron_runs (started_at, status) VALUES (?, ?) RETURNING id",
|
|
496
|
-
[now, "running"]
|
|
497
|
-
);
|
|
498
|
-
return row ? toNumber(row.id) : null;
|
|
591
|
+
const db = await getDb(event);
|
|
592
|
+
if (!db) return null;
|
|
593
|
+
const now = Date.now();
|
|
594
|
+
const row = await db.first("INSERT INTO ai_ready_cron_runs (started_at, status) VALUES (?, ?) RETURNING id", [now, "running"]);
|
|
595
|
+
return row ? toNumber(row.id) : null;
|
|
499
596
|
}
|
|
597
|
+
/**
|
|
598
|
+
* Complete a cron run with results
|
|
599
|
+
*/
|
|
500
600
|
export async function completeCronRun(event, runId, result) {
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
await db.exec(`
|
|
601
|
+
const db = await getDb(event);
|
|
602
|
+
if (!db) return;
|
|
603
|
+
const now = Date.now();
|
|
604
|
+
const row = await db.first("SELECT started_at FROM ai_ready_cron_runs WHERE id = ?", [runId]);
|
|
605
|
+
const durationMs = row ? now - toNumber(row.started_at) : null;
|
|
606
|
+
const status = result.errors.length > 0 ? result.pagesIndexed > 0 ? "partial" : "error" : "success";
|
|
607
|
+
await db.exec(`
|
|
509
608
|
UPDATE ai_ready_cron_runs SET
|
|
510
609
|
finished_at = ?,
|
|
511
610
|
duration_ms = ?,
|
|
@@ -514,39 +613,48 @@ export async function completeCronRun(event, runId, result) {
|
|
|
514
613
|
errors = ?,
|
|
515
614
|
status = ?
|
|
516
615
|
WHERE id = ?
|
|
517
|
-
`, [
|
|
616
|
+
`, [
|
|
617
|
+
now,
|
|
618
|
+
durationMs,
|
|
619
|
+
result.pagesIndexed,
|
|
620
|
+
result.pagesRemaining,
|
|
621
|
+
JSON.stringify(result.errors),
|
|
622
|
+
status,
|
|
623
|
+
runId
|
|
624
|
+
]);
|
|
518
625
|
}
|
|
626
|
+
/**
|
|
627
|
+
* Get recent cron runs
|
|
628
|
+
*/
|
|
519
629
|
export async function getRecentCronRuns(event, limit = 10) {
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
"SELECT * FROM ai_ready_cron_runs ORDER BY started_at DESC LIMIT ?",
|
|
525
|
-
[limit]
|
|
526
|
-
);
|
|
527
|
-
return rows.map(rowToCronRun);
|
|
630
|
+
const db = await getDb(event);
|
|
631
|
+
if (!db) return [];
|
|
632
|
+
const rows = await db.all("SELECT * FROM ai_ready_cron_runs ORDER BY started_at DESC LIMIT ?", [limit]);
|
|
633
|
+
return rows.map(rowToCronRun);
|
|
528
634
|
}
|
|
635
|
+
/**
|
|
636
|
+
* Clean up cron runs older than specified age
|
|
637
|
+
*/
|
|
529
638
|
export async function pruneCronRunsByAge(event, maxAgeMs = 24 * 60 * 60 * 1e3) {
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
if (count > 0) {
|
|
540
|
-
await db.exec("DELETE FROM ai_ready_cron_runs WHERE started_at < ?", [threshold]);
|
|
541
|
-
}
|
|
542
|
-
return count;
|
|
639
|
+
const db = await getDb(event);
|
|
640
|
+
if (!db) return 0;
|
|
641
|
+
const threshold = Date.now() - maxAgeMs;
|
|
642
|
+
const countRow = await db.first("SELECT COUNT(*) as count FROM ai_ready_cron_runs WHERE started_at < ?", [threshold]);
|
|
643
|
+
const count = toNumber(countRow?.count);
|
|
644
|
+
if (count > 0) {
|
|
645
|
+
await db.exec("DELETE FROM ai_ready_cron_runs WHERE started_at < ?", [threshold]);
|
|
646
|
+
}
|
|
647
|
+
return count;
|
|
543
648
|
}
|
|
649
|
+
/**
|
|
650
|
+
* Get all cron status in a single query for fast-path checking
|
|
651
|
+
* Reduces 6+ sequential DB calls to 1
|
|
652
|
+
*/
|
|
544
653
|
export async function getCronFastPathStatus(event, sitemapIntervalMinutes = 5) {
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
const row = await db.first(`
|
|
654
|
+
const db = await getDb(event);
|
|
655
|
+
if (!db) return null;
|
|
656
|
+
const sitemapThreshold = Date.now() - sitemapIntervalMinutes * 60 * 1e3;
|
|
657
|
+
const row = await db.first(`
|
|
550
658
|
SELECT
|
|
551
659
|
(SELECT COUNT(*) FROM ai_ready_pages) as total_pages,
|
|
552
660
|
(SELECT COUNT(*) FROM ai_ready_pages WHERE indexed = 0 AND is_error = 0) as pending_pages,
|
|
@@ -554,118 +662,173 @@ export async function getCronFastPathStatus(event, sitemapIntervalMinutes = 5) {
|
|
|
554
662
|
(SELECT value FROM _ai_ready_info WHERE id = 'build_id') as build_id,
|
|
555
663
|
(SELECT COUNT(*) FROM ai_ready_sitemaps WHERE (crawl_state IS NOT NULL OR last_crawled_at IS NULL OR last_crawled_at < ?) AND error_count < 10) as sitemaps_need_crawl
|
|
556
664
|
`, [sitemapThreshold]);
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
};
|
|
665
|
+
if (!row) return null;
|
|
666
|
+
return {
|
|
667
|
+
totalPages: toNumber(row.total_pages),
|
|
668
|
+
pendingPages: toNumber(row.pending_pages),
|
|
669
|
+
lastStaleCheck: row.last_stale_check ? Number.parseInt(row.last_stale_check, 10) : null,
|
|
670
|
+
buildId: row.build_id,
|
|
671
|
+
sitemapsNeedCrawl: toNumber(row.sitemaps_need_crawl)
|
|
672
|
+
};
|
|
566
673
|
}
|
|
674
|
+
// ============================================================================
|
|
675
|
+
// Cron Lock (prevent overlapping runs)
|
|
676
|
+
// ============================================================================
|
|
567
677
|
const CRON_LOCK_TTL_MS = 3e5;
|
|
568
678
|
function cronLockField(db, column, key) {
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
return `CASE WHEN jsonb_typeof(${jsonb}) = 'object' THEN (${jsonb} ->> '${key}') END`;
|
|
679
|
+
if (db.dialect !== "postgres") return `json_extract(${column}, '$.${key}')`;
|
|
680
|
+
const jsonb = `${column}::jsonb`;
|
|
681
|
+
return `CASE WHEN jsonb_typeof(${jsonb}) = 'object' THEN (${jsonb} ->> '${key}') END`;
|
|
573
682
|
}
|
|
683
|
+
/**
|
|
684
|
+
* Try to acquire cron lock. Returns the ownership token on success, `held`
|
|
685
|
+
* when a live lock belongs to another run.
|
|
686
|
+
*
|
|
687
|
+
* The value carries a random token plus expiry in one row, so the
|
|
688
|
+
* compare-expired-then-set upsert is atomic and ownership is unique even for
|
|
689
|
+
* two isolates that start in the same millisecond. A legacy value that
|
|
690
|
+
* predates tokens parses as no expiry, so it is treated as expired.
|
|
691
|
+
*/
|
|
574
692
|
export async function tryAcquireCronLock(event) {
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
693
|
+
const token = crypto.randomUUID();
|
|
694
|
+
const db = await getDb(event);
|
|
695
|
+
if (!db) return {
|
|
696
|
+
_tag: "acquired",
|
|
697
|
+
token
|
|
698
|
+
};
|
|
699
|
+
const now = Date.now();
|
|
700
|
+
const value = JSON.stringify({
|
|
701
|
+
t: token,
|
|
702
|
+
a: now,
|
|
703
|
+
e: now + CRON_LOCK_TTL_MS
|
|
704
|
+
});
|
|
705
|
+
try {
|
|
706
|
+
await db.exec(`
|
|
583
707
|
INSERT INTO _ai_ready_info (id, value) VALUES ('cron_lock', ?)
|
|
584
708
|
ON CONFLICT(id) DO UPDATE SET value = excluded.value
|
|
585
709
|
WHERE CAST(coalesce(${cronLockField(db, "_ai_ready_info.value", "e")}, '0') AS BIGINT) < ?
|
|
586
710
|
`, [value, now]);
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
711
|
+
const row = await db.first(`SELECT value FROM _ai_ready_info WHERE id = 'cron_lock' AND ${cronLockField(db, "value", "t")} = ?`, [token]);
|
|
712
|
+
return row ? {
|
|
713
|
+
_tag: "acquired",
|
|
714
|
+
token
|
|
715
|
+
} : { _tag: "held" };
|
|
716
|
+
} catch (error) {
|
|
717
|
+
// The upsert may have landed before the verify read failed, leaving a
|
|
718
|
+
// live lock no caller can release: they never see the token. Clear it
|
|
719
|
+
// best-effort, then surface the original error. Release is a no-op when
|
|
720
|
+
// the row is absent or owned by another run.
|
|
721
|
+
await releaseCronLock(event, token).catch(() => {
|
|
722
|
+
// Ignorable: the lock still expires after CRON_LOCK_TTL_MS, and the
|
|
723
|
+
// original acquire error is what the caller needs to see.
|
|
724
|
+
});
|
|
725
|
+
throw error;
|
|
726
|
+
}
|
|
597
727
|
}
|
|
728
|
+
/**
|
|
729
|
+
* Release cron lock. Only deletes the row when its token is ours, so a run
|
|
730
|
+
* that outlived the lock TTL cannot delete the new owner's lock.
|
|
731
|
+
*/
|
|
598
732
|
export async function releaseCronLock(event, token) {
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
await db.exec(`DELETE FROM _ai_ready_info WHERE id = 'cron_lock' AND ${cronLockField(db, "value", "t")} = ?`, [token]);
|
|
733
|
+
const db = await getDb(event);
|
|
734
|
+
if (!db) return;
|
|
735
|
+
await db.exec(`DELETE FROM _ai_ready_info WHERE id = 'cron_lock' AND ${cronLockField(db, "value", "t")} = ?`, [token]);
|
|
603
736
|
}
|
|
604
737
|
const RE_CRON_LOCK_NUMERIC = /^\d+$/;
|
|
605
738
|
function parseCronLockValue(value) {
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
739
|
+
if (RE_CRON_LOCK_NUMERIC.test(value)) {
|
|
740
|
+
return {
|
|
741
|
+
acquiredAt: Number(value),
|
|
742
|
+
expiresAt: Number(value) + CRON_LOCK_TTL_MS
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
const parsed = safeJsonParse(value, null);
|
|
746
|
+
if (parsed && typeof parsed === "object" && typeof parsed.a === "number" && typeof parsed.e === "number") return {
|
|
747
|
+
acquiredAt: parsed.a,
|
|
748
|
+
expiresAt: parsed.e
|
|
749
|
+
};
|
|
750
|
+
return null;
|
|
612
751
|
}
|
|
752
|
+
/**
|
|
753
|
+
* Get cron lock status for status endpoint
|
|
754
|
+
*/
|
|
613
755
|
export async function getCronLockStatus(event) {
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
756
|
+
const db = await getDb(event);
|
|
757
|
+
if (!db) {
|
|
758
|
+
return {
|
|
759
|
+
held: false,
|
|
760
|
+
since: null,
|
|
761
|
+
elapsedMs: null,
|
|
762
|
+
stale: false
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
const row = await db.first("SELECT value FROM _ai_ready_info WHERE id = ?", ["cron_lock"]);
|
|
766
|
+
if (!row) {
|
|
767
|
+
return {
|
|
768
|
+
held: false,
|
|
769
|
+
since: null,
|
|
770
|
+
elapsedMs: null,
|
|
771
|
+
stale: false
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
const record = parseCronLockValue(row.value);
|
|
775
|
+
if (!record) {
|
|
776
|
+
return {
|
|
777
|
+
held: false,
|
|
778
|
+
since: null,
|
|
779
|
+
elapsedMs: null,
|
|
780
|
+
stale: false
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
const now = Date.now();
|
|
784
|
+
const stale = now >= record.expiresAt;
|
|
785
|
+
return {
|
|
786
|
+
held: !stale,
|
|
787
|
+
since: record.acquiredAt,
|
|
788
|
+
elapsedMs: now - record.acquiredAt,
|
|
789
|
+
stale
|
|
790
|
+
};
|
|
634
791
|
}
|
|
635
792
|
function rowToSitemapEntry(row) {
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
};
|
|
793
|
+
const parsedState = parseSitemapCrawlState(row.crawl_state);
|
|
794
|
+
if (parsedState._tag === "error") throw new Error(`Invalid crawl state for sitemap ${row.name}: ${parsedState.error}`);
|
|
795
|
+
return {
|
|
796
|
+
name: row.name,
|
|
797
|
+
route: row.route,
|
|
798
|
+
lastCrawledAt: toNullableNumber(row.last_crawled_at),
|
|
799
|
+
urlCount: toNumber(row.url_count),
|
|
800
|
+
errorCount: toNumber(row.error_count),
|
|
801
|
+
lastError: row.last_error,
|
|
802
|
+
crawlState: parsedState.state
|
|
803
|
+
};
|
|
648
804
|
}
|
|
805
|
+
/**
|
|
806
|
+
* Sync sitemap list from config to DB
|
|
807
|
+
* Inserts new sitemaps, removes stale ones
|
|
808
|
+
*/
|
|
649
809
|
export async function syncSitemaps(event, sitemaps) {
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
810
|
+
const db = await getDb(event);
|
|
811
|
+
if (!db) return {
|
|
812
|
+
added: 0,
|
|
813
|
+
removed: 0
|
|
814
|
+
};
|
|
815
|
+
const existingRows = await db.all("SELECT name, route FROM ai_ready_sitemaps");
|
|
816
|
+
const existingNames = new Set(existingRows.map((r) => r.name));
|
|
817
|
+
const existingRoutes = new Map(existingRows.map((row) => [row.name, row.route]));
|
|
818
|
+
const configNames = new Set(sitemaps.map((s) => s.name));
|
|
819
|
+
let added = 0;
|
|
820
|
+
let removed = 0;
|
|
821
|
+
const stmts = [];
|
|
822
|
+
// Insert new sitemaps
|
|
823
|
+
for (const sitemap of sitemaps) {
|
|
824
|
+
if (!existingNames.has(sitemap.name)) {
|
|
825
|
+
stmts.push({
|
|
826
|
+
sql: "INSERT INTO ai_ready_sitemaps (name, route) VALUES (?, ?)",
|
|
827
|
+
params: [sitemap.name, sitemap.route]
|
|
828
|
+
});
|
|
829
|
+
added++;
|
|
830
|
+
} else if (existingRoutes.get(sitemap.name) !== sitemap.route) {
|
|
831
|
+
await db.exec(`
|
|
669
832
|
UPDATE ai_ready_sitemaps SET
|
|
670
833
|
route = ?,
|
|
671
834
|
last_crawled_at = NULL,
|
|
@@ -675,66 +838,82 @@ export async function syncSitemaps(event, sitemaps) {
|
|
|
675
838
|
crawl_state = NULL
|
|
676
839
|
WHERE name = ?
|
|
677
840
|
`, [sitemap.route, sitemap.name]);
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
// Remove sitemaps no longer in config
|
|
844
|
+
for (const name of existingNames) {
|
|
845
|
+
if (!configNames.has(name)) {
|
|
846
|
+
stmts.push({
|
|
847
|
+
sql: "DELETE FROM ai_ready_sitemaps WHERE name = ?",
|
|
848
|
+
params: [name]
|
|
849
|
+
});
|
|
850
|
+
removed++;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
await db.batch(stmts);
|
|
854
|
+
return {
|
|
855
|
+
added,
|
|
856
|
+
removed
|
|
857
|
+
};
|
|
691
858
|
}
|
|
859
|
+
/**
|
|
860
|
+
* Get next sitemap to crawl
|
|
861
|
+
* Prioritizes: in-progress continuations, errors, then oldest crawled
|
|
862
|
+
* Skips sitemaps crawled within minIntervalMinutes (default 5 min)
|
|
863
|
+
*/
|
|
692
864
|
export async function getNextSitemapToCrawl(event, minIntervalMinutes = 5) {
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
865
|
+
const db = await getDb(event);
|
|
866
|
+
if (!db) return null;
|
|
867
|
+
// Calculate threshold as milliseconds timestamp (matching how we store last_crawled_at)
|
|
868
|
+
const threshold = Date.now() - minIntervalMinutes * 60 * 1e3;
|
|
869
|
+
// Continuations bypass the normal recrawl interval. They are already bounded
|
|
870
|
+
// to one round per cron run, and delaying them could allow pruning against an
|
|
871
|
+
// incomplete traversal.
|
|
872
|
+
const continuationRow = await db.first(`
|
|
698
873
|
SELECT * FROM ai_ready_sitemaps
|
|
699
874
|
WHERE crawl_state IS NOT NULL AND error_count = 0
|
|
700
875
|
ORDER BY last_crawled_at ASC NULLS FIRST
|
|
701
876
|
LIMIT 1
|
|
702
877
|
`);
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
878
|
+
if (continuationRow) return rowToSitemapEntry(continuationRow);
|
|
879
|
+
// First try sitemaps with errors (retry after interval)
|
|
880
|
+
// Only retry if error_count < 10 to avoid infinite retries
|
|
881
|
+
const errorRow = await db.first(`
|
|
706
882
|
SELECT * FROM ai_ready_sitemaps
|
|
707
883
|
WHERE error_count > 0 AND error_count < 10
|
|
708
884
|
AND (last_crawled_at IS NULL OR last_crawled_at < ?)
|
|
709
885
|
ORDER BY last_crawled_at ASC NULLS FIRST
|
|
710
886
|
LIMIT 1
|
|
711
887
|
`, [threshold]);
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
888
|
+
if (errorRow) return rowToSitemapEntry(errorRow);
|
|
889
|
+
// Otherwise get oldest crawled (or never crawled) outside interval
|
|
890
|
+
const row = await db.first(`
|
|
715
891
|
SELECT * FROM ai_ready_sitemaps
|
|
716
892
|
WHERE error_count = 0
|
|
717
893
|
AND (last_crawled_at IS NULL OR last_crawled_at < ?)
|
|
718
894
|
ORDER BY last_crawled_at ASC NULLS FIRST
|
|
719
895
|
LIMIT 1
|
|
720
896
|
`, [threshold]);
|
|
721
|
-
|
|
897
|
+
return row ? rowToSitemapEntry(row) : null;
|
|
722
898
|
}
|
|
899
|
+
/**
|
|
900
|
+
* Get the last crawl timestamp for a single sitemap. Used to throttle runtime
|
|
901
|
+
* re-seeding (the sitemap:resolved hook fires on every sitemap request).
|
|
902
|
+
* Returns null when the sitemap row doesn't exist yet.
|
|
903
|
+
*/
|
|
723
904
|
export async function getSitemapLastCrawledAt(event, name) {
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
"SELECT last_crawled_at FROM ai_ready_sitemaps WHERE name = ?",
|
|
729
|
-
[name]
|
|
730
|
-
);
|
|
731
|
-
return toNullableNumber(row?.last_crawled_at);
|
|
905
|
+
const db = await getDb(event);
|
|
906
|
+
if (!db) return null;
|
|
907
|
+
const row = await db.first("SELECT last_crawled_at FROM ai_ready_sitemaps WHERE name = ?", [name]);
|
|
908
|
+
return toNullableNumber(row?.last_crawled_at);
|
|
732
909
|
}
|
|
910
|
+
/**
|
|
911
|
+
* Mark sitemap as successfully crawled
|
|
912
|
+
*/
|
|
733
913
|
export async function markSitemapCrawled(event, name, urlCount) {
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
await db.exec(`
|
|
914
|
+
const db = await getDb(event);
|
|
915
|
+
if (!db) return;
|
|
916
|
+
await db.exec(`
|
|
738
917
|
UPDATE ai_ready_sitemaps SET
|
|
739
918
|
last_crawled_at = ?,
|
|
740
919
|
url_count = ?,
|
|
@@ -742,15 +921,22 @@ export async function markSitemapCrawled(event, name, urlCount) {
|
|
|
742
921
|
last_error = NULL,
|
|
743
922
|
crawl_state = NULL
|
|
744
923
|
WHERE name = ?
|
|
745
|
-
`, [
|
|
924
|
+
`, [
|
|
925
|
+
Date.now(),
|
|
926
|
+
urlCount,
|
|
927
|
+
name
|
|
928
|
+
]);
|
|
746
929
|
}
|
|
930
|
+
/**
|
|
931
|
+
* Record a sitemap:resolved hook seed only while no durable crawl is active.
|
|
932
|
+
* The hook may finish in waitUntil after cron has persisted a continuation.
|
|
933
|
+
*/
|
|
747
934
|
export async function markSitemapSeeded(event, name, urlCount, expectedLastCrawledAt) {
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
await db.exec(`
|
|
935
|
+
const db = await getDb(event);
|
|
936
|
+
if (!db) return;
|
|
937
|
+
const expectedClause = expectedLastCrawledAt === null ? "last_crawled_at IS NULL" : "last_crawled_at = ?";
|
|
938
|
+
const expectedParams = expectedLastCrawledAt === null ? [] : [expectedLastCrawledAt];
|
|
939
|
+
await db.exec(`
|
|
754
940
|
UPDATE ai_ready_sitemaps SET
|
|
755
941
|
last_crawled_at = ?,
|
|
756
942
|
url_count = ?,
|
|
@@ -760,13 +946,18 @@ export async function markSitemapSeeded(event, name, urlCount, expectedLastCrawl
|
|
|
760
946
|
AND crawl_state IS NULL
|
|
761
947
|
AND error_count = 0
|
|
762
948
|
AND ${expectedClause}
|
|
763
|
-
`, [
|
|
949
|
+
`, [
|
|
950
|
+
Date.now(),
|
|
951
|
+
urlCount,
|
|
952
|
+
name,
|
|
953
|
+
...expectedParams
|
|
954
|
+
]);
|
|
764
955
|
}
|
|
956
|
+
/** Persist a resumable sitemap crawl without incrementing its error budget. */
|
|
765
957
|
export async function markSitemapCrawlPartial(event, name, state) {
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
await db.exec(`
|
|
958
|
+
const db = await getDb(event);
|
|
959
|
+
if (!db) return;
|
|
960
|
+
await db.exec(`
|
|
770
961
|
UPDATE ai_ready_sitemaps SET
|
|
771
962
|
last_crawled_at = ?,
|
|
772
963
|
url_count = ?,
|
|
@@ -774,62 +965,80 @@ export async function markSitemapCrawlPartial(event, name, state) {
|
|
|
774
965
|
last_error = NULL,
|
|
775
966
|
crawl_state = ?
|
|
776
967
|
WHERE name = ?
|
|
777
|
-
`, [
|
|
968
|
+
`, [
|
|
969
|
+
Date.now(),
|
|
970
|
+
state.urlsObserved,
|
|
971
|
+
serializeSitemapCrawlState(state),
|
|
972
|
+
name
|
|
973
|
+
]);
|
|
778
974
|
}
|
|
975
|
+
/**
|
|
976
|
+
* Mark sitemap crawl as failed
|
|
977
|
+
*/
|
|
779
978
|
export async function markSitemapError(event, name, error) {
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
await db.exec(`
|
|
979
|
+
const db = await getDb(event);
|
|
980
|
+
if (!db) return;
|
|
981
|
+
await db.exec(`
|
|
784
982
|
UPDATE ai_ready_sitemaps SET
|
|
785
983
|
last_crawled_at = ?,
|
|
786
984
|
error_count = error_count + 1,
|
|
787
985
|
last_error = ?,
|
|
788
986
|
crawl_state = NULL
|
|
789
987
|
WHERE name = ?
|
|
790
|
-
`, [
|
|
988
|
+
`, [
|
|
989
|
+
Date.now(),
|
|
990
|
+
error,
|
|
991
|
+
name
|
|
992
|
+
]);
|
|
791
993
|
}
|
|
994
|
+
/**
|
|
995
|
+
* Reset all sitemap errors (called on build_id change)
|
|
996
|
+
*/
|
|
792
997
|
export async function resetSitemapErrors(event) {
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
await db.exec("UPDATE ai_ready_sitemaps SET error_count = 0, last_error = NULL, last_crawled_at = NULL, crawl_state = NULL");
|
|
802
|
-
}
|
|
803
|
-
return count;
|
|
998
|
+
const db = await getDb(event);
|
|
999
|
+
if (!db) return 0;
|
|
1000
|
+
const countRow = await db.first("SELECT COUNT(*) as count FROM ai_ready_sitemaps WHERE error_count > 0 OR crawl_state IS NOT NULL");
|
|
1001
|
+
const count = toNumber(countRow?.count);
|
|
1002
|
+
if (count > 0) {
|
|
1003
|
+
await db.exec("UPDATE ai_ready_sitemaps SET error_count = 0, last_error = NULL, last_crawled_at = NULL, crawl_state = NULL");
|
|
1004
|
+
}
|
|
1005
|
+
return count;
|
|
804
1006
|
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Get all sitemaps with their status
|
|
1009
|
+
*/
|
|
805
1010
|
export async function getSitemapStatus(event) {
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
1011
|
+
const db = await getDb(event);
|
|
1012
|
+
if (!db) return [];
|
|
1013
|
+
const rows = await db.all("SELECT * FROM ai_ready_sitemaps ORDER BY name");
|
|
1014
|
+
return rows.map((row) => {
|
|
1015
|
+
const { crawlState, ...entry } = rowToSitemapEntry(row);
|
|
1016
|
+
return {
|
|
1017
|
+
...entry,
|
|
1018
|
+
continuing: crawlState !== null
|
|
1019
|
+
};
|
|
1020
|
+
});
|
|
814
1021
|
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Get recently indexed pages
|
|
1024
|
+
*/
|
|
815
1025
|
export async function getRecentlyIndexedPages(event, limit = 10) {
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
1026
|
+
const db = await getDb(event);
|
|
1027
|
+
if (!db) return [];
|
|
1028
|
+
const rows = await db.all("SELECT route, title, indexed_at FROM ai_ready_pages WHERE indexed = 1 AND is_error = 0 ORDER BY indexed_at DESC LIMIT ?", [limit]);
|
|
1029
|
+
return rows.map((r) => ({
|
|
1030
|
+
route: r.route,
|
|
1031
|
+
title: r.title,
|
|
1032
|
+
indexedAt: toNumber(r.indexed_at)
|
|
1033
|
+
}));
|
|
824
1034
|
}
|
|
1035
|
+
/**
|
|
1036
|
+
* Count pages indexed in a time window
|
|
1037
|
+
*/
|
|
825
1038
|
export async function countRecentlyIndexed(event, sinceMs) {
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
"SELECT COUNT(*) as count FROM ai_ready_pages WHERE indexed = 1 AND indexed_at > ?",
|
|
832
|
-
[threshold]
|
|
833
|
-
);
|
|
834
|
-
return toNumber(row?.count);
|
|
1039
|
+
const db = await getDb(event);
|
|
1040
|
+
if (!db) return 0;
|
|
1041
|
+
const threshold = Date.now() - sinceMs;
|
|
1042
|
+
const row = await db.first("SELECT COUNT(*) as count FROM ai_ready_pages WHERE indexed = 1 AND indexed_at > ?", [threshold]);
|
|
1043
|
+
return toNumber(row?.count);
|
|
835
1044
|
}
|