@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.
- package/package.json +55 -4
- package/src/client.ts +48 -0
- package/src/components/SeoPanel.tsx +489 -0
- package/src/contract.ts +269 -0
- package/src/hooks.ts +74 -0
- package/src/index.ts +41 -0
- package/src/lib/alt-text.ts +59 -0
- package/src/lib/analytics.ts +236 -0
- package/src/lib/canonical.ts +87 -0
- package/src/lib/deployment-role.ts +18 -0
- package/src/lib/health-report.ts +93 -0
- package/src/lib/llms.ts +55 -0
- package/src/lib/metadata.ts +268 -0
- package/src/lib/not-found.ts +83 -0
- package/src/lib/object-url.ts +83 -0
- package/src/lib/optimize.ts +77 -0
- package/src/lib/redirects-csv.ts +84 -0
- package/src/lib/redirects.ts +178 -0
- package/src/lib/resolve.ts +157 -0
- package/src/lib/robots.ts +76 -0
- package/src/lib/schema-map.ts +66 -0
- package/src/lib/schemas.ts +114 -0
- package/src/lib/seo-analysis.ts +185 -0
- package/src/lib/seo-manager-nav.ts +72 -0
- package/src/lib/settings.ts +167 -0
- package/src/lib/sitemap-report.ts +38 -0
- package/src/lib/sitemap.ts +109 -0
- package/src/lib/structured-data.ts +93 -0
- package/src/lib/titles.ts +109 -0
- package/src/nextjs.ts +70 -0
- package/src/pages/AiGeoTab.tsx +78 -0
- package/src/pages/AnalyticsTab.tsx +192 -0
- package/src/pages/GeoTab.tsx +76 -0
- package/src/pages/NotFoundTab.tsx +120 -0
- package/src/pages/SchemasTab.tsx +134 -0
- package/src/pages/SeoManagerPage.tsx +329 -0
- package/src/pages/SettingsTab.tsx +298 -0
- package/src/pages/SitemapTab.tsx +51 -0
- package/src/pages/TitlesTab.tsx +326 -0
- package/src/pages/ToolsTab.tsx +142 -0
- package/src/pages/manager-pages.tsx +46 -0
- package/src/pages/redirects.tsx +411 -0
- package/src/server/analytics-read.ts +51 -0
- package/src/server/analytics-sync.ts +182 -0
- package/src/server/artifacts.ts +305 -0
- package/src/server/health.ts +97 -0
- package/src/server/not-found-store.ts +71 -0
- package/src/server/optimize.ts +75 -0
- package/src/server/redirect-store.ts +128 -0
- package/src/server/routes.ts +604 -0
- package/src/server/search-console.ts +148 -0
- package/src/server/sitemap-source.ts +153 -0
- package/src/server/titles.ts +88 -0
- package/src/server.ts +47 -0
- package/tangen.extension.ts +153 -0
- package/README.md +0 -3
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: artifacts.ts
|
|
3
|
+
* Purpose: The SEO artifacts a website reads - resolved metadata, robots.txt,
|
|
4
|
+
* the sitemap - and the version that makes their cache entries
|
|
5
|
+
* unreachable the moment anything they depend on changes (closure
|
|
6
|
+
* plan Phase 9A, Units 18 and 19).
|
|
7
|
+
*
|
|
8
|
+
* Author: Raghunath J
|
|
9
|
+
* License: MIT
|
|
10
|
+
*
|
|
11
|
+
* Dependencies/Notes: Invalidation is a VERSION, not a sweep. Every artifact
|
|
12
|
+
* key carries it, so one write retires every stale entry at once -
|
|
13
|
+
* the technique Phase 6B used for the schema fingerprint. The
|
|
14
|
+
* alternative, enumerating keys to delete, cannot be done correctly
|
|
15
|
+
* for a paged sitemap and would be a TTL in disguise.
|
|
16
|
+
*/
|
|
17
|
+
import { resolveSeo } from '../lib/resolve'
|
|
18
|
+
import { readStored, pickMetadata } from '../lib/metadata'
|
|
19
|
+
import { normalizeSettings, SEO_SETTINGS_KEY } from '../lib/settings'
|
|
20
|
+
import { buildSiteSchema, buildTypeSchema } from '../lib/schemas'
|
|
21
|
+
import { normalizeSchemaMap, SEO_SCHEMA_MAP_KEY } from '../lib/schema-map'
|
|
22
|
+
import { buildLlmsTxt, type LlmsGroup, type LlmsItem } from '../lib/llms'
|
|
23
|
+
import { robotsTxtFor, serializeRobotsTxt } from '../lib/robots'
|
|
24
|
+
import { buildSitemap, SITEMAP_PAGE_SIZE, type SitemapObject } from './sitemap-source'
|
|
25
|
+
import { objectUrl, urlFieldValue } from '../lib/object-url'
|
|
26
|
+
import { partitionEntries, sitemapIndexXml, sitemapXml } from '../lib/sitemap'
|
|
27
|
+
import type { ResolvedSeo, SeoHelpers } from '../contract'
|
|
28
|
+
import type { ExtensionServerCtx } from '@tangen/cms'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The key the artifact version lives under. Exported because the content
|
|
32
|
+
* hooks write it too: a hook has no server ctx, and `extensionData` and
|
|
33
|
+
* `ctx.store` are the same row addressed two ways.
|
|
34
|
+
*/
|
|
35
|
+
export const ARTIFACT_VERSION_KEY = 'artifact-version'
|
|
36
|
+
|
|
37
|
+
/** Seconds. Short: the version is what actually invalidates, this is a floor. */
|
|
38
|
+
export const ARTIFACT_TTL = 300
|
|
39
|
+
|
|
40
|
+
/** The version a stored row represents, defaulting to 1 for a scope with none. */
|
|
41
|
+
export function versionOf(row: unknown): number {
|
|
42
|
+
const v = Number((row as { v?: unknown } | undefined | null)?.v)
|
|
43
|
+
return Number.isFinite(v) && v > 0 ? v : 1
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The next version after whatever is stored. */
|
|
47
|
+
export function nextVersion(row: unknown): number {
|
|
48
|
+
return versionOf(row) + 1
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The current artifact version for this workspace x environment. */
|
|
52
|
+
export async function artifactVersion(ctx: ExtensionServerCtx): Promise<number> {
|
|
53
|
+
return versionOf(await ctx.store.get(ARTIFACT_VERSION_KEY))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Retires every cached artifact in this scope. Called when content publishes
|
|
58
|
+
* or unpublishes, when SEO metadata changes and when a redirect changes -
|
|
59
|
+
* the four things an artifact is derived from.
|
|
60
|
+
*/
|
|
61
|
+
export async function bumpArtifactVersion(ctx: ExtensionServerCtx): Promise<number> {
|
|
62
|
+
const next = (await artifactVersion(ctx)) + 1
|
|
63
|
+
await ctx.store.put(ARTIFACT_VERSION_KEY, { v: next })
|
|
64
|
+
return next
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A cache key carrying every identity the answer depends on. Phase 8A and 8B
|
|
69
|
+
* both found real leaks from a key that carried one dimension too few; the
|
|
70
|
+
* platform's own key already prefixes workspace and environment, and this
|
|
71
|
+
* adds the locale and the version.
|
|
72
|
+
*/
|
|
73
|
+
export const artifactKey = (name: string, version: number, locale?: string | null): string =>
|
|
74
|
+
`seo:${name}:v${version}:${locale ?? '-'}`
|
|
75
|
+
|
|
76
|
+
export const helpersOf = (ctx: ExtensionServerCtx): SeoHelpers => (ctx.options ?? {}) as SeoHelpers
|
|
77
|
+
|
|
78
|
+
/** The environment's role, or null - never inferred from the slug (Phase 5A). */
|
|
79
|
+
export async function roleOf(ctx: ExtensionServerCtx): Promise<'development' | 'staging' | 'production' | null> {
|
|
80
|
+
try { return (ctx.deploymentRole?.()) ?? null } catch { return null }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ── robots.txt ───────────────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
export async function robotsTxt(ctx: ExtensionServerCtx): Promise<string> {
|
|
86
|
+
const helpers = helpersOf(ctx)
|
|
87
|
+
const role = await roleOf(ctx)
|
|
88
|
+
const doc = robotsTxtFor(role, helpers)
|
|
89
|
+
// A production site's sitemap is worth naming, and only production's.
|
|
90
|
+
if (role === 'production' && helpers.siteUrl && !doc.sitemaps?.length) {
|
|
91
|
+
return serializeRobotsTxt({ ...doc, sitemaps: [`${helpers.siteUrl.replace(/\/+$/, '')}/sitemap.xml`] })
|
|
92
|
+
}
|
|
93
|
+
return serializeRobotsTxt(doc)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ── Resolved metadata ────────────────────────────────────────────────────────
|
|
97
|
+
|
|
98
|
+
export interface ResolveArgs {
|
|
99
|
+
type: string
|
|
100
|
+
id: string
|
|
101
|
+
locale?: string | null
|
|
102
|
+
/** Draft reads are for a member preview; a website always reads published. */
|
|
103
|
+
preview?: boolean
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The resolved SEO for one object. A public caller sees the PUBLISHED
|
|
108
|
+
* snapshot; there is no path from a draft edit to a public answer.
|
|
109
|
+
*/
|
|
110
|
+
export async function resolvedSeoFor(ctx: ExtensionServerCtx, args: ResolveArgs): Promise<ResolvedSeo | null> {
|
|
111
|
+
const client = ctx.tangen
|
|
112
|
+
if (!client) return null
|
|
113
|
+
|
|
114
|
+
let object: Record<string, unknown>
|
|
115
|
+
try {
|
|
116
|
+
const res = await client.objects(args.type as never).status('any').find(args.id)
|
|
117
|
+
object = res.data as Record<string, unknown>
|
|
118
|
+
} catch { return null }
|
|
119
|
+
if (!object) return null
|
|
120
|
+
|
|
121
|
+
const published = String(object.status ?? '') === 'published'
|
|
122
|
+
if (!published && !args.preview) return null
|
|
123
|
+
|
|
124
|
+
const stored = readStored(await ctx.store.get(args.id))
|
|
125
|
+
const scoped = args.preview ? stored.draft : (stored.published ?? { base: {} })
|
|
126
|
+
|
|
127
|
+
const helpers = helpersOf(ctx)
|
|
128
|
+
const settings = normalizeSettings(await ctx.store.get(SEO_SETTINGS_KEY))
|
|
129
|
+
// The share image is the object's own, then the workspace default from settings.
|
|
130
|
+
const imageId = pickMetadata(scoped, args.locale).social?.imageId ?? settings.social.defaultImageId ?? null
|
|
131
|
+
const socialImageUrl = await resolveMediaUrl(ctx, imageId)
|
|
132
|
+
// The site-level entity graph (Organization + WebSite) from settings, carried
|
|
133
|
+
// on every page. The app owns the origin (helpers.siteUrl) and the logo URL.
|
|
134
|
+
const logoUrl = await resolveMediaUrl(ctx, settings.organization.logoId ?? null)
|
|
135
|
+
const siteSchema = buildSiteSchema(settings, { siteUrl: helpers.siteUrl, logoUrl: logoUrl ?? undefined })
|
|
136
|
+
|
|
137
|
+
// The generated per-content-type node (Article, Product, ...) from the map.
|
|
138
|
+
const slug = (object.slug as string | null) ?? null
|
|
139
|
+
const schemaMap = normalizeSchemaMap(await ctx.store.get(SEO_SCHEMA_MAP_KEY))
|
|
140
|
+
const typeConfig = schemaMap[args.type]
|
|
141
|
+
// One answer, used by the canonical, the type schema and anything else here:
|
|
142
|
+
// the site's resolver first, then the field it declared for this type.
|
|
143
|
+
const resolvedPageUrl = await objectUrl({
|
|
144
|
+
helpers, workspaceId: ctx.workspaceId, type: args.type, id: args.id, locale: args.locale, slug,
|
|
145
|
+
fieldValue: urlFieldValue(helpers, args.type, object),
|
|
146
|
+
})
|
|
147
|
+
const pageUrl = resolvedPageUrl ?? undefined
|
|
148
|
+
const typeSchema = typeConfig
|
|
149
|
+
? buildTypeSchema(typeConfig, {
|
|
150
|
+
object,
|
|
151
|
+
title: (object.title as string | null) ?? undefined,
|
|
152
|
+
url: pageUrl,
|
|
153
|
+
organizationName: settings.organization.name,
|
|
154
|
+
})
|
|
155
|
+
: null
|
|
156
|
+
|
|
157
|
+
return resolveSeo({
|
|
158
|
+
workspaceId: ctx.workspaceId,
|
|
159
|
+
type: args.type,
|
|
160
|
+
id: args.id,
|
|
161
|
+
locale: args.locale,
|
|
162
|
+
slug,
|
|
163
|
+
scoped,
|
|
164
|
+
published,
|
|
165
|
+
content: { title: (object.title as string | null) ?? null },
|
|
166
|
+
pageUrl: resolvedPageUrl,
|
|
167
|
+
helpers,
|
|
168
|
+
socialImageUrl,
|
|
169
|
+
robotsDefault: { index: settings.robots.defaultIndex, follow: settings.robots.defaultFollow },
|
|
170
|
+
siteSchema,
|
|
171
|
+
typeSchema,
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* An absolute media URL, from the application's resolver. Without one the
|
|
177
|
+
* image is omitted: an internal storage path is not a social image URL, and
|
|
178
|
+
* Tangen does not know the site's CDN.
|
|
179
|
+
*/
|
|
180
|
+
async function resolveMediaUrl(ctx: ExtensionServerCtx, mediaId: string | null): Promise<string | null> {
|
|
181
|
+
if (!mediaId) return null
|
|
182
|
+
const resolver = helpersOf(ctx).resolveMediaUrl
|
|
183
|
+
if (!resolver) return null
|
|
184
|
+
try { return (await resolver({ workspaceId: ctx.workspaceId, mediaId })) ?? null } catch { return null }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ── Sitemap ──────────────────────────────────────────────────────────────────
|
|
188
|
+
|
|
189
|
+
/** Published objects, one bounded page at a time. */
|
|
190
|
+
export async function* publishedObjects(ctx: ExtensionServerCtx, types: string[]): AsyncGenerator<SitemapObject[]> {
|
|
191
|
+
const client = ctx.tangen
|
|
192
|
+
if (!client) return
|
|
193
|
+
for (const type of types) {
|
|
194
|
+
let offset = 0
|
|
195
|
+
for (;;) {
|
|
196
|
+
let rows: Record<string, unknown>[] = []
|
|
197
|
+
try {
|
|
198
|
+
const res = await client.objects(type as never).status('published')
|
|
199
|
+
.sort('id', 'asc').limit(SITEMAP_PAGE_SIZE).offset(offset).get()
|
|
200
|
+
rows = (res.data ?? []) as Record<string, unknown>[]
|
|
201
|
+
} catch { break }
|
|
202
|
+
if (rows.length === 0) break
|
|
203
|
+
yield rows.map((r) => ({
|
|
204
|
+
id: String(r.id),
|
|
205
|
+
type,
|
|
206
|
+
slug: (r.slug as string | null) ?? null,
|
|
207
|
+
title: (r.title as string | null) ?? null,
|
|
208
|
+
urlFieldValue: urlFieldValue(helpersOf(ctx), type, r),
|
|
209
|
+
updatedAt: (r.updated_at ?? r.updatedAt) as string | null,
|
|
210
|
+
publishedAt: (r.published_at ?? r.publishedAt) as string | null,
|
|
211
|
+
}))
|
|
212
|
+
if (rows.length < SITEMAP_PAGE_SIZE) break
|
|
213
|
+
offset += SITEMAP_PAGE_SIZE
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The llms.txt / llms-full.txt manifest, or null when the GEO toggle is off (so
|
|
220
|
+
* the route 404s rather than serving an empty file). Enumerates published
|
|
221
|
+
* objects per eligible type, resolves each page url via the app's resolver, and
|
|
222
|
+
* groups by type. The -full variant adds each object's own summary field.
|
|
223
|
+
*/
|
|
224
|
+
export async function buildLlmsManifest(ctx: ExtensionServerCtx, opts: { full?: boolean }): Promise<string | null> {
|
|
225
|
+
const settings = normalizeSettings(await ctx.store.get(SEO_SETTINGS_KEY))
|
|
226
|
+
if (!settings.geo.llmsTxtEnabled) return null
|
|
227
|
+
|
|
228
|
+
const helpers = helpersOf(ctx)
|
|
229
|
+
const client = ctx.tangen
|
|
230
|
+
const typeLabels = new Map<string, string>()
|
|
231
|
+
try { for (const t of ctx.types?.() ?? []) typeLabels.set(t.name, (t as { label?: string }).label ?? t.name) } catch { /* names only */ }
|
|
232
|
+
|
|
233
|
+
const groups: LlmsGroup[] = []
|
|
234
|
+
if (client && helpers.resolveUrl) {
|
|
235
|
+
for (const type of sitemapTypes(ctx)) {
|
|
236
|
+
const items: LlmsItem[] = []
|
|
237
|
+
let offset = 0
|
|
238
|
+
for (;;) {
|
|
239
|
+
let rows: Record<string, unknown>[] = []
|
|
240
|
+
try {
|
|
241
|
+
const res = await client.objects(type as never).status('published').sort('id', 'asc').limit(SITEMAP_PAGE_SIZE).offset(offset).get()
|
|
242
|
+
rows = (res.data ?? []) as Record<string, unknown>[]
|
|
243
|
+
} catch { break }
|
|
244
|
+
if (rows.length === 0) break
|
|
245
|
+
for (const row of rows) {
|
|
246
|
+
const id = String(row.id)
|
|
247
|
+
let url: string | null = null
|
|
248
|
+
try {
|
|
249
|
+
url = await objectUrl({
|
|
250
|
+
helpers, workspaceId: ctx.workspaceId, type, id, locale: null,
|
|
251
|
+
slug: (row.slug as string | null) ?? null, fieldValue: urlFieldValue(helpers, type, row),
|
|
252
|
+
})
|
|
253
|
+
} catch { /* app owns urls */ }
|
|
254
|
+
if (!url) continue
|
|
255
|
+
const item: LlmsItem = { title: (row.title as string) || id, url }
|
|
256
|
+
if (opts.full) {
|
|
257
|
+
const summary = (row.excerpt ?? row.summary ?? row.description ?? row.metaDescription)
|
|
258
|
+
if (typeof summary === 'string' && summary.trim()) item.summary = summary.trim()
|
|
259
|
+
}
|
|
260
|
+
items.push(item)
|
|
261
|
+
}
|
|
262
|
+
if (rows.length < SITEMAP_PAGE_SIZE) break
|
|
263
|
+
offset += SITEMAP_PAGE_SIZE
|
|
264
|
+
}
|
|
265
|
+
if (items.length) groups.push({ label: typeLabels.get(type) ?? type, items })
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
return buildLlmsTxt({ siteName: settings.general.siteName, groups }, opts)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The types a sitemap considers: the site's list, or every type it has. */
|
|
273
|
+
export function sitemapTypes(ctx: ExtensionServerCtx): string[] {
|
|
274
|
+
const declared = helpersOf(ctx).sitemapTypes
|
|
275
|
+
if (declared?.length) return declared
|
|
276
|
+
try { return (ctx.types?.() ?? []).map((t) => t.name) } catch { return [] }
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export async function sitemapBuild(ctx: ExtensionServerCtx, locale?: string | null) {
|
|
280
|
+
return buildSitemap({
|
|
281
|
+
workspaceId: ctx.workspaceId,
|
|
282
|
+
locale,
|
|
283
|
+
helpers: helpersOf(ctx),
|
|
284
|
+
store: ctx.store,
|
|
285
|
+
objects: publishedObjects(ctx, sitemapTypes(ctx)),
|
|
286
|
+
resolveUrl: helpersOf(ctx).resolveUrl,
|
|
287
|
+
})
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** One sitemap page as XML, plus how many pages there are in total. */
|
|
291
|
+
export async function sitemapPageXml(ctx: ExtensionServerCtx, page: number, locale?: string | null) {
|
|
292
|
+
const build = await sitemapBuild(ctx, locale)
|
|
293
|
+
const pages = partitionEntries(build.entries)
|
|
294
|
+
const index = Math.max(1, Math.floor(page))
|
|
295
|
+
return { xml: sitemapXml(pages[index - 1] ?? []), pageCount: pages.length, build }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** The index over the pages, using the site's own origin for each reference. */
|
|
299
|
+
export async function sitemapIndex(ctx: ExtensionServerCtx, locale?: string | null) {
|
|
300
|
+
const build = await sitemapBuild(ctx, locale)
|
|
301
|
+
const pages = partitionEntries(build.entries)
|
|
302
|
+
const base = (helpersOf(ctx).siteUrl ?? '').replace(/\/+$/, '')
|
|
303
|
+
const refs = pages.map((_, i) => ({ loc: `${base}/sitemap.xml?page=${i + 1}` }))
|
|
304
|
+
return { xml: sitemapIndexXml(refs), pageCount: pages.length, build }
|
|
305
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: health.ts
|
|
3
|
+
* Purpose: Builds the Dashboard's health report (plan-seo-manager-v2 V1)
|
|
4
|
+
* from what the workspace has: the published objects the sitemap
|
|
5
|
+
* scans, their LIVE metadata read in one pass over the store, the
|
|
6
|
+
* sitemap report, the GEO switch and whether a Search Console
|
|
7
|
+
* connection exists. Stored under HEALTH_REPORT_KEY so the
|
|
8
|
+
* workspace dashboard's widget reads the last one without a scan.
|
|
9
|
+
*
|
|
10
|
+
* Author: Raghunath J
|
|
11
|
+
* License: MIT
|
|
12
|
+
*/
|
|
13
|
+
import type { ExtensionServerCtx } from '@tangen/cms'
|
|
14
|
+
import { SEARCH_CONSOLE_CAPABILITY } from './search-console'
|
|
15
|
+
import { publishedObjects, sitemapIndex, sitemapTypes } from './artifacts'
|
|
16
|
+
import { pickMetadata, readStored } from '../lib/metadata'
|
|
17
|
+
import { normalizeSettings, SEO_SETTINGS_KEY } from '../lib/settings'
|
|
18
|
+
import { HEALTH_REPORT_KEY, scoreObject, scoreTone, summarizeHealth, type HealthReport, type ScoredObject } from '../lib/health-report'
|
|
19
|
+
|
|
20
|
+
/** The scan stops here: a report over the first 20,000 published objects is a report, an unbounded one is an outage. */
|
|
21
|
+
export const HEALTH_SCAN_LIMIT = 20_000
|
|
22
|
+
const STORE_PAGE = 1000
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* F2: whether Search Console is READABLE here, which is no longer a question
|
|
26
|
+
* about one connector id. The platform's own derivation answers it - the pack
|
|
27
|
+
* present, a connection made, and that connection authorized for the one
|
|
28
|
+
* capability this extension needs - so the tile cannot disagree with the
|
|
29
|
+
* Connections page about what is connected.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** Whether Search Console can be read here; false when anything in the chain is missing. */
|
|
33
|
+
export async function searchConsoleConnected(ctx: ExtensionServerCtx): Promise<boolean> {
|
|
34
|
+
if (!ctx.connections) return false
|
|
35
|
+
try {
|
|
36
|
+
const available = await ctx.connections.availability?.(SEARCH_CONSOLE_CAPABILITY)
|
|
37
|
+
return available?.state === 'ready'
|
|
38
|
+
} catch { return false }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The workspace dashboard's tile (V8): the LAST report this extension wrote,
|
|
43
|
+
* shaped as the platform's stat-group widget. It never scans - a dashboard
|
|
44
|
+
* must not pay for a content sweep - so before the first check it says so.
|
|
45
|
+
*/
|
|
46
|
+
export async function healthWidget(ctx: ExtensionServerCtx): Promise<{ stats: Array<{ label: string; value: number; tone?: 'success' | 'warning' | 'danger' | 'neutral'; href?: string }> }> {
|
|
47
|
+
const report = (await ctx.store.get(HEALTH_REPORT_KEY)) as unknown as HealthReport | undefined
|
|
48
|
+
if (!report || typeof report.scanned !== 'number') return { stats: [] }
|
|
49
|
+
const tone = scoreTone(report.score)
|
|
50
|
+
return {
|
|
51
|
+
stats: [
|
|
52
|
+
{ label: 'Health score', value: report.score ?? 0, ...(tone ? { tone: tone === 'good' ? 'success' as const : tone === 'ok' ? 'warning' as const : 'danger' as const } : {}), href: 'extensions/seo' },
|
|
53
|
+
{ label: 'Needs work', value: report.counts.ok, tone: 'warning' as const, href: 'extensions/seo/titles?state=needs-work' },
|
|
54
|
+
{ label: 'No metadata', value: report.counts.poor, tone: 'danger' as const, href: 'extensions/seo/titles?state=missing' },
|
|
55
|
+
{ label: 'Published pages', value: report.scanned, tone: 'neutral' as const },
|
|
56
|
+
],
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function buildHealthReport(ctx: ExtensionServerCtx): Promise<HealthReport> {
|
|
61
|
+
// 1. The published objects, the way the sitemap sees them (bounded).
|
|
62
|
+
const objects: Array<{ id: string; type: string; title: string | null }> = []
|
|
63
|
+
scan: for await (const page of publishedObjects(ctx, sitemapTypes(ctx))) {
|
|
64
|
+
for (const o of page) {
|
|
65
|
+
objects.push({ id: o.id, type: o.type, title: o.title ?? null })
|
|
66
|
+
if (objects.length >= HEALTH_SCAN_LIMIT) break scan
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// 2. Their live metadata, one pass over the store rather than one read per object.
|
|
70
|
+
const wanted = new Set(objects.map((o) => o.id))
|
|
71
|
+
const live = new Map<string, ReturnType<typeof pickMetadata>>()
|
|
72
|
+
for (let offset = 0; ; offset += STORE_PAGE) {
|
|
73
|
+
const rows = await ctx.store.list('', { limit: STORE_PAGE, offset })
|
|
74
|
+
for (const row of rows) {
|
|
75
|
+
if (!wanted.has(row.key)) continue
|
|
76
|
+
const published = readStored(row.data).published
|
|
77
|
+
if (published) live.set(row.key, pickMetadata(published, null))
|
|
78
|
+
}
|
|
79
|
+
if (rows.length < STORE_PAGE) break
|
|
80
|
+
}
|
|
81
|
+
const scored: ScoredObject[] = objects.map((o) => scoreObject({ id: o.id, type: o.type, title: o.title, metadata: live.get(o.id) ?? null }))
|
|
82
|
+
// 3. The services around the content.
|
|
83
|
+
const settings = normalizeSettings(await ctx.store.get(SEO_SETTINGS_KEY))
|
|
84
|
+
const { build, pageCount } = await sitemapIndex(ctx, null)
|
|
85
|
+
const report: HealthReport = {
|
|
86
|
+
generatedAt: new Date().toISOString(),
|
|
87
|
+
...summarizeHealth(scored),
|
|
88
|
+
services: {
|
|
89
|
+
sitemap: { entries: build.entries.length, pageCount, truncated: build.truncated },
|
|
90
|
+
robots: { served: true },
|
|
91
|
+
llmsTxt: { enabled: settings.geo.llmsTxtEnabled },
|
|
92
|
+
searchConsole: { connected: await searchConsoleConnected(ctx) },
|
|
93
|
+
},
|
|
94
|
+
}
|
|
95
|
+
await ctx.store.put(HEALTH_REPORT_KEY, report as unknown as Record<string, unknown>)
|
|
96
|
+
return report
|
|
97
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: not-found-store.ts
|
|
3
|
+
* Purpose: The 404 Monitor's store (plan-seo-manager-v2 V5). The public
|
|
4
|
+
* redirect lookup a site calls on a miss already knows every path
|
|
5
|
+
* that did not resolve; this counts it in the extension's own
|
|
6
|
+
* store, paths only, capped at MISS_CAP unique paths. Recording is
|
|
7
|
+
* best effort: a site's 404 must never fail because bookkeeping
|
|
8
|
+
* did.
|
|
9
|
+
*
|
|
10
|
+
* Author: Raghunath J
|
|
11
|
+
* License: MIT
|
|
12
|
+
*/
|
|
13
|
+
import type { ExtensionStore } from '@tangen/cms'
|
|
14
|
+
import {
|
|
15
|
+
countMiss, MISS_CAP, MISS_PAGE_SIZE, normalizeMissPath, notFoundKey,
|
|
16
|
+
NOT_FOUND_PREFIX, sortMisses, weakestMiss, type MissRow, type MissSort,
|
|
17
|
+
} from '../lib/not-found'
|
|
18
|
+
|
|
19
|
+
const allRows = async (store: ExtensionStore): Promise<MissRow[]> =>
|
|
20
|
+
(await store.list(NOT_FOUND_PREFIX, { limit: MISS_CAP + 50 })).map((r) => r.data as unknown as MissRow).filter((r) => typeof r?.path === 'string')
|
|
21
|
+
|
|
22
|
+
/** Counts one miss. Returns the stored path, or null when nothing was recorded. */
|
|
23
|
+
export async function recordNotFound(store: ExtensionStore, rawPath: unknown, now = new Date()): Promise<string | null> {
|
|
24
|
+
const path = normalizeMissPath(rawPath)
|
|
25
|
+
if (!path) return null
|
|
26
|
+
const existing = (await store.get(notFoundKey(path))) as unknown as MissRow | undefined
|
|
27
|
+
// An ignored path stays ignored: it is a decision, not a gap in the data.
|
|
28
|
+
if (existing?.ignoredAt) return null
|
|
29
|
+
if (!existing) {
|
|
30
|
+
const rows = await allRows(store)
|
|
31
|
+
if (rows.length >= MISS_CAP) {
|
|
32
|
+
const weakest = weakestMiss(rows)
|
|
33
|
+
// Nothing weaker than a first sighting: leave the list as it is.
|
|
34
|
+
if (!weakest || weakest.hits > 1) return null
|
|
35
|
+
await store.remove(notFoundKey(weakest.path))
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
await store.put(notFoundKey(path), countMiss(existing ?? null, path, now) as never)
|
|
39
|
+
return path
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function listNotFound(
|
|
43
|
+
store: ExtensionStore,
|
|
44
|
+
opts: { limit?: number; offset?: number; includeIgnored?: boolean; sort?: MissSort; desc?: boolean } = {},
|
|
45
|
+
): Promise<{ rows: MissRow[]; total: number; tracked: number; cap: number }> {
|
|
46
|
+
const tracked = await allRows(store)
|
|
47
|
+
const rows = sortMisses(tracked, { includeIgnored: opts.includeIgnored, ...(opts.sort ? { sort: opts.sort } : {}), ...(opts.desc !== undefined ? { desc: opts.desc } : {}) })
|
|
48
|
+
const offset = Math.max(0, Math.floor(opts.offset ?? 0))
|
|
49
|
+
const limit = Math.max(1, Math.min(Math.floor(opts.limit ?? MISS_PAGE_SIZE), 200))
|
|
50
|
+
return { rows: rows.slice(offset, offset + limit), total: rows.length, tracked: tracked.length, cap: MISS_CAP }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Marks a path as needing nothing: it leaves the list and stops being counted. */
|
|
54
|
+
export async function ignoreNotFound(store: ExtensionStore, rawPath: unknown, now = new Date()): Promise<MissRow | null> {
|
|
55
|
+
const path = normalizeMissPath(rawPath)
|
|
56
|
+
if (!path) return null
|
|
57
|
+
const existing = (await store.get(notFoundKey(path))) as unknown as MissRow | undefined
|
|
58
|
+
if (!existing) return null
|
|
59
|
+
const row: MissRow = { ...existing, ignoredAt: now.toISOString() }
|
|
60
|
+
await store.put(notFoundKey(path), row as never)
|
|
61
|
+
return row
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Forgets a path entirely; it will be counted again if it is requested again. */
|
|
65
|
+
export async function clearNotFound(store: ExtensionStore, rawPath: unknown): Promise<boolean> {
|
|
66
|
+
const path = normalizeMissPath(rawPath)
|
|
67
|
+
if (!path) return false
|
|
68
|
+
if (!(await store.get(notFoundKey(path)))) return false
|
|
69
|
+
await store.remove(notFoundKey(path))
|
|
70
|
+
return true
|
|
71
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: optimize.ts
|
|
3
|
+
* Purpose: The AI optimisation ACTION (plan-seo-manager-v2 V6, user decision
|
|
4
|
+
* 5): one object in, a PROPOSAL out. It never touches the published
|
|
5
|
+
* snapshot; `apply` writes the draft, which is what Tangen publishes
|
|
6
|
+
* next, so a human still sees it before a visitor does. One object
|
|
7
|
+
* per call by design - a later bulk run walks selected objects
|
|
8
|
+
* through this same function rather than growing a second path.
|
|
9
|
+
*
|
|
10
|
+
* Author: Raghunath J
|
|
11
|
+
* License: MIT
|
|
12
|
+
*/
|
|
13
|
+
import type { ExtensionServerCtx } from '@tangen/cms'
|
|
14
|
+
import { cleanProposal, optimizePrompt, OPTIMIZE_SCHEMA, OPTIMIZE_SYSTEM, type SeoProposal } from '../lib/optimize'
|
|
15
|
+
import { pickMetadata, readStored, writeDraft } from '../lib/metadata'
|
|
16
|
+
|
|
17
|
+
export type OptimizeResult =
|
|
18
|
+
| { ok: true; proposal: SeoProposal; applied: boolean; provider: string; model: string }
|
|
19
|
+
| { ok: false; reason: string }
|
|
20
|
+
|
|
21
|
+
/** The text a provider is given: the object's own string fields, nothing fetched. */
|
|
22
|
+
function contentOf(object: Record<string, unknown>): string {
|
|
23
|
+
return Object.entries(object)
|
|
24
|
+
.filter(([key, value]) => typeof value === 'string' && !['id', 'slug', 'status', 'title'].includes(key))
|
|
25
|
+
.map(([, value]) => value as string)
|
|
26
|
+
.join(' ')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Proposes SEO values for one object. With `apply` the proposal is written to
|
|
31
|
+
* the object's DRAFT (never its published snapshot); without it nothing is
|
|
32
|
+
* stored and the caller shows the proposal for review.
|
|
33
|
+
*/
|
|
34
|
+
export async function optimizeObject(ctx: ExtensionServerCtx, input: { type: string; id: string; apply?: boolean; locale?: string | null }): Promise<OptimizeResult> {
|
|
35
|
+
const type = String(input.type ?? '').trim()
|
|
36
|
+
const id = String(input.id ?? '').trim()
|
|
37
|
+
if (!type || !id) return { ok: false, reason: 'type and id are required' }
|
|
38
|
+
if (!ctx.ai?.generateJSON) return { ok: false, reason: 'Writing metadata with AI needs the ai:generate grant and an AI provider: approve the grant with `tangen extension upgrade seo --approve-optional ai:generate`, then choose a provider under Settings > AI.' }
|
|
39
|
+
if (!ctx.tangen) return { ok: false, reason: 'The content client is not available to this extension.' }
|
|
40
|
+
|
|
41
|
+
let object: Record<string, unknown>
|
|
42
|
+
try {
|
|
43
|
+
const res = await ctx.tangen.objects(type as never).status('any').find(id)
|
|
44
|
+
object = (res.data ?? {}) as Record<string, unknown>
|
|
45
|
+
} catch { return { ok: false, reason: `No ${type} with id ${id}.` } }
|
|
46
|
+
|
|
47
|
+
const stored = readStored(await ctx.store.get(id))
|
|
48
|
+
const current = pickMetadata(stored.draft, input.locale ?? null)
|
|
49
|
+
let generated: { value: unknown; provider: string; model: string }
|
|
50
|
+
try {
|
|
51
|
+
generated = await ctx.ai.generateJSON({
|
|
52
|
+
system: OPTIMIZE_SYSTEM,
|
|
53
|
+
prompt: optimizePrompt({
|
|
54
|
+
title: (object.title as string | null) ?? null,
|
|
55
|
+
content: contentOf(object),
|
|
56
|
+
focusKeyword: current.focusKeyword ?? null,
|
|
57
|
+
locale: input.locale ?? null,
|
|
58
|
+
}),
|
|
59
|
+
jsonSchema: OPTIMIZE_SCHEMA,
|
|
60
|
+
})
|
|
61
|
+
} catch (e) {
|
|
62
|
+
return { ok: false, reason: (e as Error).message }
|
|
63
|
+
}
|
|
64
|
+
const proposal = cleanProposal(generated.value)
|
|
65
|
+
if (!proposal.title && !proposal.description) return { ok: false, reason: 'The provider returned nothing usable for this page.' }
|
|
66
|
+
|
|
67
|
+
if (input.apply) {
|
|
68
|
+
const base: Record<string, unknown> = { ...stored.draft.base }
|
|
69
|
+
if (proposal.title) base.title = proposal.title
|
|
70
|
+
if (proposal.description) base.description = proposal.description
|
|
71
|
+
if (proposal.answerSummary) base.answerSummary = proposal.answerSummary
|
|
72
|
+
await ctx.store.put(id, writeDraft(stored, { ...stored.draft, base }) as unknown as Record<string, unknown>)
|
|
73
|
+
}
|
|
74
|
+
return { ok: true, proposal, applied: Boolean(input.apply), provider: generated.provider, model: generated.model }
|
|
75
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: redirect-store.ts
|
|
3
|
+
* Purpose: Where redirects live (closure plan Phase 9A, Units 8, 17 and 20).
|
|
4
|
+
* The platform's own extension store, keyed by the normalized source,
|
|
5
|
+
* so a lookup is ONE indexed row read and a duplicate source cannot
|
|
6
|
+
* be created at all.
|
|
7
|
+
*
|
|
8
|
+
* Author: Raghunath J
|
|
9
|
+
* License: MIT
|
|
10
|
+
*
|
|
11
|
+
* Dependencies/Notes: No extension migrations and no new tables. `ctx.store`
|
|
12
|
+
* is `extension_data` with `object_id` as the key, under the unique
|
|
13
|
+
* index (extension_id, object_id, workspace_id) - already
|
|
14
|
+
* workspace and environment scoped, and already indexed for exactly
|
|
15
|
+
* the read a redirect resolver performs. A dedicated table would have
|
|
16
|
+
* been a second, weaker copy of it; the Phase 9A report says so
|
|
17
|
+
* rather than adding schema for the appearance of rigour.
|
|
18
|
+
*/
|
|
19
|
+
import { normalizeSource, normalizeSourcePath, redirectKey, validateRedirect, detectCycle, type RedirectCheck, type SeoRedirect } from '../lib/redirects'
|
|
20
|
+
import type { ExtensionStore } from '@tangen/cms'
|
|
21
|
+
|
|
22
|
+
export const REDIRECT_PREFIX = 'redirect:'
|
|
23
|
+
|
|
24
|
+
/** How many redirects the Admin list will page through at once. */
|
|
25
|
+
export const REDIRECT_PAGE_SIZE = 50
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* ONE indexed row read: the primary lookup a request path performs. Nothing
|
|
29
|
+
* is loaded into process memory, and the answer does not depend on how many
|
|
30
|
+
* redirects the workspace has.
|
|
31
|
+
*/
|
|
32
|
+
export async function findRedirect(store: ExtensionStore, path: string): Promise<SeoRedirect | null> {
|
|
33
|
+
// A rule that names a query string is exact; otherwise the visitor's query
|
|
34
|
+
// is not part of what was moved, so the rule for the PATH answers. That is
|
|
35
|
+
// what makes `/old-page?utm_source=mail` reach the `/old-page` redirect.
|
|
36
|
+
const exact = await store.get(redirectKey(path))
|
|
37
|
+
const row = exact ?? await store.get(redirectKey(normalizeSourcePath(path)))
|
|
38
|
+
if (!row) return null
|
|
39
|
+
const redirect = row as unknown as SeoRedirect
|
|
40
|
+
return redirect.enabled === false ? null : redirect
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function listRedirects(
|
|
44
|
+
store: ExtensionStore,
|
|
45
|
+
opts: { limit?: number; offset?: number; sort?: 'source' | 'updatedAt'; desc?: boolean } = {},
|
|
46
|
+
): Promise<{ rows: SeoRedirect[]; total: number }> {
|
|
47
|
+
const [entries, total] = await Promise.all([
|
|
48
|
+
store.list(REDIRECT_PREFIX, { orderByDataKey: opts.sort ?? 'source', ...(opts.desc ? { desc: true } : {}), limit: opts.limit ?? REDIRECT_PAGE_SIZE, offset: opts.offset ?? 0 }),
|
|
49
|
+
store.count ? store.count(REDIRECT_PREFIX) : Promise.resolve(-1),
|
|
50
|
+
])
|
|
51
|
+
const rows = entries.map((e) => e.data as unknown as SeoRedirect)
|
|
52
|
+
return { rows, total: total >= 0 ? total : rows.length }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type SaveResult = { ok: true; redirect: SeoRedirect } | { ok: false; reason: string; detail?: unknown }
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Writes one redirect. Everything that can be refused is refused HERE - the
|
|
59
|
+
* route is a thin caller - so the same rules apply to the Admin, to the CLI
|
|
60
|
+
* and to anything else that ever writes one.
|
|
61
|
+
*/
|
|
62
|
+
export async function saveRedirect(
|
|
63
|
+
store: ExtensionStore,
|
|
64
|
+
input: Partial<SeoRedirect> & { source: string },
|
|
65
|
+
opts: { replacing?: string; siteUrl?: string; now: string } = { now: new Date(0).toISOString() },
|
|
66
|
+
): Promise<SaveResult> {
|
|
67
|
+
// Validate what the editor TYPED, then normalise for storage. Normalising
|
|
68
|
+
// first made `SOURCE_EMPTY` and `SOURCE_NOT_A_PATH` unreachable through the
|
|
69
|
+
// route: an empty From became "/" and would have redirected the home page.
|
|
70
|
+
const typed = String(input.source ?? '')
|
|
71
|
+
const source = normalizeSource(typed)
|
|
72
|
+
const candidate: SeoRedirect = {
|
|
73
|
+
source,
|
|
74
|
+
destination: input.destination as SeoRedirect['destination'],
|
|
75
|
+
status: (input.status ?? 301) as SeoRedirect['status'],
|
|
76
|
+
enabled: input.enabled !== false,
|
|
77
|
+
// Absent means "carry it"; only an explicit false is stored.
|
|
78
|
+
...(input.keepQuery === false ? { keepQuery: false } : {}),
|
|
79
|
+
createdAt: input.createdAt ?? opts.now,
|
|
80
|
+
updatedAt: opts.now,
|
|
81
|
+
...(input.note ? { note: String(input.note).slice(0, 500) } : {}),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const checked: RedirectCheck = validateRedirect({ ...candidate, source: typed, siteUrl: opts.siteUrl })
|
|
85
|
+
if (!checked.ok) return { ok: false, reason: checked.reason }
|
|
86
|
+
|
|
87
|
+
// One source, one redirect: the key IS the source, so a duplicate is a
|
|
88
|
+
// collision rather than a second row nobody can tell apart.
|
|
89
|
+
const replacingKey = opts.replacing ? redirectKey(opts.replacing) : null
|
|
90
|
+
const key = redirectKey(source)
|
|
91
|
+
if (key !== replacingKey && (await store.get(key))) return { ok: false, reason: 'DUPLICATE_SOURCE' }
|
|
92
|
+
|
|
93
|
+
// Bounded cycle check across what is already stored. Explicitly bounded -
|
|
94
|
+
// this is a guard against the obvious mistake, not a graph analysis.
|
|
95
|
+
if (candidate.destination?.kind === 'external' || candidate.destination?.kind === 'path') {
|
|
96
|
+
const existing = await loadChain(store)
|
|
97
|
+
let destPath: string | null = null
|
|
98
|
+
if (candidate.destination.kind === 'path') destPath = normalizeSourcePath(candidate.destination.path)
|
|
99
|
+
else try { destPath = new URL(candidate.destination.url).pathname } catch { destPath = null }
|
|
100
|
+
if (destPath) {
|
|
101
|
+
const cycle = detectCycle(source, destPath, existing)
|
|
102
|
+
if (cycle.cycle) return { ok: false, reason: 'REDIRECT_LOOP', detail: cycle.path }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (replacingKey && replacingKey !== key) await store.remove(replacingKey)
|
|
107
|
+
await store.put(key, candidate as unknown as Record<string, unknown>)
|
|
108
|
+
return { ok: true, redirect: candidate }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function deleteRedirect(store: ExtensionStore, source: string): Promise<void> {
|
|
112
|
+
await store.remove(redirectKey(source))
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* source -> destination path, for the bounded cycle check only. It reads the
|
|
117
|
+
* stored redirects once at WRITE time; nothing on the request path does this.
|
|
118
|
+
*/
|
|
119
|
+
async function loadChain(store: ExtensionStore): Promise<Map<string, string>> {
|
|
120
|
+
const entries = await store.list(REDIRECT_PREFIX, { limit: 1000 })
|
|
121
|
+
const chain = new Map<string, string>()
|
|
122
|
+
for (const { data } of entries) {
|
|
123
|
+
const r = data as unknown as SeoRedirect
|
|
124
|
+
if (r.destination?.kind !== 'external') continue
|
|
125
|
+
try { chain.set(normalizeSource(r.source), new URL(r.destination.url).pathname) } catch { /* skip */ }
|
|
126
|
+
}
|
|
127
|
+
return chain
|
|
128
|
+
}
|