@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.
- 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,411 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: redirects.tsx
|
|
3
|
+
* Purpose: Redirect management (closure plan Phase 9A, Unit 15), built on the
|
|
4
|
+
* Phase 8B Admin contracts rather than on a second set of its own:
|
|
5
|
+
* four async states, filtered-empty distinct from true empty, a
|
|
6
|
+
* failed load that says so and offers a retry, and a delete that
|
|
7
|
+
* confirms in proportion to what it does.
|
|
8
|
+
*
|
|
9
|
+
* Author: Raghunath J
|
|
10
|
+
* License: MIT
|
|
11
|
+
*
|
|
12
|
+
* Dependencies/Notes: @/kit only. The server owns every rule; this page
|
|
13
|
+
* renders the server's refusals rather than duplicating them, so the
|
|
14
|
+
* Admin and any other caller can never disagree about what is legal.
|
|
15
|
+
* No em dashes in UI copy.
|
|
16
|
+
*/
|
|
17
|
+
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
18
|
+
import { IconMoreHorizontal, IconArrowLeftRight, IconLink, IconRepeat, IconToggleOn, IconListChecks } from '@tangen/icons'
|
|
19
|
+
import {
|
|
20
|
+
adminFetch, useCan, useContentTypes, RelationPicker, usePageHeaderActions, ListChip, ListFilter, ListFilterChips, activeFilters,
|
|
21
|
+
Button, Badge, Callout, Text, DataList, Input, Label, Select, SelectItem, useConfirm, toast,
|
|
22
|
+
Dialog, DialogContent, DialogHeader, DialogTitle, DialogBody, DialogFooter,
|
|
23
|
+
ChoiceRow, RadioGroup, RadioGroupItem, Toggle,
|
|
24
|
+
type DataListColumn, type ListFilterFacet, type ListFilterValue, Menu, MenuTrigger, MenuContent, MenuItem, Panel } from '@/kit'
|
|
25
|
+
import { MANAGER_PAGE_SIZE } from '../lib/seo-manager-nav'
|
|
26
|
+
|
|
27
|
+
interface RedirectRow {
|
|
28
|
+
source: string
|
|
29
|
+
destination: { kind: 'external'; url: string } | { kind: 'path'; path: string } | { kind: 'internal'; type: string; id: string }
|
|
30
|
+
status: 301 | 302
|
|
31
|
+
enabled: boolean
|
|
32
|
+
createdAt: string
|
|
33
|
+
updatedAt: string
|
|
34
|
+
note?: string
|
|
35
|
+
/** Absent means the visitor's query string rides along. */
|
|
36
|
+
keepQuery?: boolean
|
|
37
|
+
/** For a content target: the URL the site resolves it to, when it can. */
|
|
38
|
+
resolved?: string | null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** What the one Filter control offers, in the order an editor reaches for it. */
|
|
42
|
+
const FACETS: ListFilterFacet[] = [
|
|
43
|
+
{ id: 'enabled', label: 'State', icon: <IconListChecks />, options: [{ value: 'all', label: 'All' }, { value: 'on', label: 'On' }, { value: 'off', label: 'Off' }] },
|
|
44
|
+
{
|
|
45
|
+
id: 'kind', label: 'Destination', icon: <IconArrowLeftRight />,
|
|
46
|
+
options: [
|
|
47
|
+
{ value: 'all', label: 'Any destination' },
|
|
48
|
+
{ value: 'content', label: 'Content' },
|
|
49
|
+
{ value: 'path', label: 'A path' },
|
|
50
|
+
{ value: 'url', label: 'A full URL' },
|
|
51
|
+
],
|
|
52
|
+
},
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
/** What a frontend fetches to hold the whole map itself. */
|
|
56
|
+
const REDIRECTS_JSON_PATH = '/api/v1/ext/seo/redirects.json'
|
|
57
|
+
|
|
58
|
+
const describe = (d: RedirectRow['destination'], resolved?: string | null): string =>
|
|
59
|
+
d.kind === 'external' ? d.url : d.kind === 'path' ? d.path : resolved ?? `${d.type} / ${d.id}`
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The Redirects section, rendered as a tab inside the SEO Manager hub. It owns
|
|
63
|
+
* no page header (the hub does): a self-contained toolbar carries the search
|
|
64
|
+
* and the New action instead.
|
|
65
|
+
*/
|
|
66
|
+
export function RedirectsPanel({ initialSource }: { initialSource?: string } = {}) {
|
|
67
|
+
const { hasCapability } = useCan()
|
|
68
|
+
const { confirm, confirmDialog } = useConfirm()
|
|
69
|
+
// Permission, not capability: the extension being ON is a separate question
|
|
70
|
+
// the platform's page gate already answered (Phase 8A/8B).
|
|
71
|
+
const mayWrite = hasCapability('seo:write' as never)
|
|
72
|
+
|
|
73
|
+
const [rows, setRows] = useState<RedirectRow[]>([])
|
|
74
|
+
const [loading, setLoading] = useState(true)
|
|
75
|
+
const [error, setError] = useState<string | null>(null)
|
|
76
|
+
const [search, setSearch] = useState('')
|
|
77
|
+
const [filters, setFilters] = useState<ListFilterValue>({ enabled: 'all', kind: 'all' })
|
|
78
|
+
const enabled = String(filters.enabled ?? 'all')
|
|
79
|
+
const kind = String(filters.kind ?? 'all')
|
|
80
|
+
const [total, setTotal] = useState(0)
|
|
81
|
+
const [page, setPage] = useState(1)
|
|
82
|
+
// Rows whose destination the app cannot place: they are in the table but not
|
|
83
|
+
// in the endpoint, which is confusing unless the page says so.
|
|
84
|
+
const unresolved = rows.filter((r) => r.destination.kind === 'internal' && !r.resolved)
|
|
85
|
+
const [sort, setSort] = useState<{ field: string; direction: 'asc' | 'desc' } | undefined>(undefined)
|
|
86
|
+
const [editing, setEditing] = useState<RedirectRow | null>(null)
|
|
87
|
+
const [open, setOpen] = useState(false)
|
|
88
|
+
|
|
89
|
+
const load = useCallback(async () => {
|
|
90
|
+
setLoading(true); setError(null)
|
|
91
|
+
try {
|
|
92
|
+
const res = await adminFetch<{ data: RedirectRow[]; meta?: { total?: number } }>('/admin/ext/seo/redirects', undefined, {
|
|
93
|
+
search, ...(enabled === 'all' ? {} : { enabled }), ...(kind === 'all' ? {} : { kind }),
|
|
94
|
+
...(sort ? { sort: sort.field, dir: sort.direction } : {}),
|
|
95
|
+
limit: String(MANAGER_PAGE_SIZE), offset: String((page - 1) * MANAGER_PAGE_SIZE),
|
|
96
|
+
})
|
|
97
|
+
setRows(res.data ?? [])
|
|
98
|
+
setTotal(res.meta?.total ?? (res.data ?? []).length)
|
|
99
|
+
} catch (e) {
|
|
100
|
+
// Phase 8B: a failed load is an ERROR, never "no results".
|
|
101
|
+
setError((e as Error).message || 'The redirect list could not be loaded.')
|
|
102
|
+
} finally { setLoading(false) }
|
|
103
|
+
}, [search, enabled, kind, sort, page])
|
|
104
|
+
|
|
105
|
+
useEffect(() => { load() }, [load])
|
|
106
|
+
|
|
107
|
+
// V5: the 404 Monitor sends an editor here with the path already known.
|
|
108
|
+
const prefilled = useRef(false)
|
|
109
|
+
useEffect(() => {
|
|
110
|
+
if (prefilled.current || !initialSource || !mayWrite) return
|
|
111
|
+
prefilled.current = true
|
|
112
|
+
setEditing({ source: initialSource, destination: { kind: 'external', url: '' }, status: 301 } as RedirectRow)
|
|
113
|
+
setOpen(true)
|
|
114
|
+
}, [initialSource, mayWrite])
|
|
115
|
+
|
|
116
|
+
async function remove(row: RedirectRow) {
|
|
117
|
+
const ok = await confirm({
|
|
118
|
+
title: 'Delete this redirect?',
|
|
119
|
+
message: `Visitors going to ${row.source} will stop being sent to ${describe(row.destination, row.resolved)}. You can create it again afterwards.`,
|
|
120
|
+
confirmLabel: 'Delete redirect',
|
|
121
|
+
variant: 'destructive',
|
|
122
|
+
})
|
|
123
|
+
if (!ok) return
|
|
124
|
+
try {
|
|
125
|
+
await adminFetch('/admin/ext/seo/redirects', { method: 'DELETE' }, { source: row.source })
|
|
126
|
+
toast.success('Redirect deleted')
|
|
127
|
+
load()
|
|
128
|
+
} catch (e) { toast.error('Could not delete the redirect', (e as Error).message) }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function setEnabledState(row: RedirectRow, next: boolean) {
|
|
132
|
+
try {
|
|
133
|
+
const res = await adminFetch<{ data?: unknown; error?: { message?: string } }>('/admin/ext/seo/redirects', {
|
|
134
|
+
method: 'PATCH',
|
|
135
|
+
body: JSON.stringify({ source: row.source, replacing: row.source, destination: row.destination, status: row.status, createdAt: row.createdAt, enabled: next }),
|
|
136
|
+
})
|
|
137
|
+
if (res?.error) { toast.error(res.error.message || 'That could not be changed'); return }
|
|
138
|
+
toast.success(next ? 'Redirect turned on' : 'Redirect turned off')
|
|
139
|
+
load()
|
|
140
|
+
} catch (e) { toast.error(e instanceof Error ? e.message : 'That could not be changed') }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const columns: DataListColumn<RedirectRow>[] = [
|
|
144
|
+
{ key: 'source', header: 'From', icon: <IconArrowLeftRight />, sortKey: 'source', cell: (r) => <span className="font-mono text-xs">{r.source}</span> },
|
|
145
|
+
{
|
|
146
|
+
key: 'destination', header: 'To', icon: <IconLink />,
|
|
147
|
+
cell: (r) => (
|
|
148
|
+
<span className="min-w-0">
|
|
149
|
+
<span className="font-mono text-xs">{describe(r.destination, r.resolved)}</span>
|
|
150
|
+
{r.destination.kind === 'internal' && <span className="ml-1.5 text-[11px] text-fg-subtle">{r.resolved ? 'content' : `${r.destination.type}, no URL yet`}</span>}
|
|
151
|
+
{r.destination.kind === 'path' && <span className="ml-1.5 text-[11px] text-fg-subtle">on this site</span>}
|
|
152
|
+
{r.keepQuery === false && <span className="ml-1.5 text-[11px] text-fg-subtle">query dropped</span>}
|
|
153
|
+
</span>
|
|
154
|
+
),
|
|
155
|
+
},
|
|
156
|
+
{ key: 'status', header: 'Kind', icon: <IconRepeat />, cell: (r) => <Badge>{r.status === 301 ? 'Permanent' : 'Temporary'}</Badge> },
|
|
157
|
+
{ key: 'enabled', header: 'State', icon: <IconToggleOn />, cell: (r) => <Badge variant={r.enabled ? 'success' : 'neutral'}>{r.enabled ? 'On' : 'Off'}</Badge> },
|
|
158
|
+
{
|
|
159
|
+
// Row actions reveal on hover or keyboard focus (UI V2 spec §16): a quiet
|
|
160
|
+
// Edit, and the irreversible Delete behind the row menu rather than a
|
|
161
|
+
// red button on every line.
|
|
162
|
+
key: 'actions', header: '', cell: (r) => mayWrite ? (
|
|
163
|
+
<div className="flex justify-end gap-1 opacity-0 transition-opacity motion-fast group-hover/row:opacity-100 group-focus-within/row:opacity-100 has-[[data-state=open]]:opacity-100">
|
|
164
|
+
<Button size="sm" variant="ghost" onClick={() => { setEditing(r); setOpen(true) }}>Edit</Button>
|
|
165
|
+
<Menu>
|
|
166
|
+
<MenuTrigger asChild>
|
|
167
|
+
<Button size="sm" variant="ghost" icon={<IconMoreHorizontal />} aria-label={`Actions for ${r.source}`} />
|
|
168
|
+
</MenuTrigger>
|
|
169
|
+
<MenuContent align="end">
|
|
170
|
+
<MenuItem onSelect={() => { setEditing(r); setOpen(true) }}>Edit</MenuItem>
|
|
171
|
+
<MenuItem onSelect={() => setEnabledState(r, r.enabled === false)}>{r.enabled === false ? 'Turn on' : 'Turn off'}</MenuItem>
|
|
172
|
+
<MenuItem destructive onSelect={() => remove(r)}>Delete</MenuItem>
|
|
173
|
+
</MenuContent>
|
|
174
|
+
</Menu>
|
|
175
|
+
</div>
|
|
176
|
+
) : null,
|
|
177
|
+
},
|
|
178
|
+
]
|
|
179
|
+
|
|
180
|
+
// The page header carries the one primary action, as every other page does.
|
|
181
|
+
usePageHeaderActions(
|
|
182
|
+
mayWrite ? <Button size="sm" onClick={() => { setEditing(null); setOpen(true) }}>New redirect</Button> : null,
|
|
183
|
+
[mayWrite],
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
return (
|
|
187
|
+
<div className="space-y-4">
|
|
188
|
+
<DataList<RedirectRow>
|
|
189
|
+
chrome="framed"
|
|
190
|
+
columns={columns}
|
|
191
|
+
search={search}
|
|
192
|
+
onSearchChange={(v) => { setSearch(v); setPage(1) }}
|
|
193
|
+
searchPlaceholder="Search by address"
|
|
194
|
+
filtered={search.trim() !== '' || enabled !== 'all' || kind !== 'all'}
|
|
195
|
+
total={total}
|
|
196
|
+
page={page}
|
|
197
|
+
pageSize={MANAGER_PAGE_SIZE}
|
|
198
|
+
onPageChange={setPage}
|
|
199
|
+
sortConfig={sort}
|
|
200
|
+
onSortChange={setSort}
|
|
201
|
+
toolbarLeft={<ListChip icon={<IconArrowLeftRight />} label="Redirects" count={total} />}
|
|
202
|
+
toolbarRight={<ListFilter facets={FACETS} value={filters} onChange={(next) => { setFilters(next); setPage(1) }} />}
|
|
203
|
+
filterRow={activeFilters(FACETS, filters).length
|
|
204
|
+
? <ListFilterChips facets={FACETS} value={filters} onChange={(next) => { setFilters(next); setPage(1) }} />
|
|
205
|
+
: undefined}
|
|
206
|
+
rows={rows}
|
|
207
|
+
rowKey={(r) => r.source}
|
|
208
|
+
loading={loading}
|
|
209
|
+
error={error ? { message: error, onRetry: load } : undefined}
|
|
210
|
+
emptyState={{
|
|
211
|
+
title: 'No redirects yet',
|
|
212
|
+
description: 'When a page moves, add a redirect here so its old address keeps working.',
|
|
213
|
+
action: mayWrite ? <Button size="sm" onClick={() => { setEditing(null); setOpen(true) }}>New redirect</Button> : undefined,
|
|
214
|
+
}}
|
|
215
|
+
filteredEmptyState={{
|
|
216
|
+
title: search.trim() ? `Nothing matches "${search}"` : 'No redirect is in that state',
|
|
217
|
+
description: search.trim() ? 'No redirect uses that address.' : 'Change the state filter to see the others.',
|
|
218
|
+
action: <Button size="sm" variant="secondary" onClick={() => { setSearch(''); setFilters({ enabled: 'all', kind: 'all' }) }}>Clear filters</Button>,
|
|
219
|
+
}}
|
|
220
|
+
/>
|
|
221
|
+
{unresolved.length > 0 && (
|
|
222
|
+
<Callout variant="warning" title={`${unresolved.length} redirect${unresolved.length === 1 ? '' : 's'} cannot be followed yet`}>
|
|
223
|
+
{`${unresolved.length === 1 ? 'It points' : 'They point'} at content, and your application has not told Tangen how to build that URL, so ${unresolved.length === 1 ? 'it is' : 'they are'} left out of the endpoint below and the public lookup answers nothing for ${unresolved.length === 1 ? 'it' : 'them'}. Give the SEO helpers a resolveUrl in your project's extension config, or point the redirect at a path or a full URL instead.`}
|
|
224
|
+
</Callout>
|
|
225
|
+
)}
|
|
226
|
+
<Panel>
|
|
227
|
+
<p className="text-sm font-semibold text-fg">The whole list, for your frontend</p>
|
|
228
|
+
<p className="mt-1 text-ui-xs text-fg-subtle">
|
|
229
|
+
Every redirect that is on, with its destination already resolved, so your site can hold the map itself (a Next.js <code className="font-mono">redirects()</code>, an edge middleware) instead of asking per request. It answers to a workspace API key.
|
|
230
|
+
</p>
|
|
231
|
+
<div className="mt-2 flex items-center gap-2">
|
|
232
|
+
<Input readOnly value={REDIRECTS_JSON_PATH} aria-label="The redirects endpoint" className="min-w-0 flex-1 font-mono text-[11px]" />
|
|
233
|
+
<Button size="sm" variant="secondary" onClick={() => { navigator.clipboard?.writeText(REDIRECTS_JSON_PATH); toast.success('Endpoint copied') }}>Copy</Button>
|
|
234
|
+
</div>
|
|
235
|
+
<p className="mt-1.5 text-[11px] text-fg-subtle">With the SDK: <code className="font-mono">client.seo.redirects()</code></p>
|
|
236
|
+
</Panel>
|
|
237
|
+
<Text variant="help">
|
|
238
|
+
Your site asks Tangen for a redirect on a path it does not recognise, through the public SEO route. Tangen stores the rule and resolves the destination; your application performs the redirect.
|
|
239
|
+
</Text>
|
|
240
|
+
<RedirectDialog open={open} onOpenChange={setOpen} editing={editing} onSaved={() => { setOpen(false); load() }} />
|
|
241
|
+
{confirmDialog}
|
|
242
|
+
</div>
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function RedirectDialog({ open, onOpenChange, editing, onSaved }: {
|
|
247
|
+
open: boolean
|
|
248
|
+
onOpenChange: (v: boolean) => void
|
|
249
|
+
editing: RedirectRow | null
|
|
250
|
+
onSaved: () => void
|
|
251
|
+
}) {
|
|
252
|
+
const [source, setSource] = useState('')
|
|
253
|
+
const [url, setUrl] = useState('')
|
|
254
|
+
const [status, setStatus] = useState<301 | 302>(301)
|
|
255
|
+
const [saving, setSaving] = useState(false)
|
|
256
|
+
const [fieldError, setFieldError] = useState<string | null>(null)
|
|
257
|
+
// Two ways to say where it goes: a piece of content on this site (stored as
|
|
258
|
+
// an identity, so it follows the page when its URL changes), or a full URL.
|
|
259
|
+
const [mode, setMode] = useState<'content' | 'address'>('content')
|
|
260
|
+
const [keepQuery, setKeepQuery] = useState(true)
|
|
261
|
+
const [targetType, setTargetType] = useState('')
|
|
262
|
+
const [targetId, setTargetId] = useState<string | null>(null)
|
|
263
|
+
const contentTypes = useContentTypes()
|
|
264
|
+
|
|
265
|
+
useEffect(() => {
|
|
266
|
+
if (!open) return
|
|
267
|
+
setSource(editing?.source ?? '')
|
|
268
|
+
setUrl(editing ? (editing.destination.kind === 'external' ? editing.destination.url : editing.destination.kind === 'path' ? editing.destination.path : '') : '')
|
|
269
|
+
setMode(editing ? (editing.destination.kind === 'internal' ? 'content' : 'address') : 'content')
|
|
270
|
+
setKeepQuery(editing ? editing.keepQuery !== false : true)
|
|
271
|
+
setTargetType(editing && editing.destination.kind === 'internal' ? editing.destination.type : '')
|
|
272
|
+
setTargetId(editing && editing.destination.kind === 'internal' ? editing.destination.id : null)
|
|
273
|
+
setStatus(editing?.status ?? 301)
|
|
274
|
+
setFieldError(null)
|
|
275
|
+
}, [open, editing])
|
|
276
|
+
|
|
277
|
+
// Default to the first content type so the picker has something to search.
|
|
278
|
+
useEffect(() => {
|
|
279
|
+
if (mode === 'content' && !targetType && contentTypes.length > 0) setTargetType(contentTypes[0]!.name)
|
|
280
|
+
}, [mode, targetType, contentTypes])
|
|
281
|
+
|
|
282
|
+
// One field, either form: a path on this site, or a full address. The shape
|
|
283
|
+
// of what was typed decides what is stored, so nobody picks a radio button
|
|
284
|
+
// to describe what they already wrote.
|
|
285
|
+
const typedAddress = url.trim()
|
|
286
|
+
const addressDestination = typedAddress.startsWith('/')
|
|
287
|
+
? { kind: 'path' as const, path: typedAddress }
|
|
288
|
+
: { kind: 'external' as const, url: typedAddress }
|
|
289
|
+
|
|
290
|
+
async function save() {
|
|
291
|
+
setSaving(true); setFieldError(null)
|
|
292
|
+
try {
|
|
293
|
+
// A route may answer an error envelope with a 200; treating that as a
|
|
294
|
+
// save is how a refused redirect looked created and never appeared.
|
|
295
|
+
const res = await adminFetch<{ data?: unknown; error?: { message?: string } }>('/admin/ext/seo/redirects', {
|
|
296
|
+
method: editing ? 'PATCH' : 'POST',
|
|
297
|
+
body: JSON.stringify({
|
|
298
|
+
source,
|
|
299
|
+
destination: mode === 'content'
|
|
300
|
+
? { kind: 'internal', type: targetType, id: targetId ?? '' }
|
|
301
|
+
: addressDestination,
|
|
302
|
+
status,
|
|
303
|
+
keepQuery,
|
|
304
|
+
...(editing ? { replacing: editing.source, createdAt: editing.createdAt } : {}),
|
|
305
|
+
}),
|
|
306
|
+
})
|
|
307
|
+
if (res?.error) { setFieldError(res.error.message || 'This redirect could not be saved.'); return }
|
|
308
|
+
toast.success(editing ? 'Redirect updated' : 'Redirect created')
|
|
309
|
+
onSaved()
|
|
310
|
+
} catch (e) {
|
|
311
|
+
// The server's own wording. The Admin does not re-author the rules.
|
|
312
|
+
setFieldError((e as Error).message || 'This redirect could not be saved.')
|
|
313
|
+
} finally { setSaving(false) }
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return (
|
|
317
|
+
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
318
|
+
<DialogContent className="max-w-md">
|
|
319
|
+
<DialogHeader><DialogTitle>{editing ? 'Edit redirect' : 'New redirect'}</DialogTitle></DialogHeader>
|
|
320
|
+
<DialogBody className="space-y-6">
|
|
321
|
+
<div className="space-y-1.5">
|
|
322
|
+
<Label htmlFor="seo-redirect-source">From</Label>
|
|
323
|
+
<Input id="seo-redirect-source" value={source} onChange={(e) => setSource((e.target as HTMLInputElement).value)} placeholder="/old-page" autoFocus />
|
|
324
|
+
<Text variant="help">A path on your site, not a full address.</Text>
|
|
325
|
+
</div>
|
|
326
|
+
|
|
327
|
+
<div className="space-y-2.5">
|
|
328
|
+
<Label>To</Label>
|
|
329
|
+
{/* A choice reads as a choice: two radio rows, then the control for
|
|
330
|
+
whichever was chosen. Button pairs looked like actions. */}
|
|
331
|
+
<RadioGroup value={mode} onValueChange={(v) => setMode(v as 'content' | 'address')}>
|
|
332
|
+
<ChoiceRow
|
|
333
|
+
htmlFor="seo-redirect-to-content"
|
|
334
|
+
label="A page on this site"
|
|
335
|
+
help="Stored as the page's identity, so the redirect follows it if its address changes."
|
|
336
|
+
control={<RadioGroupItem id="seo-redirect-to-content" value="content" />}
|
|
337
|
+
/>
|
|
338
|
+
<ChoiceRow
|
|
339
|
+
htmlFor="seo-redirect-to-address"
|
|
340
|
+
label="An address"
|
|
341
|
+
help={'A path like /abc.html, or a full URL including https.'}
|
|
342
|
+
control={<RadioGroupItem id="seo-redirect-to-address" value="address" />}
|
|
343
|
+
/>
|
|
344
|
+
</RadioGroup>
|
|
345
|
+
<div className="pt-0.5">
|
|
346
|
+
{mode === 'content' ? (
|
|
347
|
+
<div className="space-y-2">
|
|
348
|
+
{contentTypes.length > 1 && (
|
|
349
|
+
<Select value={targetType} onValueChange={(v) => { setTargetType(v); setTargetId(null) }} placeholder="Content type">
|
|
350
|
+
{contentTypes.map((t) => <SelectItem key={t.name} value={t.name}>{t.label ?? t.name}</SelectItem>)}
|
|
351
|
+
</Select>
|
|
352
|
+
)}
|
|
353
|
+
{targetType
|
|
354
|
+
? <RelationPicker targetType={targetType} value={targetId} onChange={setTargetId} label="Destination page" />
|
|
355
|
+
: <Text variant="help">This workspace has no content types yet.</Text>}
|
|
356
|
+
</div>
|
|
357
|
+
) : (
|
|
358
|
+
<div className="space-y-1.5">
|
|
359
|
+
<Input id="seo-redirect-url" aria-label="Destination address" value={url} onChange={(e) => setUrl((e.target as HTMLInputElement).value)} placeholder="/abc.html or https://example.com/new-page" />
|
|
360
|
+
{typedAddress !== '' && (
|
|
361
|
+
<Text variant="help">
|
|
362
|
+
{typedAddress.startsWith('/')
|
|
363
|
+
? 'A path on this site: your app redirects from its own origin.'
|
|
364
|
+
: 'A full address. Start with "/" instead for a path on this site.'}
|
|
365
|
+
</Text>
|
|
366
|
+
)}
|
|
367
|
+
</div>
|
|
368
|
+
)}
|
|
369
|
+
</div>
|
|
370
|
+
</div>
|
|
371
|
+
|
|
372
|
+
<div className="space-y-2.5">
|
|
373
|
+
<Label>Kind</Label>
|
|
374
|
+
{/* Two options, so they are both visible rather than hidden behind a
|
|
375
|
+
menu that a short dialog clips. */}
|
|
376
|
+
<RadioGroup value={String(status)} onValueChange={(v) => setStatus(Number(v) as 301 | 302)}>
|
|
377
|
+
<ChoiceRow
|
|
378
|
+
htmlFor="seo-redirect-301"
|
|
379
|
+
label="Permanent (301)"
|
|
380
|
+
help="The move is final; search engines carry the ranking over."
|
|
381
|
+
control={<RadioGroupItem id="seo-redirect-301" value="301" />}
|
|
382
|
+
/>
|
|
383
|
+
<ChoiceRow
|
|
384
|
+
htmlFor="seo-redirect-302"
|
|
385
|
+
label="Temporary (302)"
|
|
386
|
+
help="The old address is coming back; rankings stay with it."
|
|
387
|
+
control={<RadioGroupItem id="seo-redirect-302" value="302" />}
|
|
388
|
+
/>
|
|
389
|
+
</RadioGroup>
|
|
390
|
+
</div>
|
|
391
|
+
|
|
392
|
+
<Toggle
|
|
393
|
+
label="Carry the query string"
|
|
394
|
+
description="A visitor arriving with ?utm_source=mail keeps it on the new address. The redirect fires either way."
|
|
395
|
+
direction="switch-first"
|
|
396
|
+
size="sm"
|
|
397
|
+
checked={keepQuery}
|
|
398
|
+
onCheckedChange={setKeepQuery}
|
|
399
|
+
/>
|
|
400
|
+
|
|
401
|
+
{/* A refusal is a persistent condition, not a toast that vanishes. */}
|
|
402
|
+
{fieldError && <p role="alert" className="text-xs text-danger-fg">{fieldError}</p>}
|
|
403
|
+
</DialogBody>
|
|
404
|
+
<DialogFooter>
|
|
405
|
+
<Button variant="secondary" size="sm" onClick={() => onOpenChange(false)}>Cancel</Button>
|
|
406
|
+
<Button variant="primary" size="sm" isLoading={saving} onClick={save}>{editing ? 'Save' : 'Create'}</Button>
|
|
407
|
+
</DialogFooter>
|
|
408
|
+
</DialogContent>
|
|
409
|
+
</Dialog>
|
|
410
|
+
)
|
|
411
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: analytics-read.ts
|
|
3
|
+
* Purpose: What the Analytics page and the Dashboard read
|
|
4
|
+
* (plan-seo-manager-v2 V4): the stored daily rows, summarised over
|
|
5
|
+
* the asked window with the window before it, the top pages and
|
|
6
|
+
* queries, and the sync's own state. Reads the store and nothing
|
|
7
|
+
* else - no request to Google happens on a render.
|
|
8
|
+
*
|
|
9
|
+
* Author: Raghunath J
|
|
10
|
+
* License: MIT
|
|
11
|
+
*/
|
|
12
|
+
import type { ExtensionServerCtx } from '@tangen/cms'
|
|
13
|
+
import { searchConsoleConnection, type SearchConsoleStatus } from './search-console'
|
|
14
|
+
import {
|
|
15
|
+
DAY_PREFIX, limitsOf, summarize, SYNC_STATE_KEY, topRows,
|
|
16
|
+
type DailyRow, type Summary, type SyncState, type TopRow,
|
|
17
|
+
} from '../lib/analytics'
|
|
18
|
+
|
|
19
|
+
/** The most day rows a read will load: the hard retention ceiling plus room. */
|
|
20
|
+
const MAX_DAY_ROWS = 600
|
|
21
|
+
export const TOP_ROWS_SHOWN = 10
|
|
22
|
+
|
|
23
|
+
export interface AnalyticsView {
|
|
24
|
+
days: number
|
|
25
|
+
/** null until a sync has written a day. */
|
|
26
|
+
summary: Summary | null
|
|
27
|
+
pages: TopRow[]
|
|
28
|
+
queries: TopRow[]
|
|
29
|
+
sync: SyncState & { intervalHours: number }
|
|
30
|
+
connection: SearchConsoleStatus
|
|
31
|
+
limits: { retentionDays: number; rowLimit: number }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function readAnalytics(ctx: ExtensionServerCtx, opts: { days?: number; now?: Date } = {}): Promise<AnalyticsView> {
|
|
35
|
+
const now = opts.now ?? new Date()
|
|
36
|
+
const days = Math.max(1, Math.min(Math.floor(opts.days ?? 28), 365))
|
|
37
|
+
const rows = (await ctx.store.list(DAY_PREFIX, { limit: MAX_DAY_ROWS })).map((r) => r.data as unknown as DailyRow)
|
|
38
|
+
const summary = rows.length ? summarize(rows, { now, days }) : null
|
|
39
|
+
const sync = ((await ctx.store.get(SYNC_STATE_KEY)) ?? {}) as SyncState
|
|
40
|
+
const settings = (await ctx.settings?.get().catch(() => ({}))) ?? {}
|
|
41
|
+
const { status } = await searchConsoleConnection(ctx)
|
|
42
|
+
return {
|
|
43
|
+
days,
|
|
44
|
+
summary: summary && summary.days ? summary : summary,
|
|
45
|
+
pages: rows.length ? topRows(rows, 'pages', { now, days, limit: TOP_ROWS_SHOWN }) : [],
|
|
46
|
+
queries: rows.length ? topRows(rows, 'queries', { now, days, limit: TOP_ROWS_SHOWN }) : [],
|
|
47
|
+
sync: { ...sync, intervalHours: 24 },
|
|
48
|
+
connection: status,
|
|
49
|
+
limits: limitsOf(settings as Record<string, unknown>),
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: analytics-sync.ts
|
|
3
|
+
* Purpose: Brings Search Console numbers into the extension's own store
|
|
4
|
+
* (plan-seo-manager-v2 V4): one row per day with that day's totals
|
|
5
|
+
* and its top pages and queries, bounded by the operator's row
|
|
6
|
+
* limit, pruned by the operator's retention. Runs as a platform
|
|
7
|
+
* task (daily, re-armed the way Flows arms a schedule) and on
|
|
8
|
+
* demand from the Analytics page; the page itself only ever reads
|
|
9
|
+
* the store, so a render never calls Google.
|
|
10
|
+
*
|
|
11
|
+
* Author: Raghunath J
|
|
12
|
+
* License: MIT
|
|
13
|
+
*/
|
|
14
|
+
import type { ExtensionServerCtx } from '@tangen/cms'
|
|
15
|
+
import { searchConsoleConnection, type SearchAnalyticsRow } from './search-console'
|
|
16
|
+
import {
|
|
17
|
+
boundedRows, dayKey, DAY_PREFIX, expiredDayKeys, limitsOf, window,
|
|
18
|
+
SYNC_STATE_KEY, type DailyRow, type DimensionRow, type SyncState, type SyncErrorKind,
|
|
19
|
+
} from '../lib/analytics'
|
|
20
|
+
|
|
21
|
+
export const SYNC_TASK = 'ext:seo:sync-search-console'
|
|
22
|
+
/** Once a day; Google finalises a day's numbers within about three. */
|
|
23
|
+
export const SYNC_INTERVAL_SECONDS = 86_400
|
|
24
|
+
/** A routine sync re-reads this many days, so late data lands. */
|
|
25
|
+
export const SYNC_REFRESH_DAYS = 7
|
|
26
|
+
/** A manual sync may not run more often than this. */
|
|
27
|
+
export const MANUAL_SYNC_COOLDOWN_SECONDS = 600
|
|
28
|
+
/** One request's row cap, whatever the operator's per-day limit multiplies out to. */
|
|
29
|
+
const REQUEST_ROW_CAP = 5_000
|
|
30
|
+
|
|
31
|
+
export type SyncOutcome =
|
|
32
|
+
| { ok: true; days: number; property: string; from: string; to: string }
|
|
33
|
+
| { ok: false; reason: string; retryAfterSeconds?: number }
|
|
34
|
+
|
|
35
|
+
const state = async (ctx: ExtensionServerCtx): Promise<SyncState> => ((await ctx.store.get(SYNC_STATE_KEY)) ?? {}) as SyncState
|
|
36
|
+
|
|
37
|
+
/** Google's `['date', <dimension>]` rows, grouped by day and cut to the per-day limit. */
|
|
38
|
+
function byDay(rows: readonly SearchAnalyticsRow[], limit: number): Map<string, DimensionRow[]> {
|
|
39
|
+
const out = new Map<string, DimensionRow[]>()
|
|
40
|
+
for (const r of rows) {
|
|
41
|
+
const [date, key] = r.keys
|
|
42
|
+
if (!date || !key) continue
|
|
43
|
+
const list = out.get(date) ?? []
|
|
44
|
+
list.push({ key, clicks: r.clicks, impressions: r.impressions, ctr: r.ctr, position: r.position })
|
|
45
|
+
out.set(date, list)
|
|
46
|
+
}
|
|
47
|
+
for (const [date, list] of out) out.set(date, boundedRows(list, limit))
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Reads the window and writes it. Never throws for an expected condition (no
|
|
53
|
+
* grant, no connection, no property, Google refusing): the reason is recorded
|
|
54
|
+
* on the sync state and returned, so the page can say it.
|
|
55
|
+
*/
|
|
56
|
+
export async function syncSearchConsole(ctx: ExtensionServerCtx, opts: { days?: number; now?: Date } = {}): Promise<SyncOutcome> {
|
|
57
|
+
const now = opts.now ?? new Date()
|
|
58
|
+
// Every recorded failure says WHY, so the page can tell whether the cause
|
|
59
|
+
// still holds (the user, 2026-09-20: the property was set, and the page
|
|
60
|
+
// still read "no property chosen" from the run before).
|
|
61
|
+
const fail = async (reason: string, kind: SyncErrorKind): Promise<SyncOutcome> => {
|
|
62
|
+
await ctx.store.put(SYNC_STATE_KEY, {
|
|
63
|
+
...(await state(ctx)), lastError: reason, lastErrorKind: kind, lastErrorAt: now.toISOString(),
|
|
64
|
+
} as never)
|
|
65
|
+
return { ok: false, reason }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const { status, reader } = await searchConsoleConnection(ctx)
|
|
69
|
+
if (!status.connected || !reader) {
|
|
70
|
+
return fail(status.connected ? 'The Search Console connection is not usable.' : status.reason, 'connection')
|
|
71
|
+
}
|
|
72
|
+
if (!status.property) {
|
|
73
|
+
return fail(
|
|
74
|
+
'No Search Console property chosen: pick it on the SEO Manager\'s Settings tab, under Search Console.',
|
|
75
|
+
'property',
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
const settings = (await ctx.settings?.get().catch(() => ({}))) ?? {}
|
|
79
|
+
const { retentionDays, rowLimit } = limitsOf(settings as Record<string, unknown>)
|
|
80
|
+
// A first sync fills the retention window; a routine one re-reads the last few days.
|
|
81
|
+
const existing = await ctx.store.list(DAY_PREFIX, { limit: 1 })
|
|
82
|
+
const days = Math.min(opts.days ?? (existing.length ? SYNC_REFRESH_DAYS : retentionDays), retentionDays)
|
|
83
|
+
const { startDate, endDate } = window(now, days)
|
|
84
|
+
const query = { siteUrl: status.property, startDate, endDate }
|
|
85
|
+
const perRequest = Math.min(rowLimit * days, REQUEST_ROW_CAP)
|
|
86
|
+
|
|
87
|
+
let totals: SearchAnalyticsRow[]
|
|
88
|
+
let pages: SearchAnalyticsRow[]
|
|
89
|
+
let queries: SearchAnalyticsRow[]
|
|
90
|
+
try {
|
|
91
|
+
totals = await reader.query({ ...query, dimensions: ['date'], rowLimit: days })
|
|
92
|
+
pages = await reader.query({ ...query, dimensions: ['date', 'page'], rowLimit: perRequest })
|
|
93
|
+
queries = await reader.query({ ...query, dimensions: ['date', 'query'], rowLimit: perRequest })
|
|
94
|
+
} catch (e) {
|
|
95
|
+
return fail((e as Error).message, 'provider')
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const pageRows = byDay(pages, rowLimit)
|
|
99
|
+
const queryRows = byDay(queries, rowLimit)
|
|
100
|
+
let written = 0
|
|
101
|
+
for (const row of totals) {
|
|
102
|
+
const date = row.keys[0]
|
|
103
|
+
if (!date) continue
|
|
104
|
+
const day: DailyRow = {
|
|
105
|
+
date, clicks: row.clicks, impressions: row.impressions, ctr: row.ctr, position: row.position,
|
|
106
|
+
pages: pageRows.get(date) ?? [], queries: queryRows.get(date) ?? [],
|
|
107
|
+
}
|
|
108
|
+
await ctx.store.put(dayKey(date), day as never)
|
|
109
|
+
written += 1
|
|
110
|
+
}
|
|
111
|
+
// Retention, over the keys that exist rather than a date walk.
|
|
112
|
+
const keys = (await ctx.store.list(DAY_PREFIX, { limit: MAX_DAY_ROWS })).map((r) => r.key)
|
|
113
|
+
for (const key of expiredDayKeys(keys, now, retentionDays)) await ctx.store.remove(key)
|
|
114
|
+
|
|
115
|
+
await ctx.store.put(SYNC_STATE_KEY, {
|
|
116
|
+
...(await state(ctx)), lastSyncedAt: now.toISOString(),
|
|
117
|
+
lastError: null, lastErrorKind: undefined, lastErrorAt: undefined,
|
|
118
|
+
property: status.property, days: written,
|
|
119
|
+
} as never)
|
|
120
|
+
return { ok: true, days: written, property: status.property, from: startDate, to: endDate }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const MAX_DAY_ROWS = 600
|
|
124
|
+
|
|
125
|
+
/** A manual sync, refused by name while the cooldown holds. */
|
|
126
|
+
export async function syncOnDemand(ctx: ExtensionServerCtx, opts: { now?: Date } = {}): Promise<SyncOutcome> {
|
|
127
|
+
const now = opts.now ?? new Date()
|
|
128
|
+
const last = (await state(ctx)).lastSyncedAt
|
|
129
|
+
if (last) {
|
|
130
|
+
const elapsed = Math.round((now.getTime() - Date.parse(last)) / 1000)
|
|
131
|
+
if (Number.isFinite(elapsed) && elapsed >= 0 && elapsed < MANUAL_SYNC_COOLDOWN_SECONDS) {
|
|
132
|
+
return { ok: false, reason: 'Search Console was synced a moment ago; the numbers update once a day.', retryAfterSeconds: MANUAL_SYNC_COOLDOWN_SECONDS - elapsed }
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return syncSearchConsole(ctx, { now })
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Arms the daily chain: a new generation retires any chain a previous boot
|
|
140
|
+
* left behind, so a wake carrying an old generation exits (the Flows pattern).
|
|
141
|
+
*/
|
|
142
|
+
export async function armAnalyticsSync(ctx: ExtensionServerCtx, opts: { delaySeconds?: number } = {}): Promise<number> {
|
|
143
|
+
const prev = await state(ctx)
|
|
144
|
+
const gen = (prev.gen ?? 0) + 1
|
|
145
|
+
await ctx.store.put(SYNC_STATE_KEY, { ...prev, gen } as never)
|
|
146
|
+
await ctx.enqueue(SYNC_TASK, { gen }, { delaySeconds: opts.delaySeconds ?? SYNC_INTERVAL_SECONDS })
|
|
147
|
+
return gen
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** One wake of the chain: sync when the generation is current, then re-arm. */
|
|
151
|
+
export async function runAnalyticsSyncTask(payload: unknown, ctx: ExtensionServerCtx): Promise<void> {
|
|
152
|
+
const p = payload as { gen?: unknown; once?: unknown } | undefined
|
|
153
|
+
// A ONE-OFF run: the settings changed and somebody is waiting to see
|
|
154
|
+
// numbers. It syncs and stops - re-arming here would start a second daily
|
|
155
|
+
// chain beside the one already running.
|
|
156
|
+
if (p?.once === true) {
|
|
157
|
+
await syncSearchConsole(ctx).catch(() => undefined)
|
|
158
|
+
return
|
|
159
|
+
}
|
|
160
|
+
const gen = Number(p?.gen ?? 0)
|
|
161
|
+
const current = await state(ctx)
|
|
162
|
+
if ((current.gen ?? 0) !== gen) return
|
|
163
|
+
await syncSearchConsole(ctx).catch(() => undefined)
|
|
164
|
+
await ctx.enqueue(SYNC_TASK, { gen }, { delaySeconds: SYNC_INTERVAL_SECONDS })
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The settings that decide WHAT is synced: a change to either is worth a run. */
|
|
168
|
+
export const SYNC_SETTING_KEYS = ['searchConsole', 'searchConsoleProperty'] as const
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* An operator chose the connection or the property, so the numbers are one
|
|
172
|
+
* sync away. Enqueued, never run inline: the Save button must not wait on
|
|
173
|
+
* Google (and a settings hook that blocks is a settings page that hangs).
|
|
174
|
+
*/
|
|
175
|
+
export async function syncAfterSettingsChange(
|
|
176
|
+
ctx: ExtensionServerCtx,
|
|
177
|
+
changed: readonly string[],
|
|
178
|
+
): Promise<boolean> {
|
|
179
|
+
if (!changed.some((k) => (SYNC_SETTING_KEYS as readonly string[]).includes(k))) return false
|
|
180
|
+
await ctx.enqueue(SYNC_TASK, { once: true }).catch(() => undefined)
|
|
181
|
+
return true
|
|
182
|
+
}
|