@tangen/ext-seo 0.0.0-stage → 0.2.1

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,87 @@
1
+ /**
2
+ * File Name: canonical.ts
3
+ * Purpose: Canonical URL resolution and its safety rules (closure plan Phase
4
+ * 9A, Unit 3). The one rule that governs the whole file: Tangen
5
+ * never invents a URL. A canonical is stated, resolved by the
6
+ * application, or omitted.
7
+ *
8
+ * Author: Raghunath J
9
+ * License: MIT
10
+ *
11
+ * Dependencies/Notes: Pure. Phase 6B froze "Tangen resolves content identity;
12
+ * the consuming application resolves site routing", so there is no
13
+ * slug concatenation here and no Core href resolver is introduced.
14
+ */
15
+ import type { SeoUrlInput, SeoUrlResolver } from '../contract'
16
+
17
+ /** Schemes a canonical may use. Everything else is refused, not sanitized. */
18
+ const ALLOWED_SCHEMES = new Set(['https:', 'http:'])
19
+
20
+ /** Long enough for any real URL; short enough that nothing absurd is stored. */
21
+ export const MAX_URL_LENGTH = 2048
22
+
23
+ export type CanonicalCheck =
24
+ | { ok: true; url: string }
25
+ | { ok: false; reason: 'CANONICAL_EMPTY' | 'CANONICAL_MALFORMED' | 'CANONICAL_NOT_ABSOLUTE' | 'CANONICAL_SCHEME' | 'CANONICAL_FRAGMENT' | 'CANONICAL_TOO_LONG' }
26
+
27
+ /**
28
+ * Whether a string may be used as a canonical.
29
+ *
30
+ * Fragments are REFUSED rather than stripped. A canonical names the page a
31
+ * search engine should index; `#section` names a place inside one, and
32
+ * quietly deleting it would hide an editor's mistake instead of showing it.
33
+ */
34
+ export function validateCanonical(value: unknown): CanonicalCheck {
35
+ if (typeof value !== 'string' || value.trim() === '') return { ok: false, reason: 'CANONICAL_EMPTY' }
36
+ const raw = value.trim()
37
+ if (raw.length > MAX_URL_LENGTH) return { ok: false, reason: 'CANONICAL_TOO_LONG' }
38
+
39
+ let url: URL
40
+ try { url = new URL(raw) } catch { return { ok: false, reason: raw.startsWith('/') ? 'CANONICAL_NOT_ABSOLUTE' : 'CANONICAL_MALFORMED' } }
41
+
42
+ if (!ALLOWED_SCHEMES.has(url.protocol)) return { ok: false, reason: 'CANONICAL_SCHEME' }
43
+ if (!url.hostname) return { ok: false, reason: 'CANONICAL_MALFORMED' }
44
+ if (url.hash) return { ok: false, reason: 'CANONICAL_FRAGMENT' }
45
+ return { ok: true, url: raw }
46
+ }
47
+
48
+ export interface CanonicalResolveInput extends SeoUrlInput {
49
+ /** The editor's explicit canonical, if they stated one. */
50
+ override?: string | null
51
+ /** The application's resolver, if the site supplied one. */
52
+ resolveUrl?: SeoUrlResolver
53
+ }
54
+
55
+ /**
56
+ * The canonical for one object, in precedence order:
57
+ *
58
+ * 1. the editor's explicit override
59
+ * 2. the consuming application's resolver
60
+ * 3. nothing
61
+ *
62
+ * A resolver that throws is treated as "no answer": a site bug must not take
63
+ * a page down, and a wrong canonical is worse than an absent one.
64
+ */
65
+ export async function resolveCanonical(input: CanonicalResolveInput): Promise<string | undefined> {
66
+ if (input.override) {
67
+ const checked = validateCanonical(input.override)
68
+ return checked.ok ? checked.url : undefined
69
+ }
70
+ if (!input.resolveUrl) return undefined
71
+
72
+ let answer: string | null
73
+ try {
74
+ answer = await input.resolveUrl({
75
+ workspaceId: input.workspaceId,
76
+ type: input.type,
77
+ id: input.id,
78
+ locale: input.locale,
79
+ slug: input.slug,
80
+ ...(input.fieldValue ? { fieldValue: input.fieldValue } : {}),
81
+ })
82
+ } catch { return undefined }
83
+
84
+ if (!answer) return undefined
85
+ const checked = validateCanonical(answer)
86
+ return checked.ok ? checked.url : undefined
87
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * File Name: deployment-role.ts
3
+ * Purpose: The deployment role as the SEO extension may see it (closure plan
4
+ * Phase 9A). The platform's role service is INTERNAL to @tangen/api,
5
+ * so the extension names the shape it needs and receives the value
6
+ * through the ctx seam rather than importing across the boundary.
7
+ *
8
+ * Author: Raghunath J
9
+ * License: MIT
10
+ */
11
+
12
+ /** The three roles, or null when the deployment has not adopted one. */
13
+ export type DeploymentRoleLike = 'development' | 'staging' | 'production' | null | undefined
14
+
15
+ /** Whether this deployment is the live site. Unknown is never production. */
16
+ export function isProductionRole(role: DeploymentRoleLike): boolean {
17
+ return role === 'production'
18
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * File Name: health-report.ts
3
+ * Purpose: The SEO Manager's Dashboard numbers (plan-seo-manager-v2 V1),
4
+ * pure: one published object scored with the same checks the panel
5
+ * shows the editor (title length, description length over what is
6
+ * LIVE), the workspace summarised into a score, counts, coverage per
7
+ * type and the objects that need attention. Real data or nothing:
8
+ * an empty workspace has no score, not a fake one.
9
+ *
10
+ * Author: Raghunath J
11
+ * License: MIT
12
+ */
13
+ import { analyzeTitleLength, analyzeMetaDescLength, computeOverallScore, type SeoScore } from './seo-analysis'
14
+ import type { SeoMetadata } from '../contract'
15
+
16
+ /** Whether the object carries metadata at all, and how much of it. */
17
+ export type CoverageState = 'optimised' | 'missing-description' | 'no-metadata'
18
+
19
+ export interface ScoredObject {
20
+ id: string
21
+ type: string
22
+ title: string
23
+ score: SeoScore
24
+ state: CoverageState
25
+ /** The checks that are not good, in the panel's words. */
26
+ issues: string[]
27
+ }
28
+
29
+ export interface TypeCoverage {
30
+ type: string
31
+ total: number
32
+ optimised: number
33
+ missingDescription: number
34
+ noMetadata: number
35
+ }
36
+
37
+ export interface HealthServices {
38
+ sitemap: { entries: number; pageCount: number; truncated: boolean }
39
+ robots: { served: boolean }
40
+ llmsTxt: { enabled: boolean }
41
+ searchConsole: { connected: boolean }
42
+ }
43
+
44
+ export interface HealthReport {
45
+ generatedAt: string
46
+ scanned: number
47
+ /** 0..100 over the scanned objects; null when nothing was scanned. */
48
+ score: number | null
49
+ counts: Record<SeoScore, number>
50
+ coverage: TypeCoverage[]
51
+ services: HealthServices
52
+ }
53
+
54
+ export const HEALTH_REPORT_KEY = 'health-report'
55
+ const POINTS: Record<SeoScore, number> = { good: 100, ok: 60, poor: 0 }
56
+
57
+ /** One published object under the panel's own checks, over its LIVE metadata (the published snapshot, never a draft). */
58
+ export function scoreObject(input: { id: string; type: string; title: string | null; metadata: Pick<SeoMetadata, 'title' | 'description'> | null }): ScoredObject {
59
+ const seoTitle = input.metadata?.title?.trim() ?? ''
60
+ const description = input.metadata?.description?.trim() ?? ''
61
+ const title = seoTitle || (input.title ?? '').trim()
62
+ const checks = [analyzeTitleLength(title), analyzeMetaDescLength(description)]
63
+ const state: CoverageState = !seoTitle && !description ? 'no-metadata' : !description ? 'missing-description' : 'optimised'
64
+ return {
65
+ id: input.id, type: input.type, title: title || input.id,
66
+ score: computeOverallScore(checks), state,
67
+ issues: checks.filter((c) => c.score !== 'good').map((c) => c.message),
68
+ }
69
+ }
70
+
71
+ /** The workspace over its scored objects. */
72
+ export function summarizeHealth(objects: readonly ScoredObject[]): Pick<HealthReport, 'scanned' | 'score' | 'counts' | 'coverage'> {
73
+ const counts: Record<SeoScore, number> = { good: 0, ok: 0, poor: 0 }
74
+ const byType = new Map<string, TypeCoverage>()
75
+ for (const o of objects) {
76
+ counts[o.score] += 1
77
+ const c = byType.get(o.type) ?? { type: o.type, total: 0, optimised: 0, missingDescription: 0, noMetadata: 0 }
78
+ c.total += 1
79
+ if (o.state === 'optimised') c.optimised += 1
80
+ else if (o.state === 'missing-description') c.missingDescription += 1
81
+ else c.noMetadata += 1
82
+ byType.set(o.type, c)
83
+ }
84
+ const scanned = objects.length
85
+ const score = scanned ? Math.round(objects.reduce((sum, o) => sum + POINTS[o.score], 0) / scanned) : null
86
+ return { scanned, score, counts, coverage: [...byType.values()].sort((a, b) => b.total - a.total) }
87
+ }
88
+
89
+ /** The tone a score reads in, the panel's own thresholds. */
90
+ export function scoreTone(score: number | null): SeoScore | null {
91
+ if (score === null) return null
92
+ return score >= 80 ? 'good' : score >= 50 ? 'ok' : 'poor'
93
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * File Name: llms.ts
3
+ * Purpose: The llms.txt / llms-full.txt manifest (plan-seo-next Phase 4, GEO).
4
+ * A pure Markdown renderer that turns published content into the
5
+ * AI-crawler manifest generative engines read - the GEO equivalent of
6
+ * a sitemap. Structure only; the server supplies the content.
7
+ *
8
+ * Author: Raghunath J
9
+ * License: MIT
10
+ */
11
+
12
+ export interface LlmsItem {
13
+ title: string
14
+ url: string
15
+ /** A short summary, shown only in the -full manifest. */
16
+ summary?: string
17
+ }
18
+
19
+ export interface LlmsGroup {
20
+ label: string
21
+ items: LlmsItem[]
22
+ }
23
+
24
+ export interface LlmsInput {
25
+ siteName?: string
26
+ siteDescription?: string
27
+ groups: LlmsGroup[]
28
+ }
29
+
30
+ const clean = (v: unknown): string => (typeof v === 'string' ? v.trim() : '')
31
+
32
+ /**
33
+ * Render the manifest. `full` includes each item's summary after the link; the
34
+ * default (llms.txt) is titles and links only. Empty groups are skipped.
35
+ */
36
+ export function buildLlmsTxt(input: LlmsInput, opts: { full?: boolean } = {}): string {
37
+ const lines: string[] = []
38
+ lines.push(`# ${clean(input.siteName) || 'Site'}`)
39
+ const desc = clean(input.siteDescription)
40
+ if (desc) { lines.push(''); lines.push(`> ${desc}`) }
41
+
42
+ for (const group of input.groups) {
43
+ const items = group.items.filter((i) => clean(i.title) && clean(i.url))
44
+ if (items.length === 0) continue
45
+ lines.push('')
46
+ lines.push(`## ${clean(group.label) || 'Content'}`)
47
+ lines.push('')
48
+ for (const item of items) {
49
+ const summary = opts.full ? clean(item.summary) : ''
50
+ lines.push(`- [${clean(item.title)}](${clean(item.url)})${summary ? `: ${summary}` : ''}`)
51
+ }
52
+ }
53
+
54
+ return lines.join('\n') + '\n'
55
+ }
@@ -0,0 +1,268 @@
1
+ /**
2
+ * File Name: metadata.ts
3
+ * Purpose: The stored SEO payload and its precedence (closure plan Phase 9A,
4
+ * Units 2 and 11). Everything here is pure: no database, no ctx, no
5
+ * clock - so precedence can be argued about in a unit test rather
6
+ * than inferred from a running server.
7
+ *
8
+ * Author: Raghunath J
9
+ * License: MIT
10
+ *
11
+ * Dependencies/Notes: `extension_data` has one row per object with no locale
12
+ * column and (finding 9A-3) no working published snapshot, so this
13
+ * module carries BOTH dimensions inside the extension's own payload
14
+ * and is explicit about doing so.
15
+ */
16
+ import type { JsonLdNode, SeoLocalizedMetadata, SeoMetadata, SeoScoped, SeoStored, SeoRobots, SeoSocial } from '../contract'
17
+ import { SEO_SCHEMA_VERSION } from '../contract'
18
+
19
+ /** Locale codes we will store: BCP-47-ish, and nothing that could be a path. */
20
+ const LOCALE_PATTERN = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*$/
21
+
22
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
23
+
24
+ /** Trimmed text, or undefined - an empty override is an absence, not a value. */
25
+ function text(v: unknown): string | undefined {
26
+ if (typeof v !== 'string') return undefined
27
+ const t = v.trim()
28
+ return t === '' ? undefined : t
29
+ }
30
+
31
+ function robots(v: unknown): SeoRobots | undefined {
32
+ if (!isRecord(v)) return undefined
33
+ if (typeof v.index !== 'boolean' || typeof v.follow !== 'boolean') return undefined
34
+ return { index: v.index, follow: v.follow }
35
+ }
36
+
37
+ function social(v: unknown): SeoSocial | undefined {
38
+ if (!isRecord(v)) return undefined
39
+ const out: SeoSocial = {}
40
+ const t = text(v.title); if (t) out.title = t
41
+ const d = text(v.description); if (d) out.description = d
42
+ const i = text(v.imageId); if (i) out.imageId = i
43
+ const ty = text(v.type); if (ty) out.type = ty
44
+ const alt = text(v.imageAlt); if (alt) out.imageAlt = alt
45
+ return Object.keys(out).length ? out : undefined
46
+ }
47
+
48
+ function jsonLd(v: unknown): JsonLdNode[] | undefined {
49
+ if (!Array.isArray(v)) return undefined
50
+ const out = v.filter((n): n is JsonLdNode => isRecord(n) && typeof n['@type'] === 'string' && n['@type'].trim() !== '')
51
+ return out.length ? out : undefined
52
+ }
53
+
54
+ /** FAQ pairs: both sides required and trimmed, bounded, blanks dropped. */
55
+ const MAX_FAQS = 30
56
+ function faqs(v: unknown): { question: string; answer: string }[] | undefined {
57
+ if (!Array.isArray(v)) return undefined
58
+ const out: { question: string; answer: string }[] = []
59
+ for (const item of v) {
60
+ if (!isRecord(item)) continue
61
+ const q = text(item.question)
62
+ const a = text(item.answer)
63
+ if (q && a) out.push({ question: q, answer: a })
64
+ if (out.length >= MAX_FAQS) break
65
+ }
66
+ return out.length ? out : undefined
67
+ }
68
+
69
+ /** The localized half of a write, cleaned. */
70
+ function cleanLocalized(v: unknown): SeoLocalizedMetadata {
71
+ if (!isRecord(v)) return {}
72
+ const out: SeoLocalizedMetadata = {}
73
+ const t = text(v.title); if (t) out.title = t
74
+ const d = text(v.description); if (d) out.description = d
75
+ const c = text(v.canonicalOverride); if (c) out.canonicalOverride = c
76
+ const s = social(v.social); if (s) out.social = s
77
+ return out
78
+ }
79
+
80
+ /** A full metadata write, cleaned: unknown keys are dropped, not stored. */
81
+ function cleanMetadata(v: unknown): SeoMetadata {
82
+ if (!isRecord(v)) return {}
83
+ const out: SeoMetadata = cleanLocalized(v)
84
+ const r = robots(v.robots); if (r) out.robots = r
85
+ if (v.sitemapExclude === true) out.sitemapExclude = true
86
+ const sd = jsonLd(v.structuredData); if (sd) out.structuredData = sd
87
+ const fk = text(v.focusKeyword); if (fk) out.focusKeyword = fk
88
+ const fq = faqs(v.faqs); if (fq) out.faqs = fq
89
+ const as = text(v.answerSummary); if (as) out.answerSummary = as
90
+ return out
91
+ }
92
+
93
+ function cleanScoped(v: unknown): SeoScoped {
94
+ const src = isRecord(v) ? v : {}
95
+ const scoped: SeoScoped = { base: cleanMetadata(src.base) }
96
+ if (isRecord(src.locales)) {
97
+ const locales: Record<string, SeoLocalizedMetadata> = {}
98
+ for (const [code, value] of Object.entries(src.locales)) {
99
+ if (!LOCALE_PATTERN.test(code)) continue
100
+ const cleaned = cleanLocalized(value)
101
+ if (Object.keys(cleaned).length) locales[code] = cleaned
102
+ }
103
+ if (Object.keys(locales).length) scoped.locales = locales
104
+ }
105
+ return scoped
106
+ }
107
+
108
+ /**
109
+ * Reads whatever is in `extension_data` into the current shape. A payload
110
+ * from before this contract is a bare `SeoMetadata` and becomes the draft
111
+ * base - no migration, and nothing an editor typed is lost.
112
+ */
113
+ export function readStored(raw: unknown): SeoStored {
114
+ if (!isRecord(raw)) return { schemaVersion: SEO_SCHEMA_VERSION, draft: { base: {} } }
115
+ if (isRecord(raw.draft)) {
116
+ // A row this module has written since v1. (When SEO_SCHEMA_VERSION next
117
+ // moves, branch on raw.schemaVersion here to migrate older shapes.)
118
+ const out: SeoStored = { schemaVersion: SEO_SCHEMA_VERSION, draft: cleanScoped(raw.draft) }
119
+ if (isRecord(raw.published)) out.published = cleanScoped(raw.published)
120
+ return out
121
+ }
122
+ // Legacy (pre-versioning): the whole payload WAS the metadata.
123
+ // `seoTitle`/`metaDescription` were the old panel's own key names.
124
+ const legacy = { ...raw } as Record<string, unknown>
125
+ if (legacy.title === undefined && legacy.seoTitle !== undefined) legacy.title = legacy.seoTitle
126
+ if (legacy.description === undefined && legacy.metaDescription !== undefined) legacy.description = legacy.metaDescription
127
+ return { schemaVersion: SEO_SCHEMA_VERSION, draft: cleanScoped({ base: legacy }) }
128
+ }
129
+
130
+ /**
131
+ * Applies an editor's write to the DRAFT only. A client that sends a
132
+ * `published` key is ignored rather than trusted: publishing is a transition,
133
+ * not something a form can assert.
134
+ */
135
+ export function writeDraft(current: SeoStored, incoming: unknown): SeoStored {
136
+ const out: SeoStored = { schemaVersion: SEO_SCHEMA_VERSION, draft: cleanScoped(incoming) }
137
+ if (current.published) out.published = current.published
138
+ return out
139
+ }
140
+
141
+ /** Publish: the draft becomes what the website sees, copied by value. */
142
+ export function promoteToPublished(current: SeoStored): SeoStored {
143
+ return { schemaVersion: SEO_SCHEMA_VERSION, draft: current.draft, published: structuredClone(current.draft) }
144
+ }
145
+
146
+ /** Unpublish: the website sees nothing; the editor keeps their draft. */
147
+ export function clearPublished(current: SeoStored): SeoStored {
148
+ return { schemaVersion: SEO_SCHEMA_VERSION, draft: current.draft }
149
+ }
150
+
151
+ /**
152
+ * The sidebar panel's flat fields. It predates the scoped contract and speaks
153
+ * `seoTitle`/`metaDescription`/`focusKeyword`; the store speaks
154
+ * `{ base: { title, description, focusKeyword } }`. The two functions below are
155
+ * the ONLY bridge, so nothing an editor types is dropped at the boundary.
156
+ */
157
+ export interface SeoPanelFields {
158
+ focusKeyword?: string
159
+ seoTitle?: string
160
+ metaDescription?: string
161
+ /** FAQ pairs (base-only, shared across locales). */
162
+ faqs?: { question: string; answer: string }[]
163
+ /** The GEO answer summary (base-only). */
164
+ answerSummary?: string
165
+ /** The share image's alt text, og:image:alt (base-only; S3). */
166
+ imageAlt?: string
167
+ }
168
+
169
+ /** The per-locale slice the panel edits: only the localized text fields. */
170
+ export interface SeoPanelLocaleFields {
171
+ seoTitle?: string
172
+ metaDescription?: string
173
+ }
174
+
175
+ /** The draft scoped shape from any payload the panel may be handed. */
176
+ function draftScopedOf(raw: unknown): SeoScoped {
177
+ // The panel's own bare `{ base, locales }` emit vs the stored `{ draft, ... }`.
178
+ if (isRecord(raw) && isRecord(raw.base) && !isRecord(raw.draft)) return cleanScoped(raw)
179
+ return readStored(raw).draft
180
+ }
181
+
182
+ /** Flat panel fields -> the scoped write shape `writeDraft`/`cleanScoped` expect. */
183
+ export function panelToScoped(fields: SeoPanelFields): SeoScoped {
184
+ const base: Record<string, unknown> = {}
185
+ const t = text(fields.seoTitle); if (t) base.title = t
186
+ const d = text(fields.metaDescription); if (d) base.description = d
187
+ const fk = text(fields.focusKeyword); if (fk) base.focusKeyword = fk
188
+ if (fields.faqs?.length) base.faqs = fields.faqs
189
+ const asum = text(fields.answerSummary); if (asum) base.answerSummary = asum
190
+ const alt = text(fields.imageAlt); if (alt) base.social = { imageAlt: alt }
191
+ return { base: cleanMetadata(base) }
192
+ }
193
+
194
+ /**
195
+ * A stored payload -> the panel's flat fields for (re)hydration. Tolerant of
196
+ * every shape the panel might be handed: the stored `{ draft: { base } }`, a
197
+ * legacy flat row, and the panel's own bare `{ base }` emit (a remount before
198
+ * the next save).
199
+ */
200
+ export function scopedToPanel(raw: unknown): SeoPanelFields {
201
+ const base = draftScopedOf(raw).base
202
+ return { seoTitle: base.title ?? undefined, metaDescription: base.description ?? undefined, focusKeyword: base.focusKeyword ?? undefined, faqs: base.faqs ?? undefined, answerSummary: base.answerSummary ?? undefined, imageAlt: base.social?.imageAlt ?? undefined }
203
+ }
204
+
205
+ /**
206
+ * The locale-aware write: base fields plus a per-locale slice (title/description
207
+ * only). Because `writeDraft` REPLACES the whole draft, the panel must emit
208
+ * EVERY locale it holds - this assembles the complete `{ base, locales }` so no
209
+ * locale is silently wiped. An empty locale slice is dropped, not stored.
210
+ */
211
+ export function panelToScopedFull(base: SeoPanelFields, locales: Record<string, SeoPanelLocaleFields>): SeoScoped {
212
+ const baseScoped = panelToScoped(base)
213
+ const outLocales: Record<string, unknown> = {}
214
+ for (const [code, fields] of Object.entries(locales)) {
215
+ const loc: Record<string, unknown> = {}
216
+ const t = text(fields.seoTitle); if (t) loc.title = t
217
+ const d = text(fields.metaDescription); if (d) loc.description = d
218
+ if (Object.keys(loc).length) outLocales[code] = loc
219
+ }
220
+ return Object.keys(outLocales).length ? { base: baseScoped.base, locales: outLocales as never } : baseScoped
221
+ }
222
+
223
+ /** A stored payload -> the panel's base fields AND every locale slice. */
224
+ export function scopedToPanelFull(raw: unknown): { base: SeoPanelFields; locales: Record<string, SeoPanelLocaleFields> } {
225
+ const scoped = draftScopedOf(raw)
226
+ const base: SeoPanelFields = {
227
+ seoTitle: scoped.base.title ?? undefined,
228
+ metaDescription: scoped.base.description ?? undefined,
229
+ focusKeyword: scoped.base.focusKeyword ?? undefined,
230
+ faqs: scoped.base.faqs ?? undefined,
231
+ answerSummary: scoped.base.answerSummary ?? undefined,
232
+ imageAlt: scoped.base.social?.imageAlt ?? undefined,
233
+ }
234
+ const locales: Record<string, SeoPanelLocaleFields> = {}
235
+ for (const [code, loc] of Object.entries(scoped.locales ?? {})) {
236
+ locales[code] = { seoTitle: loc.title ?? undefined, metaDescription: loc.description ?? undefined }
237
+ }
238
+ return { base, locales }
239
+ }
240
+
241
+ /**
242
+ * One locale's metadata. Localized fields fall back to the base; SHARED
243
+ * fields (robots, sitemap exclusion, structured data) come from the base and
244
+ * only the base, whatever a locale payload claims.
245
+ */
246
+ export function pickMetadata(scoped: SeoScoped, locale?: string | null): SeoMetadata {
247
+ const override = locale ? scoped.locales?.[locale] : undefined
248
+ const localized = override ? cleanLocalized(override) : {}
249
+ return {
250
+ ...scoped.base,
251
+ ...localized,
252
+ robots: scoped.base.robots,
253
+ sitemapExclude: scoped.base.sitemapExclude,
254
+ structuredData: scoped.base.structuredData,
255
+ focusKeyword: scoped.base.focusKeyword,
256
+ faqs: scoped.base.faqs,
257
+ answerSummary: scoped.base.answerSummary,
258
+ }
259
+ }
260
+
261
+ /**
262
+ * The precedence, in one place: an editor's override, then the content's own
263
+ * field, then whatever the site offered, then nothing. "Nothing" is an
264
+ * omission - never an empty string, which would render as a blank tag.
265
+ */
266
+ export function resolveText(input: { override?: string | null; content?: string | null; fallback?: string | null }): string | undefined {
267
+ return text(input.override) ?? text(input.content) ?? text(input.fallback)
268
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * File Name: not-found.ts
3
+ * Purpose: The 404 Monitor's data rules (plan-seo-manager-v2 V5), pure.
4
+ * PATHS ONLY: a miss is normalised to a path, its query string and
5
+ * fragment dropped, and nothing about the visitor is derived or
6
+ * kept - no address, no agent, no referrer. The store holds at most
7
+ * MISS_CAP unique paths; at the cap the weakest row (fewest hits,
8
+ * then least recently seen) makes room, so a scanner spraying
9
+ * unique URLs cannot push out the miss that matters.
10
+ *
11
+ * Author: Raghunath J
12
+ * License: MIT
13
+ */
14
+
15
+ export const NOT_FOUND_PREFIX = 'notfound:'
16
+ /** Unique paths, not hits: a path is counted for as long as it is tracked. */
17
+ export const MISS_CAP = 500
18
+ export const MISS_PAGE_SIZE = 50
19
+ const MAX_PATH_LENGTH = 512
20
+
21
+ export interface MissRow {
22
+ path: string
23
+ hits: number
24
+ firstSeenAt: string
25
+ lastSeenAt: string
26
+ /** Set when an editor decided this path needs no redirect; it stops being counted and leaves the list. */
27
+ ignoredAt?: string
28
+ }
29
+
30
+ export const notFoundKey = (path: string): string => `${NOT_FOUND_PREFIX}${path}`
31
+
32
+ /**
33
+ * The path a miss is recorded under, or null when there is nothing usable.
34
+ * An absolute URL contributes its pathname only; a query string, a fragment,
35
+ * and anything past the length limit are dropped rather than stored.
36
+ */
37
+ export function normalizeMissPath(raw: unknown): string | null {
38
+ if (typeof raw !== 'string') return null
39
+ let value = raw.trim()
40
+ if (!value) return null
41
+ // An absolute URL: keep the path, drop the origin, the query and the hash.
42
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
43
+ try { value = new URL(value).pathname } catch { return null }
44
+ }
45
+ value = value.split('#')[0]!.split('?')[0]!
46
+ if (!value) return null
47
+ // One leading slash, no trailing one, no doubles.
48
+ value = `/${value.replace(/^\/+/, '')}`.replace(/\/{2,}/g, '/')
49
+ if (value.length > 1) value = value.replace(/\/+$/, '')
50
+ if (!value || value === '/') return null
51
+ if (value.length > MAX_PATH_LENGTH) return null
52
+ // A control character never belongs in a stored path.
53
+ if (/[\u0000-\u001f\u007f]/.test(value)) return null
54
+ return value
55
+ }
56
+
57
+ /** The row after one more miss on it; a first sighting starts at one hit. */
58
+ export function countMiss(existing: MissRow | null | undefined, path: string, now: Date): MissRow {
59
+ const at = now.toISOString()
60
+ if (!existing) return { path, hits: 1, firstSeenAt: at, lastSeenAt: at }
61
+ return { ...existing, path, hits: (Number(existing.hits) || 0) + 1, firstSeenAt: existing.firstSeenAt ?? at, lastSeenAt: at }
62
+ }
63
+
64
+ /** Which tracked path makes room for a new one: fewest hits, then least recently seen. Null when there is nothing to evict. */
65
+ export function weakestMiss(rows: readonly MissRow[]): MissRow | null {
66
+ if (rows.length === 0) return null
67
+ return [...rows].sort((a, b) => (a.hits - b.hits) || a.lastSeenAt.localeCompare(b.lastSeenAt) || a.path.localeCompare(b.path))[0]!
68
+ }
69
+
70
+ export type MissSort = 'hits' | 'path' | 'lastSeenAt' | 'firstSeenAt'
71
+
72
+ /** The list an editor reads: ignored rows aside, busiest first unless asked otherwise. */
73
+ export function sortMisses(rows: readonly MissRow[], opts: { includeIgnored?: boolean; sort?: MissSort; desc?: boolean } = {}): MissRow[] {
74
+ const sort = opts.sort ?? 'hits'
75
+ // Each key has the direction an editor means by default: most hits, most
76
+ // recent, but paths read A to Z.
77
+ const desc = opts.desc ?? sort !== 'path'
78
+ const compare = (a: MissRow, b: MissRow): number => {
79
+ const first = sort === 'hits' ? a.hits - b.hits : String(a[sort] ?? '').localeCompare(String(b[sort] ?? ''))
80
+ return (desc ? -first : first) || a.path.localeCompare(b.path)
81
+ }
82
+ return rows.filter((r) => (opts.includeIgnored ? true : !r.ignoredAt)).sort(compare)
83
+ }