|
8 | 8 | import { json } from '@sveltejs/kit'; |
9 | 9 | import { SEO_TARGETS } from '$lib/seo-targets.js'; |
10 | 10 | import { |
11 | | - healthQueries, |
12 | | - targetPerformanceQuery, |
13 | | - sitewideQueries, |
14 | | - analyseTarget, |
15 | | - checkRateLimit, |
16 | | - rateLimitHeaders, |
17 | | - type DataHealth, |
18 | | - type QueryRow, |
19 | | - type TargetResult, |
20 | | - type SitewideQuery, |
21 | | - type SitewidePage, |
22 | | - type ContentGap, |
23 | | - type Search404, |
24 | | - type SeoAction |
| 11 | + healthQueries, |
| 12 | + targetPerformanceQuery, |
| 13 | + sitewideQueries, |
| 14 | + analyseTarget, |
| 15 | + checkRateLimit, |
| 16 | + rateLimitHeaders, |
| 17 | + type DataHealth, |
| 18 | + type QueryRow, |
| 19 | + type TargetResult, |
| 20 | + type SitewideQuery, |
| 21 | + type SitewidePage, |
| 22 | + type ContentGap, |
| 23 | + type Search404, |
| 24 | + type SeoAction |
25 | 25 | } from '@esolia/core/seo'; |
26 | 26 | import type { RequestHandler } from './$types.js'; |
27 | 27 |
|
28 | 28 | // ── Helpers ──────────────────────────────────────────────────────── |
29 | 29 |
|
30 | 30 | function getDb(platform: App.Platform | undefined): D1Database | undefined { |
31 | | - // InfoSec: Cloudflare adapter Proxy throws (not returns undefined) during |
32 | | - // prerendering / local dev without D1. Wrap in try-catch. |
33 | | - try { |
34 | | - return platform?.env?.SEARCH_INTEL_DB; |
35 | | - } catch { |
36 | | - return undefined; |
37 | | - } |
| 31 | + // InfoSec: Cloudflare adapter Proxy throws (not returns undefined) during |
| 32 | + // prerendering / local dev without D1. Wrap in try-catch. |
| 33 | + try { |
| 34 | + return platform?.env?.SEARCH_INTEL_DB; |
| 35 | + } catch { |
| 36 | + return undefined; |
| 37 | + } |
38 | 38 | } |
39 | 39 |
|
40 | 40 | // ── Handler ──────────────────────────────────────────────────────── |
41 | 41 |
|
42 | 42 | export const GET: RequestHandler = async ({ platform, getClientAddress }) => { |
43 | | - // InfoSec: Application-level rate limiting (defense-in-depth behind WAF rules) |
44 | | - const rl = await checkRateLimit(platform?.env?.CACHE_KV, `seo-dash:${getClientAddress()}`, { |
45 | | - limit: 10, |
46 | | - window: 60 |
47 | | - }); |
48 | | - if (!rl.allowed) { |
49 | | - return json( |
50 | | - { error: 'Rate limit exceeded. Try again later.' }, |
51 | | - { status: 429, headers: { 'Cache-Control': 'no-store', ...rateLimitHeaders(rl, 10) } } |
52 | | - ); |
53 | | - } |
54 | | - |
55 | | - const db = getDb(platform); |
56 | | - |
57 | | - if (!db) { |
58 | | - return json( |
59 | | - { |
60 | | - error: 'D1 database unavailable', |
61 | | - hint: 'SEARCH_INTEL_DB binding not found. This endpoint requires Cloudflare Workers with D1.' |
62 | | - }, |
63 | | - { |
64 | | - status: 503, |
65 | | - headers: { 'Cache-Control': 'no-store' } |
66 | | - } |
67 | | - ); |
68 | | - } |
69 | | - |
70 | | - try { |
71 | | - // ── Data health (single batch) ───────────────────────────── |
72 | | - const healthStmts = healthQueries().map((q) => db.prepare(q.sql).bind(...q.params)); |
73 | | - const healthResults = await db.batch(healthStmts); |
74 | | - |
75 | | - const row0 = healthResults[0]?.results[0] as { cnt: number } | undefined; |
76 | | - const row1 = healthResults[1]?.results[0] as |
77 | | - | { earliest: string | null; latest: string | null } |
78 | | - | undefined; |
79 | | - const row2 = healthResults[2]?.results[0] as { cnt: number } | undefined; |
80 | | - const row3 = healthResults[3]?.results[0] as { cnt: number } | undefined; |
81 | | - const row4 = healthResults[4]?.results[0] as { cnt: number } | undefined; |
82 | | - |
83 | | - const dataHealth: DataHealth = { |
84 | | - totalRows: row0?.cnt ?? 0, |
85 | | - earliest: row1?.earliest ?? null, |
86 | | - latest: row1?.latest ?? null, |
87 | | - uniqueQueries: row2?.cnt ?? 0, |
88 | | - uniquePages: row3?.cnt ?? 0, |
89 | | - notFoundCount: row4?.cnt ?? 0 |
90 | | - }; |
91 | | - |
92 | | - // ── Per-target queries (FTS5 trigram pre-filter + LIKE refinement) ── |
93 | | - const targetStmts = SEO_TARGETS.map((t) => { |
94 | | - const q = targetPerformanceQuery(t.keywords); |
95 | | - return db.prepare(q.sql).bind(...q.params); |
96 | | - }); |
97 | | - |
98 | | - const targetResults = await db.batch(targetStmts); |
99 | | - |
100 | | - const targets: TargetResult[] = SEO_TARGETS.map((t, i) => { |
101 | | - const rows = (targetResults[i]?.results ?? []) as QueryRow[]; |
102 | | - const totalImpressions = rows.reduce((s, r) => s + r.impressions, 0); |
103 | | - const totalClicks = rows.reduce((s, r) => s + r.clicks, 0); |
104 | | - const avgPosition = |
105 | | - totalImpressions > 0 |
106 | | - ? rows.reduce((s, r) => s + r.position * r.impressions, 0) / totalImpressions |
107 | | - : 0; |
108 | | - const avgCtr = totalImpressions > 0 ? (totalClicks / totalImpressions) * 100 : 0; |
109 | | - |
110 | | - return { |
111 | | - name: t.name, |
112 | | - audience: t.audience, |
113 | | - keywords: t.keywords, |
114 | | - targetPages: t.targetPages, |
115 | | - performance: { |
116 | | - totalImpressions, |
117 | | - totalClicks, |
118 | | - avgPosition: Math.round(avgPosition * 10) / 10, |
119 | | - avgCtr: Math.round(avgCtr * 100) / 100, |
120 | | - topQueries: rows.slice(0, 10) |
121 | | - }, |
122 | | - actions: analyseTarget(t, rows) |
123 | | - }; |
124 | | - }); |
125 | | - |
126 | | - // ── Sitewide overview (single batch) ────────────────────── |
127 | | - const swStmts = sitewideQueries().map((q) => db.prepare(q.sql).bind(...q.params)); |
128 | | - const sitewideResults = await db.batch(swStmts); |
129 | | - |
130 | | - const sitewide = { |
131 | | - topQueries: (sitewideResults[0]?.results ?? []) as SitewideQuery[], |
132 | | - topPages: (sitewideResults[1]?.results ?? []) as SitewidePage[], |
133 | | - contentGaps: (sitewideResults[2]?.results ?? []) as ContentGap[], |
134 | | - search404s: (sitewideResults[3]?.results ?? []) as Search404[], |
135 | | - recentActions: (sitewideResults[4]?.results ?? []) as SeoAction[] |
136 | | - }; |
137 | | - |
138 | | - return json( |
139 | | - { |
140 | | - generated: new Date().toISOString(), |
141 | | - dataHealth, |
142 | | - targets, |
143 | | - sitewide |
144 | | - }, |
145 | | - { |
146 | | - headers: { 'Cache-Control': 'no-store' } |
147 | | - } |
148 | | - ); |
149 | | - } catch (err: unknown) { |
150 | | - const message = err instanceof Error ? err.message : String(err); |
151 | | - console.error('SEO dashboard query failed:', message); |
152 | | - return json( |
153 | | - { |
154 | | - error: 'Query failed', |
155 | | - message, |
156 | | - hint: 'Check that the search-intelligence D1 schema has been applied (schema.sql).' |
157 | | - }, |
158 | | - { |
159 | | - status: 500, |
160 | | - headers: { 'Cache-Control': 'no-store' } |
161 | | - } |
162 | | - ); |
163 | | - } |
| 43 | + // InfoSec: Application-level rate limiting (defense-in-depth behind WAF rules) |
| 44 | + const rl = await checkRateLimit(platform?.env?.CACHE_KV, `seo-dash:${getClientAddress()}`, { |
| 45 | + limit: 10, |
| 46 | + window: 60 |
| 47 | + }); |
| 48 | + if (!rl.allowed) { |
| 49 | + return json( |
| 50 | + { error: 'Rate limit exceeded. Try again later.' }, |
| 51 | + { status: 429, headers: { 'Cache-Control': 'no-store', ...rateLimitHeaders(rl, 10) } } |
| 52 | + ); |
| 53 | + } |
| 54 | + |
| 55 | + const db = getDb(platform); |
| 56 | + |
| 57 | + if (!db) { |
| 58 | + return json( |
| 59 | + { |
| 60 | + error: 'D1 database unavailable', |
| 61 | + hint: 'SEARCH_INTEL_DB binding not found. This endpoint requires Cloudflare Workers with D1.' |
| 62 | + }, |
| 63 | + { |
| 64 | + status: 503, |
| 65 | + headers: { 'Cache-Control': 'no-store' } |
| 66 | + } |
| 67 | + ); |
| 68 | + } |
| 69 | + |
| 70 | + try { |
| 71 | + // ── Data health (single batch) ───────────────────────────── |
| 72 | + const healthStmts = healthQueries().map((q) => db.prepare(q.sql).bind(...q.params)); |
| 73 | + const healthResults = await db.batch(healthStmts); |
| 74 | + |
| 75 | + const row0 = healthResults[0]?.results[0] as { cnt: number } | undefined; |
| 76 | + const row1 = healthResults[1]?.results[0] as |
| 77 | + | { earliest: string | null; latest: string | null } |
| 78 | + | undefined; |
| 79 | + const row2 = healthResults[2]?.results[0] as { cnt: number } | undefined; |
| 80 | + const row3 = healthResults[3]?.results[0] as { cnt: number } | undefined; |
| 81 | + const row4 = healthResults[4]?.results[0] as { cnt: number } | undefined; |
| 82 | + |
| 83 | + const dataHealth: DataHealth = { |
| 84 | + totalRows: row0?.cnt ?? 0, |
| 85 | + earliest: row1?.earliest ?? null, |
| 86 | + latest: row1?.latest ?? null, |
| 87 | + uniqueQueries: row2?.cnt ?? 0, |
| 88 | + uniquePages: row3?.cnt ?? 0, |
| 89 | + notFoundCount: row4?.cnt ?? 0 |
| 90 | + }; |
| 91 | + |
| 92 | + // ── Per-target queries (FTS5 trigram pre-filter + LIKE refinement) ── |
| 93 | + const targetStmts = SEO_TARGETS.map((t) => { |
| 94 | + const q = targetPerformanceQuery(t.keywords); |
| 95 | + return db.prepare(q.sql).bind(...q.params); |
| 96 | + }); |
| 97 | + |
| 98 | + const targetResults = await db.batch(targetStmts); |
| 99 | + |
| 100 | + const targets: TargetResult[] = SEO_TARGETS.map((t, i) => { |
| 101 | + const rows = (targetResults[i]?.results ?? []) as QueryRow[]; |
| 102 | + const totalImpressions = rows.reduce((s, r) => s + r.impressions, 0); |
| 103 | + const totalClicks = rows.reduce((s, r) => s + r.clicks, 0); |
| 104 | + const avgPosition = |
| 105 | + totalImpressions > 0 |
| 106 | + ? rows.reduce((s, r) => s + r.position * r.impressions, 0) / totalImpressions |
| 107 | + : 0; |
| 108 | + const avgCtr = totalImpressions > 0 ? (totalClicks / totalImpressions) * 100 : 0; |
| 109 | + |
| 110 | + return { |
| 111 | + name: t.name, |
| 112 | + audience: t.audience, |
| 113 | + keywords: t.keywords, |
| 114 | + targetPages: t.targetPages, |
| 115 | + performance: { |
| 116 | + totalImpressions, |
| 117 | + totalClicks, |
| 118 | + avgPosition: Math.round(avgPosition * 10) / 10, |
| 119 | + avgCtr: Math.round(avgCtr * 100) / 100, |
| 120 | + topQueries: rows.slice(0, 10) |
| 121 | + }, |
| 122 | + actions: analyseTarget(t, rows) |
| 123 | + }; |
| 124 | + }); |
| 125 | + |
| 126 | + // ── Sitewide overview (single batch) ────────────────────── |
| 127 | + const swStmts = sitewideQueries().map((q) => db.prepare(q.sql).bind(...q.params)); |
| 128 | + const sitewideResults = await db.batch(swStmts); |
| 129 | + |
| 130 | + const sitewide = { |
| 131 | + topQueries: (sitewideResults[0]?.results ?? []) as SitewideQuery[], |
| 132 | + topPages: (sitewideResults[1]?.results ?? []) as SitewidePage[], |
| 133 | + contentGaps: (sitewideResults[2]?.results ?? []) as ContentGap[], |
| 134 | + search404s: (sitewideResults[3]?.results ?? []) as Search404[], |
| 135 | + recentActions: (sitewideResults[4]?.results ?? []) as SeoAction[] |
| 136 | + }; |
| 137 | + |
| 138 | + return json( |
| 139 | + { |
| 140 | + generated: new Date().toISOString(), |
| 141 | + dataHealth, |
| 142 | + targets, |
| 143 | + sitewide |
| 144 | + }, |
| 145 | + { |
| 146 | + headers: { 'Cache-Control': 'no-store' } |
| 147 | + } |
| 148 | + ); |
| 149 | + } catch (err: unknown) { |
| 150 | + const message = err instanceof Error ? err.message : String(err); |
| 151 | + console.error('SEO dashboard query failed:', message); |
| 152 | + return json( |
| 153 | + { |
| 154 | + error: 'Query failed', |
| 155 | + message, |
| 156 | + hint: 'Check that the search-intelligence D1 schema has been applied (schema.sql).' |
| 157 | + }, |
| 158 | + { |
| 159 | + status: 500, |
| 160 | + headers: { 'Cache-Control': 'no-store' } |
| 161 | + } |
| 162 | + ); |
| 163 | + } |
164 | 164 | }; |
0 commit comments