@tangen/ext-seo 0.0.0-stage → 0.2.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 (56) hide show
  1. package/package.json +55 -4
  2. package/src/client.ts +48 -0
  3. package/src/components/SeoPanel.tsx +489 -0
  4. package/src/contract.ts +269 -0
  5. package/src/hooks.ts +74 -0
  6. package/src/index.ts +41 -0
  7. package/src/lib/alt-text.ts +59 -0
  8. package/src/lib/analytics.ts +236 -0
  9. package/src/lib/canonical.ts +87 -0
  10. package/src/lib/deployment-role.ts +18 -0
  11. package/src/lib/health-report.ts +93 -0
  12. package/src/lib/llms.ts +55 -0
  13. package/src/lib/metadata.ts +268 -0
  14. package/src/lib/not-found.ts +83 -0
  15. package/src/lib/object-url.ts +83 -0
  16. package/src/lib/optimize.ts +77 -0
  17. package/src/lib/redirects-csv.ts +84 -0
  18. package/src/lib/redirects.ts +178 -0
  19. package/src/lib/resolve.ts +157 -0
  20. package/src/lib/robots.ts +76 -0
  21. package/src/lib/schema-map.ts +66 -0
  22. package/src/lib/schemas.ts +114 -0
  23. package/src/lib/seo-analysis.ts +185 -0
  24. package/src/lib/seo-manager-nav.ts +72 -0
  25. package/src/lib/settings.ts +167 -0
  26. package/src/lib/sitemap-report.ts +38 -0
  27. package/src/lib/sitemap.ts +109 -0
  28. package/src/lib/structured-data.ts +93 -0
  29. package/src/lib/titles.ts +109 -0
  30. package/src/nextjs.ts +70 -0
  31. package/src/pages/AiGeoTab.tsx +78 -0
  32. package/src/pages/AnalyticsTab.tsx +192 -0
  33. package/src/pages/GeoTab.tsx +76 -0
  34. package/src/pages/NotFoundTab.tsx +120 -0
  35. package/src/pages/SchemasTab.tsx +134 -0
  36. package/src/pages/SeoManagerPage.tsx +329 -0
  37. package/src/pages/SettingsTab.tsx +298 -0
  38. package/src/pages/SitemapTab.tsx +51 -0
  39. package/src/pages/TitlesTab.tsx +326 -0
  40. package/src/pages/ToolsTab.tsx +142 -0
  41. package/src/pages/manager-pages.tsx +46 -0
  42. package/src/pages/redirects.tsx +411 -0
  43. package/src/server/analytics-read.ts +51 -0
  44. package/src/server/analytics-sync.ts +182 -0
  45. package/src/server/artifacts.ts +305 -0
  46. package/src/server/health.ts +97 -0
  47. package/src/server/not-found-store.ts +71 -0
  48. package/src/server/optimize.ts +75 -0
  49. package/src/server/redirect-store.ts +128 -0
  50. package/src/server/routes.ts +604 -0
  51. package/src/server/search-console.ts +148 -0
  52. package/src/server/sitemap-source.ts +153 -0
  53. package/src/server/titles.ts +88 -0
  54. package/src/server.ts +47 -0
  55. package/tangen.extension.ts +153 -0
  56. package/README.md +0 -3
@@ -0,0 +1,604 @@
1
+ /**
2
+ * File Name: routes.ts
3
+ * Purpose: The SEO extension's HTTP surface (closure plan Phase 9A, Units 12
4
+ * and 15): what a website reads, and what the Admin manages. Two
5
+ * mounts with two different audiences and no overlap between them.
6
+ *
7
+ * Author: Raghunath J
8
+ * License: MIT
9
+ *
10
+ * Dependencies/Notes: Public routes serve the PUBLISHED snapshot only - there
11
+ * is no path from a draft edit to a public answer, and a route that
12
+ * could serve one would make every other guarantee here decorative.
13
+ * Member routes carry the extension's own capability. Every route
14
+ * 404s while the extension is not active in the resolved scope,
15
+ * which the platform enforces for us (Phase 4, Unit 10).
16
+ */
17
+ import { RouteError, type ExtensionAdminRoute, type ExtensionServerCtx } from '@tangen/cms'
18
+ import {
19
+ ARTIFACT_TTL, artifactKey, artifactVersion, bumpArtifactVersion,
20
+ helpersOf, resolvedSeoFor, robotsTxt, roleOf, sitemapIndex, sitemapPageXml, buildLlmsManifest,
21
+ } from './artifacts'
22
+ import { deleteRedirect, findRedirect, listRedirects, saveRedirect, REDIRECT_PAGE_SIZE } from './redirect-store'
23
+ import { applyQuery, normalizeSource, sourceQuery, type SeoRedirect } from '../lib/redirects'
24
+ import { validateCanonical } from '../lib/canonical'
25
+ import { normalizeSettings, mergeSettingsGroups, SEO_SETTINGS_KEY } from '../lib/settings'
26
+ import { normalizeSchemaMap, SEO_SCHEMA_MAP_KEY } from '../lib/schema-map'
27
+ import { readStored, pickMetadata } from '../lib/metadata'
28
+ import { altTextPrompt, cleanAltText, generateStatus, visionStatus } from '../lib/alt-text'
29
+ import { buildHealthReport, healthWidget } from './health'
30
+ import { searchConsoleConnection } from './search-console'
31
+ import { syncOnDemand } from './analytics-sync'
32
+ import { readAnalytics } from './analytics-read'
33
+ import { clearNotFound, ignoreNotFound, listNotFound, recordNotFound } from './not-found-store'
34
+ import { readTitles, writeTitle } from './titles'
35
+ import { optimizeObject } from './optimize'
36
+ import { parseRedirectCsv, toRedirectCsv } from '../lib/redirects-csv'
37
+ import { objectUrl, urlFieldName, urlFieldValue } from '../lib/object-url'
38
+
39
+ const XML = { 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=300' }
40
+ const TEXT = { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=300' }
41
+
42
+ const str = (v: unknown): string => (typeof v === 'string' ? v : '')
43
+ const num = (v: unknown, fallback: number): number => { const n = Number(v); return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback }
44
+
45
+ /**
46
+ * A key route's own gate: the manifest's `apiKeyScope` action, checked with the
47
+ * platform's `req.keyCan`. Without it a key minted for another extension could
48
+ * read everything this one serves.
49
+ */
50
+ async function keyedRead<T>(req: { keyCan?: (action: string) => boolean }, run: () => Promise<T>): Promise<T> {
51
+ if (req.keyCan && !req.keyCan('read')) {
52
+ throw new RouteError(403, 'This API key does not grant SEO read. Tick "Read SEO and redirects" on the key under Settings > API keys.', { code: 'SEO_KEY_SCOPE' })
53
+ }
54
+ return run()
55
+ }
56
+
57
+ /** Reads through the platform cache, keyed by version and locale. */
58
+ async function cached<T>(ctx: ExtensionServerCtx, name: string, locale: string | null, fn: () => Promise<T>): Promise<T> {
59
+ const version = await artifactVersion(ctx)
60
+ const key = artifactKey(name, version, locale)
61
+ const client = ctx.tangen
62
+ if (!client) return fn()
63
+ return client.cache({ key, ttl: ARTIFACT_TTL }, fn)
64
+ }
65
+
66
+ export const seoRoutes: ExtensionAdminRoute[] = [
67
+ // ── What a website reads ───────────────────────────────────────────────────
68
+ {
69
+ method: 'GET', path: 'meta', auth: 'public',
70
+ handler: async (req, ctx) => {
71
+ const type = str(req.query?.type)
72
+ const id = str(req.query?.id)
73
+ const locale = str(req.query?.locale) || null
74
+ if (!type || !id) return { error: { code: 'SEO_BAD_REQUEST', message: 'type and id are required' } }
75
+ // Published only. `preview` is not a query parameter on purpose: a
76
+ // public caller must not be able to ask for a draft.
77
+ const resolved = await cached(ctx, `meta:${type}:${id}`, locale, () => resolvedSeoFor(ctx, { type, id, locale }))
78
+ if (!resolved) return new Response(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'No published SEO for this object' } }), {
79
+ status: 404, headers: { 'Content-Type': 'application/json' },
80
+ })
81
+ return { data: resolved }
82
+ },
83
+ },
84
+ {
85
+ // The SDK's resolver: identical published SEO to `meta`, but authenticated
86
+ // by API key so the workspace comes from the key (client.seo() needs no
87
+ // X-Tangen-Workspace header). Published only, like its public twin.
88
+ //
89
+ // Gated by the same `seo: read` scope as redirects.json (2026-09-19): the
90
+ // route predates the manifest's apiKeyScope, so until now ANY key for the
91
+ // workspace could read it - including one minted for another extension.
92
+ // A key with full access is unaffected; a scoped one needs the box ticked.
93
+ method: 'GET', path: 'resolve', auth: 'key',
94
+ handler: async (req, ctx) => keyedRead(req, async () => {
95
+ const type = str(req.query?.type)
96
+ const id = str(req.query?.id)
97
+ const locale = str(req.query?.locale) || null
98
+ if (!type || !id) return { error: { code: 'SEO_BAD_REQUEST', message: 'type and id are required' } }
99
+ const resolved = await cached(ctx, `meta:${type}:${id}`, locale, () => resolvedSeoFor(ctx, { type, id, locale }))
100
+ if (!resolved) return new Response(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'No published SEO for this object' } }), {
101
+ status: 404, headers: { 'Content-Type': 'application/json' },
102
+ })
103
+ return { data: resolved }
104
+ }),
105
+ },
106
+ {
107
+ method: 'GET', path: 'robots.txt', auth: 'public',
108
+ handler: async (_req, ctx) => new Response(await cached(ctx, 'robots', null, () => robotsTxt(ctx)), { headers: TEXT }),
109
+ },
110
+ {
111
+ // The GEO manifest for AI crawlers. 404 when the toggle is off, so a
112
+ // disabled site serves no empty file. Cached by artifact version.
113
+ method: 'GET', path: 'llms.txt', auth: 'public',
114
+ handler: async (_req, ctx) => {
115
+ const body = await cached(ctx, 'llms', null, () => buildLlmsManifest(ctx, { full: false }))
116
+ if (body == null) return new Response('Not found', { status: 404, headers: TEXT })
117
+ return new Response(body, { headers: TEXT })
118
+ },
119
+ },
120
+ {
121
+ method: 'GET', path: 'llms-full.txt', auth: 'public',
122
+ handler: async (_req, ctx) => {
123
+ const body = await cached(ctx, 'llms-full', null, () => buildLlmsManifest(ctx, { full: true }))
124
+ if (body == null) return new Response('Not found', { status: 404, headers: TEXT })
125
+ return new Response(body, { headers: TEXT })
126
+ },
127
+ },
128
+ {
129
+ method: 'GET', path: 'sitemap.xml', auth: 'public',
130
+ handler: async (req, ctx) => {
131
+ const locale = str(req.query?.locale) || null
132
+ const page = num(req.query?.page, 1)
133
+ const { xml } = await cached(ctx, `sitemap:${page}`, locale, () => sitemapPageXml(ctx, page, locale))
134
+ return new Response(xml, { headers: XML })
135
+ },
136
+ },
137
+ {
138
+ method: 'GET', path: 'sitemap-index.xml', auth: 'public',
139
+ handler: async (req, ctx) => {
140
+ const locale = str(req.query?.locale) || null
141
+ const { xml } = await cached(ctx, 'sitemap-index', locale, () => sitemapIndex(ctx, locale))
142
+ return new Response(xml, { headers: XML })
143
+ },
144
+ },
145
+ {
146
+ // The request-path lookup: ONE indexed row read, whatever the site's size.
147
+ method: 'GET', path: 'redirect', auth: 'public',
148
+ handler: async (req, ctx) => {
149
+ const path = str(req.query?.path)
150
+ if (!path) return { error: { code: 'SEO_BAD_REQUEST', message: 'path is required' } }
151
+ const redirect = await findRedirect(ctx.store, path)
152
+ if (!redirect) {
153
+ // V5: the site is telling us a path did not resolve. Count it (paths only),
154
+ // never at the cost of its own answer.
155
+ await recordNotFound(ctx.store, path).catch(() => null)
156
+ return new Response(JSON.stringify({ data: null }), { status: 404, headers: { 'Content-Type': 'application/json' } })
157
+ }
158
+ const resolved = await resolveDestination(ctx, redirect)
159
+ // The query the visitor arrived with rides along unless this redirect says not to.
160
+ const destination = resolved ? applyQuery(resolved, sourceQuery(path), redirect.keepQuery) : resolved
161
+ // An internal target whose URL the application cannot place is NOT a
162
+ // redirect anyone can follow, so it is reported as unresolved rather
163
+ // than served as a broken one.
164
+ if (!destination) return new Response(JSON.stringify({ data: null, reason: 'UNRESOLVED_DESTINATION' }), { status: 404, headers: { 'Content-Type': 'application/json' } })
165
+ return { data: { source: redirect.source, destination, status: redirect.status } }
166
+ },
167
+ },
168
+
169
+ // ── What the Admin manages ─────────────────────────────────────────────────
170
+ {
171
+ method: 'GET', path: 'redirects', auth: 'member', capability: 'seo:read',
172
+ handler: async (req, ctx) => {
173
+ const limit = Math.min(num(req.query?.limit, REDIRECT_PAGE_SIZE), 200)
174
+ const offset = num(req.query?.offset, 0) - (req.query?.offset ? 0 : 0)
175
+ const sort = str(req.query?.sort) === 'updatedAt' ? 'updatedAt' as const : 'source' as const
176
+ const { rows, total } = await listRedirects(ctx.store, {
177
+ limit, offset: Number(req.query?.offset ?? 0) || 0, sort, desc: str(req.query?.dir) === 'desc',
178
+ })
179
+ const search = str(req.query?.search).trim().toLowerCase()
180
+ const enabled = str(req.query?.enabled)
181
+ const kind = str(req.query?.kind)
182
+ const bySearch = search ? rows.filter((r) => r.source.includes(search) || JSON.stringify(r.destination).toLowerCase().includes(search)) : rows
183
+ const byState = enabled === 'on' ? bySearch.filter((r) => r.enabled !== false)
184
+ : enabled === 'off' ? bySearch.filter((r) => r.enabled === false)
185
+ : bySearch
186
+ // 'content' is the stored 'internal' kind, said the way the form says it.
187
+ const wanted = kind === 'content' ? 'internal' : kind === 'url' ? 'external' : kind === 'path' ? 'path' : null
188
+ const filtered = wanted ? byState.filter((r) => r.destination.kind === wanted) : byState
189
+ // A content target is stored as an identity; the app resolves the URL. Show
190
+ // it, so the editor sees where the redirect actually goes (null when the
191
+ // app cannot place it yet, which is honest rather than a broken link).
192
+ const withResolved = await Promise.all(filtered.map(async (r) => (
193
+ r.destination.kind === 'internal' ? { ...r, resolved: await resolveDestination(ctx, r) } : r
194
+ )))
195
+ return { data: withResolved, meta: { total, limit, offset, filtered: Boolean(search) } }
196
+ },
197
+ },
198
+ {
199
+ method: 'POST', path: 'redirects', auth: 'member', capability: 'seo:write',
200
+ handler: async (req, ctx) => writeRedirect(ctx, req.body as Record<string, unknown>, undefined),
201
+ },
202
+ {
203
+ method: 'PATCH', path: 'redirects', auth: 'member', capability: 'seo:write',
204
+ handler: async (req, ctx) => {
205
+ const body = (req.body ?? {}) as Record<string, unknown>
206
+ return writeRedirect(ctx, body, str(body.replacing) || undefined)
207
+ },
208
+ },
209
+ {
210
+ method: 'DELETE', path: 'redirects', auth: 'member', capability: 'seo:write',
211
+ handler: async (req, ctx) => {
212
+ const source = str(req.query?.source) || str((req.body as Record<string, unknown> | undefined)?.source)
213
+ if (!source) throw new RouteError(422, 'source is required', { code: 'SEO_BAD_REQUEST' })
214
+ await deleteRedirect(ctx.store, source)
215
+ await bumpArtifactVersion(ctx)
216
+ return { data: { source: normalizeSource(source), deleted: true } }
217
+ },
218
+ },
219
+ {
220
+ // The editor's own preview of a draft. Member-only, and it says so.
221
+ method: 'GET', path: 'preview', auth: 'member', capability: 'seo:read',
222
+ handler: async (req, ctx) => {
223
+ const type = str(req.query?.type)
224
+ const id = str(req.query?.id)
225
+ if (!type || !id) return { error: { code: 'SEO_BAD_REQUEST', message: 'type and id are required' } }
226
+ return { data: await resolvedSeoFor(ctx, { type, id, locale: str(req.query?.locale) || null, preview: true }) }
227
+ },
228
+ },
229
+ {
230
+ // What the sitemap would contain and, more usefully, what it would not.
231
+ method: 'GET', path: 'sitemap-report', auth: 'member', capability: 'seo:read',
232
+ handler: async (req, ctx) => {
233
+ const { build, pageCount } = await sitemapIndex(ctx, str(req.query?.locale) || null)
234
+ return { data: { entries: build.entries.length, pageCount, skipped: build.skipped, scanned: build.scanned, truncated: build.truncated } }
235
+ },
236
+ },
237
+ {
238
+ // S2: the GEO tab's preview of the manifest the public route serves. Member-only and gated by the same
239
+ // switch: when llms.txt is off the answer says so, rather than the public route's 404.
240
+ method: 'GET', path: 'llms-preview', auth: 'member', capability: 'seo:read',
241
+ handler: async (req, ctx) => {
242
+ const manifest = await buildLlmsManifest(ctx, { full: str(req.query?.full) === '1' })
243
+ return { data: { enabled: manifest !== null, path: '/api/v1/ext/seo/llms.txt', manifest } }
244
+ },
245
+ },
246
+ // ── V1: the Dashboard's health report ───────────────────────────────────────
247
+ {
248
+ // Cached under the artifact version (a publish retires it); POST rebuilds now.
249
+ method: 'GET', path: 'health-report', auth: 'member', capability: 'seo:read',
250
+ handler: async (_req, ctx) => ({ data: await cached(ctx, 'health-report', null, () => buildHealthReport(ctx)) }),
251
+ },
252
+ {
253
+ // A rebuild writes the stored report, so it is a write like any other.
254
+ method: 'POST', path: 'health-report', auth: 'member', capability: 'seo:write',
255
+ handler: async (_req, ctx) => ({ data: await buildHealthReport(ctx) }),
256
+ },
257
+ // ── V3: Search Console ──────────────────────────────────────────────────────
258
+ {
259
+ // The connection's state and the properties it may read, so an operator can copy the exact property value into Settings.
260
+ method: 'GET', path: 'search-console/sites', auth: 'member', capability: 'seo:read',
261
+ handler: async (_req, ctx) => {
262
+ const { status, reader } = await searchConsoleConnection(ctx)
263
+ if (!status.connected || !reader) return { data: { ...status, sites: [] } }
264
+ try { return { data: { ...status, sites: await reader.listSites() } } }
265
+ catch (e) { return { data: { connected: false as const, reason: `The connection could not list properties: ${(e as Error).message}`, sites: [] } } }
266
+ },
267
+ },
268
+ // ── V2: Titles & Meta, a workspace-wide table ───────────────────────────────
269
+ {
270
+ method: 'GET', path: 'titles', auth: 'member', capability: 'seo:read',
271
+ handler: async (req, ctx) => {
272
+ const sort = ['page', 'title', 'state'].includes(str(req.query?.sort)) ? str(req.query?.sort) as 'page' : undefined
273
+ const view = await readTitles(ctx, {
274
+ type: str(req.query?.type) || null, state: str(req.query?.state) || null, search: str(req.query?.search) || null,
275
+ limit: num(req.query?.limit, 25), offset: Number(req.query?.offset ?? 0) || 0,
276
+ ...(sort ? { sort } : {}),
277
+ ...(str(req.query?.dir) ? { desc: str(req.query?.dir) === 'desc' } : {}),
278
+ })
279
+ return { data: view.rows, meta: { total: view.total, scanned: view.scanned, counts: view.counts, types: view.types } }
280
+ },
281
+ },
282
+ {
283
+ // Writes the DRAFT, never the live snapshot: Tangen's publishing semantics
284
+ // decide when a visitor sees it, and the row says so.
285
+ method: 'PATCH', path: 'titles', auth: 'member', capability: 'seo:write',
286
+ handler: async (req, ctx) => {
287
+ const body = (req.body ?? {}) as Record<string, unknown>
288
+ const out = await writeTitle(ctx, {
289
+ id: str(body.id), type: str(body.type),
290
+ ...(body.title !== undefined ? { title: body.title as string | null } : {}),
291
+ ...(body.description !== undefined ? { description: body.description as string | null } : {}),
292
+ ...(body.locale ? { locale: str(body.locale) } : {}),
293
+ })
294
+ if (!out.ok) throw new RouteError(422, out.reason, { code: 'SEO_BAD_REQUEST' })
295
+ await bumpArtifactVersion(ctx)
296
+ return { data: out.row }
297
+ },
298
+ },
299
+ // ── V7: Tools ───────────────────────────────────────────────────────────────
300
+ {
301
+ // What the public robots.txt currently says, and which deployment role shaped it.
302
+ method: 'GET', path: 'robots-preview', auth: 'member', capability: 'seo:read',
303
+ handler: async (_req, ctx) => ({ data: { body: await robotsTxt(ctx), role: await roleOf(ctx), path: '/api/v1/ext/seo/robots.txt' } }),
304
+ },
305
+ {
306
+ // Retires every cached artifact (meta, sitemaps, llms.txt, the health report).
307
+ method: 'POST', path: 'refresh-caches', auth: 'member', capability: 'seo:write',
308
+ handler: async (_req, ctx) => ({ data: { version: await bumpArtifactVersion(ctx) } }),
309
+ },
310
+ {
311
+ // Every redirect as a CSV file, for a spreadsheet or another CMS.
312
+ method: 'GET', path: 'redirects/export', auth: 'member', capability: 'seo:read',
313
+ handler: async (_req, ctx) => {
314
+ const { rows } = await listRedirects(ctx.store, { limit: 10_000 })
315
+ return new Response(toRedirectCsv(rows), { headers: { 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="redirects.csv"' } })
316
+ },
317
+ },
318
+ {
319
+ // A CSV file in. Every row that cannot be read is reported with its line
320
+ // number; the rows that can be are written through the same saveRedirect
321
+ // the form uses, so the same rules apply.
322
+ method: 'POST', path: 'redirects/import', auth: 'member', capability: 'seo:write',
323
+ handler: async (req, ctx) => {
324
+ const body = (req.body ?? {}) as Record<string, unknown>
325
+ const parsed = parseRedirectCsv(str(body.csv))
326
+ const now = new Date().toISOString()
327
+ const siteUrl = helpersOf(ctx).siteUrl
328
+ let created = 0
329
+ const refused: Array<{ source: string; reason: string }> = []
330
+ for (const row of parsed.rows) {
331
+ const saved = await saveRedirect(ctx.store, { source: row.source, destination: { kind: 'external', url: row.url }, status: row.status }, { now, ...(siteUrl ? { siteUrl } : {}) })
332
+ if (saved.ok) created += 1
333
+ else refused.push({ source: row.source, reason: saved.reason })
334
+ }
335
+ if (created) await bumpArtifactVersion(ctx)
336
+ return { data: { read: parsed.rows.length, written: created, malformed: parsed.errors, refused } }
337
+ },
338
+ },
339
+ // ── V6: what this installation's AI can do for SEO ──────────────────────────
340
+ {
341
+ method: 'GET', path: 'ai-status', auth: 'member', capability: 'seo:read',
342
+ handler: async (_req, ctx) => ({ data: { generate: generateStatus(ctx), vision: visionStatus(ctx) } }),
343
+ },
344
+ // ── V6: the AI optimisation action, one object at a time ────────────────────
345
+ {
346
+ // Proposes SEO values for one page. Nothing is stored unless `apply` is
347
+ // asked for, and then only the DRAFT: AI never changes what a visitor sees.
348
+ // A later bulk run calls this same action per selected object.
349
+ method: 'POST', path: 'optimize', auth: 'member', capability: 'seo:write',
350
+ handler: async (req, ctx) => {
351
+ const body = (req.body ?? {}) as Record<string, unknown>
352
+ const out = await optimizeObject(ctx, { type: str(body.type), id: str(body.id), apply: body.apply === true, locale: str(body.locale) || null })
353
+ if (!out.ok) throw new RouteError(422, out.reason, { code: 'SEO_OPTIMIZE_UNAVAILABLE' })
354
+ if (out.applied) await bumpArtifactVersion(ctx)
355
+ return { data: out }
356
+ },
357
+ },
358
+ {
359
+ // Every enabled redirect, resolved, for a site that wants to hold the map
360
+ // itself (a Next.js `redirects()`, an edge middleware) instead of asking
361
+ // per request. Key-authenticated like the SDK resolver, and cached under
362
+ // the artifact version, so a write invalidates it.
363
+ method: 'GET', path: 'redirects.json', auth: 'key',
364
+ handler: async (req, ctx) => {
365
+ // The key must carry SEO read (Settings > API keys). A key minted for
366
+ // something else does not get the site's whole routing table.
367
+ const built = await keyedRead(req, async () => cached(ctx, 'redirects-json', null, async () => {
368
+ const { rows } = await listRedirects(ctx.store, { limit: 10_000 })
369
+ const data: Array<{ from: string; to: string; status: 301 | 302 }> = []
370
+ let off = 0
371
+ let unresolved = 0
372
+ for (const row of rows) {
373
+ if (row.enabled === false) { off += 1; continue }
374
+ const to = await resolveDestination(ctx, row)
375
+ // A destination the app cannot place is not a redirect anyone can
376
+ // follow, so it is left out rather than shipped as a rule nobody can
377
+ // follow - and COUNTED, because a rule that silently vanished from
378
+ // the map is how an operator loses an afternoon.
379
+ if (to) data.push({ from: row.source, to, status: row.status })
380
+ else unresolved += 1
381
+ }
382
+ return { data, counts: { total: rows.length, off, unresolved } }
383
+ })) as { data: Array<{ from: string; to: string; status: 301 | 302 }>; counts: { total: number; off: number; unresolved: number } }
384
+ return { data: built.data, meta: { ...built.counts, generatedAt: new Date().toISOString() } }
385
+ },
386
+ },
387
+ // ── V5: the 404 Monitor ─────────────────────────────────────────────────────
388
+ {
389
+ // For a site that does not ask Tangen for a redirect on a miss: tell it the
390
+ // path. Paths only - an absolute URL or a query string is reduced to its
391
+ // path, and nothing about the visitor is read. Rate limited like any public write.
392
+ method: 'POST', path: 'not-found', auth: 'public',
393
+ handler: async (req, ctx) => {
394
+ const limit = await ctx.tangen?.rateLimit?.('seo:not-found', 120, 60).catch(() => undefined)
395
+ if (limit && limit.allowed === false) {
396
+ return new Response(JSON.stringify({ data: null, reason: 'RATE_LIMITED' }), { status: 429, headers: { 'Content-Type': 'application/json' } })
397
+ }
398
+ const body = (req.body ?? {}) as Record<string, unknown>
399
+ const recorded = await recordNotFound(ctx.store, body.path ?? str(req.query?.path)).catch(() => null)
400
+ return { data: { recorded: recorded !== null } }
401
+ },
402
+ },
403
+ {
404
+ method: 'GET', path: 'not-found', auth: 'member', capability: 'seo:read',
405
+ handler: async (req, ctx) => {
406
+ const sort = ['hits', 'path', 'lastSeenAt', 'firstSeenAt'].includes(str(req.query?.sort)) ? str(req.query?.sort) as 'hits' : undefined
407
+ const { rows, total, tracked, cap } = await listNotFound(ctx.store, {
408
+ limit: num(req.query?.limit, 50),
409
+ offset: Number(req.query?.offset ?? 0) || 0,
410
+ includeIgnored: str(req.query?.includeIgnored) === '1',
411
+ ...(sort ? { sort } : {}),
412
+ ...(str(req.query?.dir) ? { desc: str(req.query?.dir) === 'desc' } : {}),
413
+ })
414
+ return { data: rows, meta: { total, tracked, cap } }
415
+ },
416
+ },
417
+ {
418
+ method: 'POST', path: 'not-found/ignore', auth: 'member', capability: 'seo:write',
419
+ handler: async (req, ctx) => {
420
+ const row = await ignoreNotFound(ctx.store, (req.body as Record<string, unknown> | undefined)?.path)
421
+ if (!row) throw new RouteError(404, 'That path is not being tracked.', { code: 'SEO_NOT_FOUND_UNKNOWN' })
422
+ return { data: row }
423
+ },
424
+ },
425
+ {
426
+ method: 'DELETE', path: 'not-found', auth: 'member', capability: 'seo:write',
427
+ handler: async (req, ctx) => {
428
+ const path = str(req.query?.path) || str((req.body as Record<string, unknown> | undefined)?.path)
429
+ const cleared = await clearNotFound(ctx.store, path)
430
+ if (!cleared) throw new RouteError(404, 'That path is not being tracked.', { code: 'SEO_NOT_FOUND_UNKNOWN' })
431
+ return { data: { path, cleared: true } }
432
+ },
433
+ },
434
+ // ── V4: Analytics, read from the store alone ────────────────────────────────
435
+ {
436
+ // A render never calls Google: the daily task and the Sync button write, this reads.
437
+ method: 'GET', path: 'analytics', auth: 'member', capability: 'seo:read',
438
+ handler: async (req, ctx) => ({ data: await readAnalytics(ctx, { days: num(req.query?.days, 28) }) }),
439
+ },
440
+ {
441
+ method: 'POST', path: 'analytics/sync', auth: 'member', capability: 'seo:write',
442
+ handler: async (_req, ctx) => {
443
+ const out = await syncOnDemand(ctx)
444
+ if (!out.ok) throw new RouteError(429, out.reason, { code: 'SEO_SYNC_REFUSED', ...(out.retryAfterSeconds ? { retryAfterSeconds: out.retryAfterSeconds } : {}) })
445
+ return { data: out }
446
+ },
447
+ },
448
+ {
449
+ // V8: the workspace dashboard's tile. The LAST stored report, never a scan.
450
+ method: 'GET', path: 'health-widget', auth: 'member', capability: 'seo:read',
451
+ handler: async (_req, ctx) => ({ data: await healthWidget(ctx) }),
452
+ },
453
+ // ── S3: share-image alt text through a vision provider ─────────────────────
454
+ {
455
+ // Whether the panel's Describe button exists at all: both optional grants held and a provider that can see.
456
+ method: 'GET', path: 'vision-status', auth: 'member', capability: 'seo:read',
457
+ handler: async (_req, ctx) => ({ data: visionStatus(ctx) }),
458
+ },
459
+ {
460
+ // Describes the object's share image (its own, else the workspace default) from its BYTES, so a
461
+ // media file on a private host works and the provider fetches nothing. Every missing piece is a
462
+ // named answer: the panel keeps the hand-written field either way.
463
+ method: 'POST', path: 'alt-text', auth: 'member', capability: 'seo:write',
464
+ handler: async (req, ctx) => {
465
+ const body = (req.body ?? {}) as Record<string, unknown>
466
+ const id = str(body.id)
467
+ if (!id) throw new RouteError(422, 'id is required', { code: 'SEO_BAD_REQUEST' })
468
+ const status = visionStatus(ctx)
469
+ if (!status.available) throw new RouteError(422, status.reason, { code: 'SEO_VISION_UNAVAILABLE' })
470
+ const stored = readStored(await ctx.store.get(id))
471
+ const settings = normalizeSettings(await ctx.store.get(SEO_SETTINGS_KEY))
472
+ const imageId = pickMetadata(stored.draft, str(body.locale) || null).social?.imageId ?? settings.social.defaultImageId ?? null
473
+ if (!imageId) throw new RouteError(422, 'No share image to describe: this object has none and SEO Manager > Settings > Social has no default image.', { code: 'SEO_NO_IMAGE' })
474
+ const asset = await ctx.media!.read(imageId)
475
+ if (!asset) throw new RouteError(422, `The share image (${imageId}) could not be read from the media library.`, { code: 'SEO_NO_IMAGE' })
476
+ if (!asset.mimeType.startsWith('image/')) throw new RouteError(422, `The share image is ${asset.mimeType}, not an image.`, { code: 'SEO_NO_IMAGE' })
477
+ const r = await ctx.ai!.vision!.describe({
478
+ image: { base64: Buffer.from(asset.bytes).toString('base64'), mimeType: asset.mimeType },
479
+ prompt: altTextPrompt({ title: str(body.title) || undefined }),
480
+ maxTokens: 120,
481
+ })
482
+ return { data: { alt: cleanAltText(r.text), imageId, provider: r.provider, model: r.model } }
483
+ },
484
+ },
485
+ // ── Workspace-level settings (the Settings tab; hybrid config on ctx.store) ──
486
+ //
487
+ // `site-settings`, NOT `settings`: core serves `GET/POST <ext>/settings`
488
+ // itself for any extension whose manifest declares typed settings, and SEO
489
+ // declares four (the Search Console ones). So this route was SHADOWED - the
490
+ // tab asked for its own settings and was handed the manifest form's payload,
491
+ // which has no `general` (found in acme, 2026-09-20). The store key is
492
+ // unchanged, so nothing has to be migrated.
493
+ {
494
+ // Always returns a fully-defaulted, junk-free shape - the codec is the one
495
+ // read path, so an empty or legacy row still reads as valid settings.
496
+ method: 'GET', path: 'site-settings', auth: 'member', capability: 'seo:read',
497
+ handler: async (_req, ctx) => ({ data: normalizeSettings(await ctx.store.get(SEO_SETTINGS_KEY)) }),
498
+ },
499
+ {
500
+ // A MERGE, one group at a time: the Settings tab saves the group you
501
+ // edited rather than posting every group back (the user, 2026-09-20), so
502
+ // two people editing different groups do not overwrite each other and a
503
+ // failed save loses one section, not the page. A body carrying every
504
+ // group still works, which is what a full save is.
505
+ method: 'POST', path: 'site-settings', auth: 'member', capability: 'seo:write',
506
+ handler: async (req, ctx) => {
507
+ const stored = normalizeSettings(await ctx.store.get(SEO_SETTINGS_KEY))
508
+ const next = normalizeSettings(mergeSettingsGroups(stored, req.body))
509
+ await ctx.store.put(SEO_SETTINGS_KEY, next as unknown as Record<string, unknown>)
510
+ await bumpArtifactVersion(ctx) // settings change what /meta resolves - retire cached artifacts
511
+ return { data: next }
512
+ },
513
+ },
514
+ // ── Per-content-type JSON-LD schema mapping (the Schemas tab) ────────────────
515
+ {
516
+ // The map plus the content types (and their fields) to map, so the tab can
517
+ // render kind + field-mapping pickers from one call.
518
+ method: 'GET', path: 'schemas', auth: 'member', capability: 'seo:read',
519
+ handler: async (_req, ctx) => {
520
+ const map = normalizeSchemaMap(await ctx.store.get(SEO_SCHEMA_MAP_KEY))
521
+ const types = (ctx.types?.() ?? []).map((t) => ({
522
+ name: t.name,
523
+ label: (t as { label?: string }).label ?? t.name,
524
+ fields: ((t as { fields?: { name: string; label?: string }[] }).fields ?? []).map((f) => ({ name: f.name, label: f.label ?? f.name })),
525
+ }))
526
+ return { data: { map, types } }
527
+ },
528
+ },
529
+ {
530
+ // A full replace, normalized before storage (unknown kinds and 'none' drop).
531
+ method: 'POST', path: 'schemas', auth: 'member', capability: 'seo:write',
532
+ handler: async (req, ctx) => {
533
+ const next = normalizeSchemaMap(req.body)
534
+ await ctx.store.put(SEO_SCHEMA_MAP_KEY, next as unknown as Record<string, unknown>)
535
+ await bumpArtifactVersion(ctx)
536
+ return { data: next }
537
+ },
538
+ },
539
+ ]
540
+
541
+ /** A redirect's destination as an absolute URL, or null when it cannot be placed. */
542
+ async function resolveDestination(ctx: ExtensionServerCtx, redirect: SeoRedirect): Promise<string | null> {
543
+ if (redirect.destination.kind === 'external') {
544
+ const checked = validateCanonical(redirect.destination.url)
545
+ return checked.ok ? checked.url : null
546
+ }
547
+ // A path on this site stays a path: a relative Location is valid, and the
548
+ // application knows its own origin better than Tangen does.
549
+ if (redirect.destination.kind === 'path') return redirect.destination.path
550
+ const helpers = helpersOf(ctx)
551
+ const { type, id } = redirect.destination
552
+ // Read the ONE field the site declared for this type, and only when it did:
553
+ // a redirect map of 10,000 rules must not become 10,000 object reads.
554
+ let fieldValue: string | null = null
555
+ if (urlFieldName(helpers, type) && ctx.tangen) {
556
+ try {
557
+ const res = await ctx.tangen.objects(type as never).status('any').find(id)
558
+ fieldValue = urlFieldValue(helpers, type, (res.data ?? null) as Record<string, unknown> | null)
559
+ } catch { /* an object that cannot be read has no URL, which is the answer below */ }
560
+ }
561
+ try {
562
+ const url = await objectUrl({ helpers, workspaceId: ctx.workspaceId, type, id, locale: null, fieldValue })
563
+ if (!url) return null
564
+ const checked = validateCanonical(url)
565
+ return checked.ok ? checked.url : null
566
+ } catch { return null }
567
+ }
568
+
569
+ async function writeRedirect(ctx: ExtensionServerCtx, body: Record<string, unknown>, replacing?: string) {
570
+ const result = await saveRedirect(ctx.store, {
571
+ source: str(body.source),
572
+ destination: body.destination as SeoRedirect['destination'],
573
+ status: Number(body.status ?? 301) as SeoRedirect['status'],
574
+ enabled: body.enabled !== false,
575
+ ...(body.keepQuery === false ? { keepQuery: false } : {}),
576
+ createdAt: str(body.createdAt) || undefined,
577
+ note: str(body.note) || undefined,
578
+ }, { replacing, siteUrl: helpersOf(ctx).siteUrl, now: new Date().toISOString() })
579
+
580
+ if (!result.ok) {
581
+ // A refusal must be an HTTP refusal: an error envelope served with 200 let
582
+ // a client report success and lose the write (found in acme, 2026-09-18).
583
+ throw new RouteError(422, redirectMessage(result.reason), { code: result.reason, ...(result.detail ? { details: result.detail } : {}) })
584
+ }
585
+ await bumpArtifactVersion(ctx)
586
+ return { data: result.redirect }
587
+ }
588
+
589
+ /** Editor-facing wording. The code is for machines; this is for people. */
590
+ function redirectMessage(reason: string): string {
591
+ switch (reason) {
592
+ case 'SOURCE_EMPTY': return 'Enter the path this redirect starts from.'
593
+ case 'SOURCE_NOT_A_PATH': return 'The source is a path on your site, like /old-page, not a full URL.'
594
+ case 'DESTINATION_EMPTY': return 'Choose where this redirect should go.'
595
+ case 'DESTINATION_SCHEME': return 'A destination must be an http or https address.'
596
+ case 'DESTINATION_NOT_ABSOLUTE': return 'An external destination needs its full address, including https://.'
597
+ case 'DESTINATION_IDENTITY': return 'Choose the content this redirect should point at.'
598
+ case 'SELF_REDIRECT': return 'This redirect points at itself, which would loop forever.'
599
+ case 'DUPLICATE_SOURCE': return 'A redirect from this path already exists. Edit that one instead.'
600
+ case 'REDIRECT_LOOP': return 'This would complete a loop with redirects you already have.'
601
+ case 'STATUS': return 'A redirect is either permanent (301) or temporary (302).'
602
+ default: return 'This redirect could not be saved.'
603
+ }
604
+ }