Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(audit): group Site Audit pages by template, "fix once, applies to N pages" (#1141)

Cihan5864e88f4358
diff --git a/server/src/lib/audit/auto-audit.js b/server/src/lib/audit/auto-audit.js
index 3f8d9a29b..17efbacb8 100644
--- a/server/src/lib/audit/auto-audit.js
+++ b/server/src/lib/audit/auto-audit.js
@@ -105,7 +105,8 @@ export function pickRunPages(inboxes, slots, now, triedKeys = new Set()) {
const candidates = [];
for (const { brandId, opportunities } of inboxes) {
for (const row of opportunities) {
- if (row.running || triedKeys.has(row.key)) continue;
+ // A template's row (SA-007) stands for pages the inbox lists one by one.
+ if (row.template || row.running || triedKeys.has(row.key)) continue;
if (row.lastAudit && Date.parse(row.lastAudit.at) >= freshSince) continue;
candidates.push({
brandId,
diff --git a/server/src/lib/audit/auto-audit.test.js b/server/src/lib/audit/auto-audit.test.js
index 9a37e1c39..17fe27b70 100644
--- a/server/src/lib/audit/auto-audit.test.js
+++ b/server/src/lib/audit/auto-audit.test.js
@@ -126,6 +126,8 @@ describe('pickRunPages', () => {
row('/fresh', { pinned: true, lastAudit: { at: '2026-09-20T00:00:00Z' } }),
row('/old', { lastAudit: { at: '2026-09-10T00:00:00Z' } }),
row('/never'),
+ // A template's row: its pages are listed one by one.
+ row('/blog/*', { url: null, template: { pages: 38, audited: 2, toAudit: [] } }),
],
},
],
diff --git a/server/src/lib/audit/priority.js b/server/src/lib/audit/priority.js
index 4973b0272..c0ddd7ecf 100644
--- a/server/src/lib/audit/priority.js
+++ b/server/src/lib/audit/priority.js
@@ -12,9 +12,12 @@
* cited on the page's prompts, a target page not cited, never or long ago
* audited, no AI visits.
* - Ease: how close the page is to passing. Its last score; unknown when
- * never audited. (A template-level fix, SA-007, will add to it.)
+ * never audited. A page whose template shares its gaps (SA-007) is easier:
+ * one fix covers every page of it.
*/
+import { templateOf } from './templates.js';
+
export const PRIORITY_WEIGHTS = Object.freeze({
value: Object.freeze({
signals: Object.freeze({ revenue: 1, transactions: 1, key_events: 0.9, engagement: 0.75 }),
@@ -31,6 +34,10 @@ export const PRIORITY_WEIGHTS = Object.freeze({
neverAudited: 0.3,
staleAudit: 0.2,
zeroAiVisits: 0.1,
+ /** A template whose pages share gaps (SA-007): its first gap, each more, the cap. */
+ templateGaps: 0.3,
+ perExtraGap: 0.05,
+ templateGapsMax: 0.45,
min: 0.1,
}),
ease: Object.freeze({
@@ -41,6 +48,8 @@ export const PRIORITY_WEIGHTS = Object.freeze({
middle: 0.75,
low: 0.55,
unaudited: 0.8,
+ /** Added for a page whose template shares its gaps (SA-007). */
+ templateFix: 0.1,
}),
});
@@ -66,11 +75,12 @@ export function sessionsRanker(siteSessions) {
}
/**
- * @param {{ reasons: Array<object>, sessions: number|null, aiVisits?: number|null, lastAudit: { score: number }|null }} row
+ * @param {{ path?: string, reasons: Array<object>, sessions: number|null, aiVisits?: number|null, lastAudit: { score: number }|null }} row
* @param {(sessions: number|null) => number|null} rankSessions
+ * @param {Set<string>} [sharedTemplates] templates whose pages share gaps (templates.js)
* @returns {{ priority: number, value: number, opportunity: number, ease: number }}
*/
-export function scorePriority(row, rankSessions) {
+export function scorePriority(row, rankSessions, sharedTemplates = new Set()) {
const w = PRIORITY_WEIGHTS;
const reason = (type) => row.reasons.find((r) => r.type === type);
@@ -104,7 +114,7 @@ export function scorePriority(row, rankSessions) {
const e = w.ease;
const score = row.lastAudit?.score ?? null;
- const ease =
+ const byScore =
score === null
? e.unaudited
: score >= e.nearPassingScore
@@ -112,7 +122,42 @@ export function scorePriority(row, rankSessions) {
: score >= e.middleScore
? e.middle
: e.low;
+ const ease = Math.min(
+ 1,
+ byScore + (sharedTemplates.has(templateOf(row.path)) ? e.templateFix : 0),
+ );
+
+ return {
+ priority: Math.round(100 * Math.cbrt(value * opportunity * ease)),
+ value: round2(value),
+ opportunity: round2(opportunity),
+ ease: round2(ease),
+ };
+}
+/**
+ * A template row's score (SA-007): value from its pages' summed sessions;
+ * opportunity from the gaps they share, its pages not audited yet and no AI
+ * visits; ease as a never-audited page's plus the template fix, since one
+ * fix covers them all.
+ *
+ * @param {{ reasons: Array<object>, sessions: number|null, aiVisits?: number|null, template: { pages: number, audited: number } }} row
+ * @param {(sessions: number|null) => number|null} rankSessions
+ */
+export function scoreTemplate(row, rankSessions) {
+ const w = PRIORITY_WEIGHTS;
+ const o = w.opportunity;
+ const value = clamp((rankSessions(row.sessions) ?? 0) * w.value.sessions, w.value.min, 1);
+ const gaps = row.reasons.find((r) => r.type === 'template_gaps')?.gaps.length ?? 0;
+ const unaudited = row.template.pages > 0 ? 1 - row.template.audited / row.template.pages : 0;
+ let opportunity = 0;
+ if (gaps > 0) {
+ opportunity += Math.min(o.templateGapsMax, o.templateGaps + o.perExtraGap * (gaps - 1));
+ }
+ opportunity += o.neverAudited * unaudited;
+ if (row.aiVisits === 0) opportunity += o.zeroAiVisits;
+ opportunity = clamp(opportunity, o.min, 1);
+ const ease = Math.min(1, w.ease.unaudited + w.ease.templateFix);
return {
priority: Math.round(100 * Math.cbrt(value * opportunity * ease)),
value: round2(value),
@@ -123,18 +168,21 @@ export function scorePriority(row, rankSessions) {
/**
* Scores every row and orders the inbox: pinned pages first, then by
- * priority, then by path.
+ * priority, then by path. A template row (SA-007) scores as a template.
*
* @template {{ path: string, pinned: boolean, reasons: Array<object>, sessions: number|null, aiVisits?: number|null, lastAudit: object|null }} R
* @param {R[]} rows
* @param {Array<number|null>} siteSessions the site pages' 30-day sessions
+ * @param {Set<string>} [sharedTemplates] templates whose pages share gaps (SA-007)
* @returns {Array<R & { priority: number, priorityParts: { value: number, opportunity: number, ease: number } }>}
*/
-export function rankOpportunities(rows, siteSessions) {
+export function rankOpportunities(rows, siteSessions, sharedTemplates = new Set()) {
const rankSessions = sessionsRanker(siteSessions);
return rows
.map((row) => {
- const { priority, ...priorityParts } = scorePriority(row, rankSessions);
+ const { priority, ...priorityParts } = row.template
+ ? scoreTemplate(row, rankSessions)
+ : scorePriority(row, rankSessions, sharedTemplates);
return { ...row, priority, priorityParts };
})
.sort(
diff --git a/server/src/lib/audit/priority.test.js b/server/src/lib/audit/priority.test.js
index 1e3d89f36..75904b82c 100644
--- a/server/src/lib/audit/priority.test.js
+++ b/server/src/lib/audit/priority.test.js
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { PRIORITY_WEIGHTS, rankOpportunities, scorePriority, sessionsRanker } from './priority.js';
+import {
+ PRIORITY_WEIGHTS,
+ rankOpportunities,
+ scorePriority,
+ scoreTemplate,
+ sessionsRanker,
+} from './priority.js';
const row = (over = {}) => ({
path: '/page',
@@ -102,6 +108,63 @@ describe('scorePriority', () => {
expect(ease(0.2)).toBe(0.55);
expect(ease(null)).toBe(0.8);
});
+
+ it('makes a page whose template shares its gaps easier, up to 1 (SA-007)', () => {
+ const shared = new Set(['/blog/*']);
+ const ease = (path, score) =>
+ scorePriority(row({ path, lastAudit: score === null ? null : { score } }), noRank, shared)
+ .ease;
+ expect(ease('/blog/milk-drinks', null)).toBe(0.9);
+ expect(ease('/blog/milk-drinks', 0.5)).toBe(0.85);
+ expect(ease('/blog/milk-drinks', 0.65)).toBe(1);
+ expect(ease('/guides/espresso', null)).toBe(0.8);
+ expect(ease('/pricing', null)).toBe(0.8);
+ });
+});
+
+describe('scoreTemplate', () => {
+ const template = (over = {}) => ({
+ path: '/blog/*',
+ pinned: false,
+ reasons: [{ type: 'template_gaps', gaps: [{ key: 'author-byline' }] }],
+ sessions: 900,
+ aiVisits: 112,
+ template: { pages: 38, audited: 12, toAudit: [] },
+ ...over,
+ });
+
+ it('scores a template from its sessions, shared gaps, unaudited share and the template fix', () => {
+ // Above every site page: the top of the sessions value.
+ const rank = sessionsRanker([10, 40, 90]);
+ expect(scoreTemplate(template(), rank)).toEqual({
+ priority: 65,
+ value: 0.6,
+ // 0.3 for the gap + 0.3 × 26 of 38 not audited.
+ opportunity: 0.51,
+ ease: 0.9,
+ });
+ const more = scoreTemplate(
+ template({
+ aiVisits: 0,
+ reasons: [
+ {
+ type: 'template_gaps',
+ gaps: [{ key: 'a' }, { key: 'b' }, { key: 'c' }, { key: 'd' }, { key: 'e' }],
+ },
+ ],
+ template: { pages: 10, audited: 10, toAudit: [] },
+ }),
+ rank,
+ );
+ // Gaps capped at 0.45, plus no AI visits; all audited.
+ expect(more.opportunity).toBe(0.55);
+ });
+
+ it('ranks template rows with the pages', () => {
+ const ranked = rankOpportunities([row({ path: '/pricing' }), template()], [10, 40, 90]);
+ expect(ranked.map((r) => r.path)).toEqual(['/blog/*', '/pricing']);
+ expect(ranked[0].priorityParts.ease).toBe(0.9);
+ });
});
describe('rankOpportunities', () => {
diff --git a/server/src/lib/audit/templates.js b/server/src/lib/audit/templates.js
new file mode 100644
index 000000000..9507799cf
--- /dev/null
+++ b/server/src/lib/audit/templates.js
@@ -0,0 +1,171 @@
+/**
+ * Site Audit template grouping (SA-007): pages built from one template (the
+ * blog's posts, the product pages) share most of their gaps, and fixing the
+ * template fixes every page of it: "Fix once, applies to 38 pages". Pure, so
+ * the route only reads rows and this decides what they add up to.
+ *
+ * A page's template is its path with the last part as a wildcard
+ * (/blog/milk-drinks → /blog/*); a top-level page has none. A template
+ * counts with at least three pages, from the site's pages (site_pages) and
+ * the audited ones. Its shared gaps are the signals that fail or warn on at
+ * least two-thirds of its audited pages, through each page's latest audit.
+ * A template with shared gaps is a row of the Opportunities inbox (the
+ * mockup's "/blog/* · 38 pages"), whose audit covers its pages not audited
+ * yet.
+ */
+
+import { isExcludedPath } from '../page-paths.js';
+import { pageKey } from './history.js';
+import { signalsByKey } from './rubric.js';
+
+export const TEMPLATES = Object.freeze({
+ /** Pages a template needs to be one. */
+ minPages: 3,
+ /** Audited pages a shared gap needs. */
+ minAudited: 2,
+ /** Share of the audited pages a signal must fail or warn on to be the template's. */
+ sharedShare: 2 / 3,
+ /** Shared gaps listed per template. */
+ maxGaps: 3,
+ /** Pages one audit of a template starts: a bulk request's limit (BULK_AUDIT_MAX). */
+ maxToAudit: 50,
+});
+
+/** '/blog/milk-drinks' → '/blog/*', lowercased; null for a top-level page. */
+export function templateOf(path) {
+ const parts = String(path ?? '')
+ .toLowerCase()
+ .split('/')
+ .filter(Boolean);
+ return parts.length < 2 ? null : `/${parts.slice(0, -1).join('/')}/*`;
+}
+
+/**
+ * @param {object} input
+ * @param {string|null} input.primaryHost
+ * @param {Array<{ url: string, ga_sessions?: number|null }>} [input.sitePages] site_pages rows
+ * @param {Array<{ key: string, host: string|null, path: string, url: string, auditId: string, score: number|null, status?: string }>} [input.auditPages]
+ * buildAuditPages output
+ * @param {Array<{ audit_id: string, signal_key: string }>} [input.failingRows]
+ * failed or warning signals of the audited pages' latest audits
+ * @returns {Array<{ template: string, pages: number, audited: number, sharedGaps: Array<{ key: string, label: string, category: string|null, pages: number }>, urls: string[], toAudit: string[], running: boolean, sessions: number|null }>}
+ * biggest first; urls are its pages, toAudit those without a completed
+ * audit (up to maxToAudit), sessions the site pages' summed GA sessions
+ */
+export function buildTemplates({ primaryHost, sitePages = [], auditPages = [], failingRows = [] }) {
+ if (!primaryHost) return [];
+ const groups = new Map();
+ const groupFor = (path) => {
+ // Checkout, login, legal and the like carry no opportunity (page-paths.js).
+ const template = isExcludedPath(path) ? null : templateOf(path);
+ if (!template) return null;
+ if (!groups.has(template)) {
+ groups.set(template, {
+ template,
+ urls: new Map(),
+ auditIds: new Set(),
+ auditedKeys: new Set(),
+ running: false,
+ sessions: null,
+ });
+ }
+ return groups.get(template);
+ };
+
+ for (const row of sitePages) {
+ const page = pageKey(row.url);
+ if (!page || page.host !== primaryHost) continue;
+ const group = groupFor(page.path);
+ if (!group) continue;
+ const key = page.key.toLowerCase();
+ if (!group.urls.has(key)) group.urls.set(key, row.url);
+ if (typeof row.ga_sessions === 'number') {
+ group.sessions = (group.sessions ?? 0) + row.ga_sessions;
+ }
+ }
+ for (const page of auditPages) {
+ if (page.host !== primaryHost) continue;
+ const group = groupFor(page.path);
+ if (!group) continue;
+ const key = page.key.toLowerCase();
+ if (!group.urls.has(key)) group.urls.set(key, page.url);
+ if (page.status === 'running') group.running = true;
+ if (page.score !== null) {
+ group.auditIds.add(page.auditId);
+ group.auditedKeys.add(key);
+ }
+ }
+
+ // Each audited page once per signal.
+ const pagesBySignal = new Map();
+ for (const row of failingRows) {
+ if (!pagesBySignal.has(row.audit_id)) pagesBySignal.set(row.audit_id, new Set());
+ pagesBySignal.get(row.audit_id).add(row.signal_key);
+ }
+
+ return [...groups.values()]
+ .filter((g) => g.urls.size >= TEMPLATES.minPages)
+ .map((g) => {
+ const counts = new Map();
+ for (const id of g.auditIds) {
+ for (const key of pagesBySignal.get(id) ?? []) counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ const audited = g.auditIds.size;
+ const sharedGaps =
+ audited < TEMPLATES.minAudited
+ ? []
+ : [...counts]
+ .filter(([, pages]) => pages / audited >= TEMPLATES.sharedShare)
+ .map(([key, pages]) => ({
+ key,
+ label: signalsByKey[key]?.label ?? key,
+ category: signalsByKey[key]?.category ?? null,
+ pages,
+ }))
+ .sort((a, b) => b.pages - a.pages || a.label.localeCompare(b.label))
+ .slice(0, TEMPLATES.maxGaps);
+ return {
+ template: g.template,
+ pages: g.urls.size,
+ audited,
+ sharedGaps,
+ urls: [...g.urls.values()],
+ toAudit: [...g.urls]
+ .filter(([key]) => !g.auditedKeys.has(key))
+ .map(([, url]) => url)
+ .slice(0, TEMPLATES.maxToAudit),
+ running: g.running,
+ sessions: g.sessions,
+ };
+ })
+ .sort((a, b) => b.pages - a.pages || a.template.localeCompare(b.template));
+}
+
+/**
+ * The Opportunities inbox's template rows (mockup: "/blog/* · 38 pages"):
+ * one per template whose pages share gaps, why being those gaps. Shaped like
+ * a page's row, with `template` for its pages: how many, how many audited,
+ * and the ones an audit of it starts.
+ *
+ * @param {ReturnType<typeof buildTemplates>} templates
+ * @param {(path: string) => boolean} [excludedByPattern] the brand's exclude patterns
+ */
+export function templateOpportunities(templates, excludedByPattern = () => false) {
+ return templates
+ .filter((t) => t.sharedGaps.length > 0 && !excludedByPattern(t.template))
+ .map((t) => ({
+ key: `template:${t.template}`,
+ url: null,
+ path: t.template,
+ title: null,
+ reasons: [
+ { type: 'template_gaps', gaps: t.sharedGaps.map((g) => ({ key: g.key, label: g.label })) },
+ ],
+ pinned: false,
+ running: t.running,
+ sessions: t.sessions,
+ citations: null,
+ lastAudit: null,
+ template: { pages: t.pages, audited: t.audited, toAudit: t.toAudit },
+ }));
+}
diff --git a/server/src/lib/audit/templates.test.js b/server/src/lib/audit/templates.test.js
new file mode 100644
index 000000000..0f13217d1
--- /dev/null
+++ b/server/src/lib/audit/templates.test.js
@@ -0,0 +1,164 @@
+import { describe, expect, it } from 'vitest';
+import { buildTemplates, templateOpportunities, templateOf } from './templates.js';
+
+const site = (path, ga_sessions = null) => ({ url: `https://acme.com${path}`, ga_sessions });
+const audited = (path, auditId, score = 0.5, host = 'acme.com', status = 'completed') => ({
+ key: `${host}${path}`,
+ host,
+ path,
+ url: `https://${host}${path}`,
+ auditId,
+ score,
+ status,
+});
+const failing = (auditId, ...keys) => keys.map((signal_key) => ({ audit_id: auditId, signal_key }));
+
+describe('templateOf', () => {
+ it('turns the last part of the path into a wildcard', () => {
+ expect(templateOf('/blog/milk-drinks')).toBe('/blog/*');
+ expect(templateOf('/Guides/Coffee/Espresso')).toBe('/guides/coffee/*');
+ expect(templateOf('/pricing')).toBeNull();
+ expect(templateOf('/')).toBeNull();
+ });
+});
+
+describe('buildTemplates', () => {
+ it('counts site and audited pages once, and lists the gaps most audited pages share', () => {
+ const templates = buildTemplates({
+ primaryHost: 'acme.com',
+ sitePages: [
+ site('/blog/a'),
+ site('/blog/b'),
+ site('/blog/c'),
+ site('/blog/d'),
+ site('/pricing'),
+ ],
+ auditPages: [audited('/blog/a', 'a1'), audited('/blog/b', 'b1'), audited('/blog/c', 'c1')],
+ failingRows: [
+ ...failing('a1', 'author-byline', 'faq-schema', 'og-meta'),
+ ...failing('b1', 'author-byline', 'faq-schema'),
+ ...failing('c1', 'author-byline'),
+ ],
+ });
+ expect(templates).toEqual([
+ {
+ template: '/blog/*',
+ pages: 4,
+ audited: 3,
+ urls: [
+ 'https://acme.com/blog/a',
+ 'https://acme.com/blog/b',
+ 'https://acme.com/blog/c',
+ 'https://acme.com/blog/d',
+ ],
+ // The pages an audit of the template starts: the one not audited.
+ toAudit: ['https://acme.com/blog/d'],
+ running: false,
+ sessions: null,
+ // og-meta fails on one of three: not the template's.
+ sharedGaps: [
+ { key: 'author-byline', label: 'Author byline', category: 'authority', pages: 3 },
+ { key: 'faq-schema', label: 'FAQ schema', category: 'structure', pages: 2 },
+ ],
+ },
+ ]);
+ });
+
+ it('needs three pages, two audited pages for a gap, and the primary host', () => {
+ expect(
+ buildTemplates({
+ primaryHost: 'acme.com',
+ sitePages: [site('/docs/a'), site('/docs/b')],
+ }),
+ ).toEqual([]);
+
+ const [only] = buildTemplates({
+ primaryHost: 'acme.com',
+ sitePages: [site('/docs/a'), site('/docs/b'), site('/docs/c')],
+ auditPages: [audited('/docs/a', 'a1'), audited('/docs/x', 'x1', 0.5, 'other.com')],
+ failingRows: failing('a1', 'author-byline'),
+ });
+ expect(only).toMatchObject({ template: '/docs/*', pages: 3, audited: 1, sharedGaps: [] });
+ expect(buildTemplates({ primaryHost: null, sitePages: [site('/a/b')] })).toEqual([]);
+ });
+
+ it("leaves out an audit that didn't complete, and orders the biggest template first", () => {
+ const templates = buildTemplates({
+ primaryHost: 'acme.com',
+ sitePages: ['/a/1', '/a/2', '/a/3', '/b/1', '/b/2', '/b/3', '/b/4'].map(site),
+ auditPages: [audited('/a/1', 'x1', null), audited('/a/2', 'x2'), audited('/a/3', 'x3')],
+ failingRows: [...failing('x1', 'faq-schema'), ...failing('x2', 'faq-schema')],
+ });
+ expect(templates.map((t) => [t.template, t.pages, t.audited])).toEqual([
+ ['/b/*', 4, 0],
+ ['/a/*', 3, 2],
+ ]);
+ // Failing on one of the two completed audits: under two-thirds.
+ expect(templates[1].sharedGaps).toEqual([]);
+ });
+
+ it("sums the site pages' sessions, and marks a template with an audit running", () => {
+ const [blog] = buildTemplates({
+ primaryHost: 'acme.com',
+ sitePages: [site('/blog/a', 10), site('/blog/b', 5), site('/blog/c')],
+ auditPages: [audited('/blog/c', 'c1', null, 'acme.com', 'running')],
+ });
+ expect(blog).toMatchObject({ sessions: 15, running: true, audited: 0 });
+ expect(blog.toAudit).toHaveLength(3);
+ });
+});
+
+describe('buildTemplates and the pages that carry no opportunity', () => {
+ it('leaves out account, checkout or legal pages, as the inbox does', () => {
+ const templates = buildTemplates({
+ primaryHost: 'acme.com',
+ sitePages: [
+ ...['/account/orders', '/account/profile', '/account/billing'].map((p) => site(p)),
+ ...['/blog/a', '/blog/b', '/blog/legal'].map((p) => site(p)),
+ ],
+ });
+ // /account/* is gone; /blog/legal isn't one of the blog's pages.
+ expect(templates).toEqual([]);
+ });
+});
+
+describe('templateOpportunities', () => {
+ const blog = {
+ template: '/blog/*',
+ pages: 38,
+ audited: 12,
+ sharedGaps: [
+ { key: 'author-byline', label: 'Author byline', category: 'authority', pages: 10 },
+ ],
+ urls: [],
+ toAudit: ['https://acme.com/blog/x'],
+ running: false,
+ sessions: 900,
+ };
+
+ it('turns a template whose pages share gaps into an inbox row', () => {
+ expect(templateOpportunities([blog, { ...blog, template: '/docs/*', sharedGaps: [] }])).toEqual(
+ [
+ {
+ key: 'template:/blog/*',
+ url: null,
+ path: '/blog/*',
+ title: null,
+ reasons: [
+ { type: 'template_gaps', gaps: [{ key: 'author-byline', label: 'Author byline' }] },
+ ],
+ pinned: false,
+ running: false,
+ sessions: 900,
+ citations: null,
+ lastAudit: null,
+ template: { pages: 38, audited: 12, toAudit: ['https://acme.com/blog/x'] },
+ },
+ ],
+ );
+ });
+
+ it("leaves out a template the brand's exclude patterns cover", () => {
+ expect(templateOpportunities([blog], (path) => path.startsWith('/blog/'))).toEqual([]);
+ });
+});
diff --git a/server/src/routes/audits-opportunities.test.js b/server/src/routes/audits-opportunities.test.js
index 16a210f0f..218296ccb 100644
--- a/server/src/routes/audits-opportunities.test.js
+++ b/server/src/routes/audits-opportunities.test.js
@@ -291,6 +291,80 @@ describe('GET /api/audits/opportunities', () => {
expect(rpcCalls.map((c) => c.name)).not.toContain('audit_competitor_cited_prompts');
});
+ describe('templates (SA-007)', () => {
+ const recent = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
+ const blogAudit = (id, path, score) => ({
+ id,
+ brand_id: brandId,
+ url: `https://acme.com${path}`,
+ final_url: `https://acme.com${path}`,
+ status: 'completed',
+ total_score: score,
+ created_at: recent,
+ });
+ beforeEach(() => {
+ tables.site_pages.push(
+ ...['/blog/a', '/blog/b', '/blog/c'].map((path) => ({
+ brand_id: brandId,
+ url: `https://acme.com${path}`,
+ title: null,
+ ga_sessions: 10,
+ ai_citations: 0,
+ })),
+ );
+ tables.site_audits = [blogAudit('a1', '/blog/a', '0.5'), blogAudit('b1', '/blog/b', '0.6')];
+ tables.audit_signal_results = [
+ { audit_id: 'a1', signal_key: 'author-byline', status: 'fail' },
+ { audit_id: 'b1', signal_key: 'author-byline', status: 'warn' },
+ ];
+ });
+
+ it('lists a template whose pages share gaps as a row, and eases its pages', async () => {
+ const body = await (await fetch(`${baseUrl}/opportunities?brandId=${brandId}`)).json();
+ const template = body.opportunities.find((o) => o.key === 'template:/blog/*');
+ expect(template).toMatchObject({
+ url: null,
+ path: '/blog/*',
+ reasons: [
+ { type: 'template_gaps', gaps: [{ key: 'author-byline', label: 'Author byline' }] },
+ ],
+ sessions: 30,
+ // The AI visits of its pages added up (the stub gives /blog/c 7).
+ aiVisits: 7,
+ template: { pages: 3, audited: 2, toAudit: ['https://acme.com/blog/c'] },
+ priority: expect.any(Number),
+ });
+ // /blog/c, never audited, gets the template fix on its ease.
+ const page = body.opportunities.find((o) => o.path === '/blog/c');
+ expect(page.priorityParts.ease).toBe(0.9);
+ // The AI visits were asked for the template's pages too, once each.
+ const { args } = rpcCalls.find((c) => c.name === 'ae_page_traffic_evidence');
+ expect(new Set(args.p_pages).size).toBe(args.p_pages.length);
+ expect(args.p_pages).toEqual(expect.arrayContaining(['https://acme.com/blog/a']));
+ });
+
+ it('leaves the template row out under an exclude pattern', async () => {
+ tables.site_audit_brand_settings = [{ brand_id: brandId, exclude_patterns: ['/blog/*'] }];
+ const body = await (await fetch(`${baseUrl}/opportunities?brandId=${brandId}`)).json();
+ expect(body.opportunities.map((o) => o.path)).toEqual(['/pricing']);
+ });
+
+ it('GET /templates lists the templates with their shared gaps', async () => {
+ const res = await fetch(`${baseUrl}/templates?brandId=${brandId}`);
+ expect(res.status).toBe(200);
+ expect((await res.json()).templates).toEqual([
+ expect.objectContaining({
+ template: '/blog/*',
+ pages: 3,
+ audited: 2,
+ sharedGaps: [
+ { key: 'author-byline', label: 'Author byline', category: 'authority', pages: 2 },
+ ],
+ }),
+ ]);
+ });
+ });
+
it('needs a brand', async () => {
expect((await fetch(`${baseUrl}/opportunities`)).status).toBe(400);
});
diff --git a/server/src/routes/audits-pages.test.js b/server/src/routes/audits-pages.test.js
index b7789abaa..70633eed6 100644
--- a/server/src/routes/audits-pages.test.js
+++ b/server/src/routes/audits-pages.test.js
@@ -167,10 +167,21 @@ describe('GET /api/audits/pages', () => {
['/broken', 'failed', null],
]);
expect(body.pages[0]).toMatchObject({ auditId: 'p2', score: 0.63, previousScore: 0.58 });
+ // Top-level pages have no template (SA-007).
+ expect(body.pages.map((p) => p.template)).toEqual([null, null, null]);
// Issues are counted for the latest completed audit of each row only.
expect(signalQueries).toEqual([['p2', 'x1']]);
});
+ it("names a primary-domain page's template", async () => {
+ audits.push(audit('n1', 'https://acme.com/blog/milk-drinks', 20, '0.5'));
+ audits.push(audit('n2', 'https://other.com/blog/x', 20, '0.5'));
+ const body = await (await fetch(`${baseUrl}/pages?brandId=b1`)).json();
+ const byPath = Object.fromEntries(body.pages.map((p) => [`${p.host}${p.path}`, p.template]));
+ expect(byPath['acme.com/blog/milk-drinks']).toBe('/blog/*');
+ expect(byPath['other.com/blog/x']).toBeNull();
+ });
+
it('pages over pages, not audits', async () => {
const res = await fetch(`${baseUrl}/pages?brandId=b1&limit=1&offset=1`);
const body = await res.json();
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.js
index d68382a89..427f51e85 100644
--- a/server/src/routes/audits.js
+++ b/server/src/routes/audits.js
@@ -40,11 +40,13 @@ import {
competitorGapPages,
EXCLUDE_PATTERN_MAX_LENGTH,
EXCLUDE_PATTERNS_MAX,
+ excludePatternMatcher,
normalizeExcludePattern,
opportunityKey,
} from '../lib/audit/opportunities.js';
import { AUTO_AUDIT } from '../lib/audit/auto-audit.js';
import { rankOpportunities } from '../lib/audit/priority.js';
+import { buildTemplates, templateOf, templateOpportunities } from '../lib/audit/templates.js';
import { ENGINE_THRESHOLDS } from '../config/action-engine.js';
import { runSignals } from '../lib/audit/engine.js';
import { evaluateLlmSignals } from '../lib/audit/llm-signals.js';
@@ -533,15 +535,18 @@ router.get('/pages', async (req, res) => {
const all = buildAuditPages(rows);
const pages = all.slice(offset, offset + limit);
const issues = await countIssues(pages.filter((p) => p.score !== null).map((p) => p.auditId));
+ const primaryHost = normStoredDomain(primary);
return res.json({
success: true,
pages: pages.map((p) => ({
...p,
issues: p.score === null ? null : (issues.get(p.auditId) ?? 0),
+ // The page's template on the primary domain, for Group by template (SA-007).
+ template: p.host === primaryHost ? templateOf(p.path) : null,
})),
total: all.length,
- primaryHost: normStoredDomain(primary),
+ primaryHost,
});
} catch (err) {
if (err.status) {
@@ -691,6 +696,26 @@ async function opportunityAiVisits(brandId, urls) {
return aiVisitsByPage(data);
}
+/**
+ * The brand's template groups (SA-007): its primary-domain pages by template,
+ * with the gaps most of a template's audited pages share. Reads the failing
+ * and warning signals of those pages' latest audits.
+ */
+async function readTemplateGroups({ primaryHost, sitePages, auditPages }) {
+ if (!primaryHost) return [];
+ const ids = auditPages
+ .filter((p) => p.host === primaryHost && p.score !== null && templateOf(p.path))
+ .map((p) => p.auditId);
+ const failingRows = await readByAuditIds(ids, ISSUE_COUNT_CHUNK, (chunk) =>
+ supabaseAdmin
+ .from('audit_signal_results')
+ .select('audit_id, signal_key')
+ .in('audit_id', chunk)
+ .in('status', ['fail', 'warn']),
+ );
+ return buildTemplates({ primaryHost, sitePages, auditPages, failingRows });
+}
+
/** A brand's exclude patterns (SA-006 settings), as stored. */
async function readExcludePatterns(brandId) {
const { data, error } = await supabaseAdmin
@@ -735,27 +760,43 @@ export async function readOpportunityInbox(brandId) {
]);
for (const read of [gaPages, sitePages, audits, prefs]) if (read.error) throw read.error;
- const competitorPages = await competitorOpportunityPages(brandId, sitePages.data ?? []);
+ const primaryHost = normStoredDomain(primary);
+ const auditPages = buildAuditPages(audits.data);
+ const [competitorPages, templates] = await Promise.all([
+ competitorOpportunityPages(brandId, sitePages.data ?? []),
+ readTemplateGroups({ primaryHost, sitePages: sitePages.data ?? [], auditPages }),
+ ]);
const { rows, excluded } = buildOpportunities({
- primaryHost: normStoredDomain(primary),
+ primaryHost,
gaPages: gaPages.data ?? [],
sitePages: sitePages.data ?? [],
- auditPages: buildAuditPages(audits.data),
+ auditPages,
competitorPages,
prefs: prefs.data ?? [],
excludePatterns,
staleDays: ENGINE_THRESHOLDS.detection.auditMaxAgeDays,
});
- const visits = await opportunityAiVisits(
- brandId,
- rows.map((r) => r.url),
- );
+ // Templates whose pages share gaps are rows too (SA-007, the mockup's
+ // "/blog/* · 38 pages"), with their pages' AI visits added up.
+ const shared = templates.filter((t) => t.sharedGaps.length > 0);
+ const templateRows = templateOpportunities(shared, excludePatternMatcher(excludePatterns));
+ const urlsOf = new Map(shared.map((t) => [`template:${t.template}`, t.urls]));
+ const visits = await opportunityAiVisits(brandId, [
+ ...new Set([...rows.map((r) => r.url), ...templateRows.flatMap((r) => urlsOf.get(r.key))]),
+ ]);
+ const visitsOf = (urls) =>
+ visits === null ? null : urls.reduce((sum, url) => sum + (visits.get(url) ?? 0), 0);
return {
- // Scored and ordered once each page has its AI visits (SA-005).
+ // Scored and ordered once each page has its AI visits (SA-005); a page
+ // whose template shares its gaps is easier to fix (SA-007).
opportunities: rankOpportunities(
- rows.map((r) => ({ ...r, aiVisits: visits === null ? null : (visits.get(r.url) ?? 0) })),
+ [
+ ...rows.map((r) => ({ ...r, aiVisits: visitsOf([r.url]) })),
+ ...templateRows.map((r) => ({ ...r, aiVisits: visitsOf(urlsOf.get(r.key)) })),
+ ],
(sitePages.data ?? []).map((p) => p.ga_sessions),
+ new Set(shared.map((t) => t.template)),
),
excluded,
};
@@ -849,6 +890,38 @@ router.put('/opportunities/prefs', async (req, res) => {
}
});
+// GET /api/audits/templates?brandId=… — the brand's template groups (SA-007):
+// "/blog/* · 38 pages", with the gaps most of its audited pages share.
+// Registered before /:id so "templates" isn't matched as an audit id.
+router.get('/templates', async (req, res) => {
+ const { brandId } = req.query;
+ if (!brandId) {
+ return res.status(400).json({ success: false, message: 'brandId is required' });
+ }
+ try {
+ await assertBrandAccess(brandId, req.user?.id);
+ const [primary, sitePages, audits] = await Promise.all([
+ primaryDomainOf(brandId),
+ supabaseAdmin.from('site_pages').select('url').eq('brand_id', brandId),
+ readBrandAudits(brandId),
+ ]);
+ for (const read of [sitePages, audits]) if (read.error) throw read.error;
+
+ const templates = await readTemplateGroups({
+ primaryHost: normStoredDomain(primary),
+ sitePages: sitePages.data ?? [],
+ auditPages: buildAuditPages(audits.data),
+ });
+ return res.json({ success: true, templates });
+ } catch (err) {
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ req.log.error({ err }, 'audit templates failed');
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
/** Roles that may change Site Audit settings, as for Daily Pulse's. */
const SETTINGS_ROLES = ['admin', 'manager'];
diff --git a/web/messages/en.json b/web/messages/en.json
index f246c96cd..03f172fbb 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -2119,7 +2119,12 @@
"needs_work": "Needs work",
"running": "Running",
"failed": "Failed"
- }
+ },
+ "groupByTemplate": "Group by template",
+ "templatesFailed": "Couldn't group the pages by template",
+ "templateAudited": "{audited} of {pages} pages audited",
+ "templateFix": "Fix once: <b>{gaps}</b> · applies to {pages} pages",
+ "otherPages": "Other pages"
},
"lists": {
"label": "Site Audit lists",
@@ -2170,7 +2175,12 @@
"restoredToast": "{count, plural, one {# page restored} other {# pages restored}}",
"empty": "No pages to audit right now. Opportunities come from Google Analytics (valuable pages without AI traffic), from prompts where a competitor is cited and you aren't, and from your site's pages that were never audited or not in {days} days.",
"showMore": "Show more",
- "prefsFailed": "Couldn't update the pages"
+ "prefsFailed": "Couldn't update the pages",
+ "templatePages": "· {pages} pages",
+ "templateFixOnce": "Fix once, applies to {pages} pages",
+ "templateAudited": "{audited} of {pages}",
+ "templateExcludedToast": "{count, plural, one {Excluded {template} and its pages} other {Excluded # templates and their pages}}",
+ "templateRestoredToast": "The template's pages are back"
},
"overview": {
"yourDomain": "your domain",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
index 87b9d462a..614985a7e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.test.tsx
@@ -18,12 +18,13 @@ const onReaudit = vi.fn();
const onExport = vi.fn();
const onClear = vi.fn();
-function render(count: number, quota: AuditQuota | null, starting = false) {
+function render(count: number, quota: AuditQuota | null, starting = false, audits?: number) {
act(() => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
<AuditBulkBar
count={count}
+ audits={audits}
quota={quota}
starting={starting}
onAudit={onReaudit}
@@ -104,6 +105,15 @@ describe('AuditBulkBar', () => {
expect(button('Re-audit').disabled).toBe(true);
});
+ it("counts a template's pages, not the rows, against what's left (SA-007)", () => {
+ render(1, { used: 0, limit: 100, remaining: 20 }, false, 26);
+ expect(usage()?.textContent).toBe('Uses 26 of your 20 audits · select up to 20');
+ expect(button('Re-audit').disabled).toBe(true);
+ // Nothing to audit (a template audited in full): the button stays off.
+ render(1, { used: 0, limit: 100, remaining: 20 }, false, 0);
+ expect(button('Re-audit').disabled).toBe(true);
+ });
+
it('counts nothing against an unlimited plan', () => {
render(40, { used: 0, limit: -1, remaining: -1 });
expect(usage()).toBeUndefined();
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
index 2768671ab..65a07db57 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_bulk-bar.tsx
@@ -65,6 +65,7 @@ export function ExportMenu({
*/
export function AuditBulkBar({
count,
+ audits,
quota,
starting,
auditLabel,
@@ -74,6 +75,8 @@ export function AuditBulkBar({
children,
}: {
count: number;
+ /** Audits the audit button starts, when not one per selected row (a template's pages). */
+ audits?: number;
quota: AuditQuota | null;
starting: boolean;
auditLabel?: string;
@@ -87,7 +90,8 @@ export function AuditBulkBar({
const t = useTranslations('audit.bulk');
const limited = quota !== null && quota.limit !== -1;
const remaining = quota?.remaining ?? 0;
- const over = limited && count > remaining;
+ const uses = audits ?? count;
+ const over = limited && uses > remaining;
return (
<div
@@ -105,8 +109,8 @@ export function AuditBulkBar({
{remaining === 0
? t('noneLeft')
: over
- ? t('overQuota', { count, remaining })
- : t('uses', { count, remaining })}
+ ? t('overQuota', { count: uses, remaining })
+ : t('uses', { count: uses, remaining })}
</span>
))}
<div className="ml-auto flex flex-wrap items-center justify-end gap-1">
@@ -115,7 +119,7 @@ export function AuditBulkBar({
size="sm"
className="h-7 gap-1.5 text-xs"
onClick={onAudit}
- disabled={starting || over}
+ disabled={starting || over || uses === 0}
>
{starting ? (
<Loader2 className="h-3 w-3 animate-spin" />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.test.tsx
index 2a2b68f1e..a863779c4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.test.tsx
@@ -4,7 +4,11 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../messages/en.json';
import type { AuditOpportunity, ExcludedPage } from '@/lib/actions/audits';
-import { OPPORTUNITIES_STEP, OpportunitiesTable } from './_opportunities-table';
+import {
+ OPPORTUNITIES_STEP,
+ OpportunitiesTable,
+ opportunityAuditUrls,
+} from './_opportunities-table';
(
globalThis as typeof globalThis & {
@@ -150,6 +154,42 @@ describe('OpportunitiesTable', () => {
]);
});
+ it("shows a template's row: its pages, the gaps they share and how many are audited (SA-007)", () => {
+ const template = opportunity({
+ key: 'template:/blog/*',
+ url: null,
+ path: '/blog/*',
+ title: null,
+ reasons: [
+ {
+ type: 'template_gaps',
+ gaps: [
+ { key: 'author-byline', label: 'Author byline' },
+ { key: 'faq-schema', label: 'FAQ schema' },
+ ],
+ },
+ ],
+ aiVisits: 112,
+ lastAudit: null,
+ priority: 69,
+ template: { pages: 38, audited: 12, toAudit: ['https://acme.com/blog/x'] },
+ });
+ render([template]);
+ expect(cells(rows()[0])).toEqual([
+ '',
+ '69',
+ '/blog/* · 38 pages',
+ 'Author bylineFAQ schema',
+ '112',
+ '12 of 38',
+ ]);
+ // Not a link: a template has no one page to open.
+ expect(rows()[0].querySelectorAll('td')[2].querySelector('a')).toBeNull();
+ expect(
+ rows()[0].querySelectorAll('td')[2].querySelector('[title]')?.getAttribute('title'),
+ ).toBe('Fix once, applies to 38 pages');
+ });
+
it('shows the priority, dark from 80, with its parts on hover', () => {
render([opportunity(), blog]);
const pill = (row: Element) => row.querySelectorAll('td')[1].querySelector('span')!;
@@ -210,3 +250,23 @@ describe('OpportunitiesTable', () => {
expect(container.querySelector('table')).toBeNull();
});
});
+
+describe('opportunityAuditUrls', () => {
+ it("audits each page, and a template's pages not audited yet, once each", () => {
+ expect(
+ opportunityAuditUrls([
+ opportunity(),
+ opportunity({
+ key: 'template:/blog/*',
+ url: null,
+ path: '/blog/*',
+ template: {
+ pages: 3,
+ audited: 1,
+ toAudit: ['https://acme.com/blog/b', 'https://acme.com/pricing'],
+ },
+ }),
+ ]),
+ ).toEqual(['https://acme.com/pricing', 'https://acme.com/blog/b']);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.tsx
index cfd7b55ac..35c00ccd4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_opportunities-table.tsx
@@ -46,6 +46,16 @@ function PriorityPill({ row }: { row: AuditOpportunity }) {
);
}
+/**
+ * The pages an audit of the selected inbox rows starts: each page, and a
+ * template's pages not audited yet (SA-007), once each.
+ */
+export function opportunityAuditUrls(rows: AuditOpportunity[]): string[] {
+ return [
+ ...new Set(rows.flatMap((o) => (o.template ? o.template.toAudit : o.url ? [o.url] : []))),
+ ];
+}
+
/** Rows shown at first, and added by Show more. */
export const OPPORTUNITIES_STEP = 50;
@@ -89,6 +99,9 @@ function ReasonChips({ row }: { row: AuditOpportunity }) {
})}
</Chip>
);
+ case 'template_gaps':
+ // The gaps the template's audited pages share (SA-007).
+ return reason.gaps.map((gap) => <Chip key={`gap-${gap.key}`}>{gap.label}</Chip>);
}
};
return (
@@ -231,16 +244,29 @@ export function OpportunitiesTable({
<PriorityPill row={row} />
</TableCell>
<TableCell className="max-w-0">
- <a
- href={row.url}
- target="_blank"
- rel="noopener noreferrer"
- title={row.title ?? row.url}
- className="group inline-flex max-w-full items-center gap-1 font-medium hover:underline"
- >
- <span className="truncate">{row.path}</span>
- <ExternalLink className="h-3 w-3 shrink-0 text-muted-foreground opacity-0 group-hover:opacity-100" />
- </a>
+ {row.template ? (
+ // A template's row (SA-007): "/blog/* · 38 pages".
+ <span
+ className="inline-flex max-w-full items-center gap-1"
+ title={t('templateFixOnce', { pages: row.template.pages })}
+ >
+ <span className="truncate font-medium">{row.path}</span>
+ <span className="shrink-0 text-muted-foreground">
+ {` ${t('templatePages', { pages: row.template.pages })}`}
+ </span>
+ </span>
+ ) : (
+ <a
+ href={row.url ?? undefined}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={row.title ?? row.url ?? undefined}
+ className="group inline-flex max-w-full items-center gap-1 font-medium hover:underline"
+ >
+ <span className="truncate">{row.path}</span>
+ <ExternalLink className="h-3 w-3 shrink-0 text-muted-foreground opacity-0 group-hover:opacity-100" />
+ </a>
+ )}
</TableCell>
{/* Wide enough for a row of chips; more wrap onto a second line. */}
<TableCell className="min-w-[18rem] whitespace-normal">
@@ -255,6 +281,11 @@ export function OpportunitiesTable({
<Loader2 className="h-3 w-3 animate-spin" />
{t('running')}
</span>
+ ) : row.template ? (
+ t('templateAudited', {
+ audited: row.template.audited,
+ pages: row.template.pages,
+ })
) : row.lastAudit ? (
<Link
href={`/dashboard/audit/${row.lastAudit.auditId}`}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsx
index f7bd79c4d..67c9eea0c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.test.tsx
@@ -3,8 +3,8 @@ import { createRoot, type Root } from 'react-dom/client';
import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../messages/en.json';
-import type { AuditedPage } from '@/lib/actions/audits';
-import { AuditPagesTable, pageLabel } from './_pages-table';
+import type { AuditedPage, AuditTemplate } from '@/lib/actions/audits';
+import { AuditPagesTable, groupPagesByTemplate, pageLabel } from './_pages-table';
(
globalThis as typeof globalThis & {
@@ -69,7 +69,11 @@ const onSelect = vi.fn();
function render(
pages: AuditedPage[],
total = pages.length,
- { selected = new Set<string>(), toolbar = null as React.ReactNode } = {},
+ {
+ selected = new Set<string>(),
+ toolbar = null as React.ReactNode,
+ templates = null as AuditTemplate[] | null,
+ } = {},
) {
act(() => {
root.render(
@@ -85,6 +89,7 @@ function render(
onSelect={onSelect}
headerAction={<button type="button">Export all</button>}
toolbar={toolbar}
+ templates={templates}
/>
</NextIntlClientProvider>,
);
@@ -244,6 +249,58 @@ describe('AuditPagesTable selection', () => {
});
});
+describe('Group by template (SA-007)', () => {
+ const blog: AuditTemplate = {
+ template: '/blog/*',
+ pages: 38,
+ audited: 12,
+ sharedGaps: [
+ { key: 'author-byline', label: 'Author byline', category: 'authority', pages: 11 },
+ { key: 'faq-schema', label: 'FAQ schema', category: 'structure', pages: 9 },
+ ],
+ };
+ const guides: AuditTemplate = { template: '/guides/*', pages: 5, audited: 1, sharedGaps: [] };
+ const post = (path: string, template: string | null) =>
+ page({ key: `acme.com${path}`, path, url: `https://acme.com${path}`, template });
+
+ it('groups the shown pages by template, biggest first, the rest under Other pages', () => {
+ const pages = [
+ post('/pricing', null),
+ post('/guides/a', '/guides/*'),
+ post('/blog/a', '/blog/*'),
+ post('/blog/b', '/blog/*'),
+ // A template under three pages isn't one: it goes with the rest.
+ post('/docs/a', '/docs/*'),
+ ];
+ expect(
+ groupPagesByTemplate(pages, [blog, guides]).map((g) => [
+ g.template?.template ?? null,
+ g.pages.map((p) => p.path),
+ ]),
+ ).toEqual([
+ ['/blog/*', ['/blog/a', '/blog/b']],
+ ['/guides/*', ['/guides/a']],
+ [null, ['/pricing', '/docs/a']],
+ ]);
+ });
+
+ it('heads each group with its pages and what one fix covers', () => {
+ render([post('/pricing', null), post('/blog/a', '/blog/*')], 2, { templates: [blog, guides] });
+ expect(rows().map((r) => r.textContent?.trim().slice(0, 120))).toEqual([
+ '/blog/* · 12 of 38 pages audited · Fix once: Author byline, FAQ schema · applies to 38 pages',
+ expect.stringContaining('/blog/a'),
+ 'Other pages',
+ expect.stringContaining('/pricing'),
+ ]);
+ });
+
+ it('lists the pages as before when grouping is off', () => {
+ render([post('/pricing', null), post('/blog/a', '/blog/*')]);
+ expect(rows()).toHaveLength(2);
+ expect(container.textContent).not.toContain('Other pages');
+ });
+});
+
describe('pageLabel', () => {
it("lists the brand's own pages by path and other sites by host", () => {
expect(pageLabel({ host: 'acme.com', path: '/pricing' }, 'acme.com')).toBe('/pricing');
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx
index fdb37e643..9bb4550b1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_pages-table.tsx
@@ -26,10 +26,60 @@ import {
TableRow,
} from '@/components/ui/table';
import { pct, scoreColor } from '@/components/audit/audit-report';
-import type { AuditedPage, AuditedPageStatus, AuditRun } from '@/lib/actions/audits';
+import type { AuditedPage, AuditedPageStatus, AuditRun, AuditTemplate } from '@/lib/actions/audits';
import { formatDate, formatDateTime, formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
+/**
+ * The shown pages by template (SA-007's Group by template): the templates in
+ * the server's order (biggest first) that have pages shown, then the pages
+ * without one, as "other" (template null).
+ */
+export function groupPagesByTemplate(
+ pages: AuditedPage[],
+ templates: AuditTemplate[],
+): { template: AuditTemplate | null; pages: AuditedPage[] }[] {
+ const known = new Map(templates.map((t) => [t.template, t]));
+ const byTemplate = new Map<string, AuditedPage[]>();
+ const other: AuditedPage[] = [];
+ for (const page of pages) {
+ const key = page.template && known.has(page.template) ? page.template : null;
+ if (key === null) other.push(page);
+ else byTemplate.set(key, [...(byTemplate.get(key) ?? []), page]);
+ }
+ return [
+ ...templates
+ .filter((t) => byTemplate.has(t.template))
+ .map((t) => ({ template: t, pages: byTemplate.get(t.template) ?? [] })),
+ ...(other.length > 0 ? [{ template: null, pages: other }] : []),
+ ];
+}
+
+/** A template group's header: "/blog/* · 12 of 38 pages audited · Fix once: … · applies to 38 pages". */
+function TemplateHeader({ template }: { template: AuditTemplate | null }) {
+ const t = useTranslations('audit.pages');
+ if (!template) return <span className="font-medium">{t('otherPages')}</span>;
+ return (
+ <span>
+ <span className="font-medium">{template.template}</span>
+ <span className="text-muted-foreground">
+ {' · '}
+ {t('templateAudited', { audited: template.audited, pages: template.pages })}
+ {template.sharedGaps.length > 0 && (
+ <>
+ {' · '}
+ {t.rich('templateFix', {
+ b: (chunks) => <span className="font-medium text-foreground">{chunks}</span>,
+ gaps: template.sharedGaps.map((g) => g.label).join(', '),
+ pages: template.pages,
+ })}
+ </>
+ )}
+ </span>
+ </span>
+ );
+}
+
const STATUS_CLASS: Record<AuditedPageStatus, string> = {
good: 'bg-green-600/10 text-green-700 dark:bg-green-500/15 dark:text-green-400',
needs_work: 'bg-amber-500/10 text-amber-700 dark:bg-amber-500/15 dark:text-amber-400',
@@ -155,6 +205,7 @@ export function AuditPagesTable({
headerAction,
toolbar,
showTitle = true,
+ templates = null,
}: {
pages: AuditedPage[];
total: number;
@@ -170,6 +221,8 @@ export function AuditPagesTable({
toolbar?: ReactNode;
/** Off inside the Pages tab, whose trigger already names the list. */
showTitle?: boolean;
+ /** Given while Group by template is on (SA-007): rows grouped under their template. */
+ templates?: AuditTemplate[] | null;
}) {
const t = useTranslations('audit');
const router = useRouter();
@@ -226,101 +279,124 @@ export function AuditPagesTable({
</TableRow>
</TableHeader>
<TableBody>
- {pages.map((page, i) => {
- const label = pageLabel(page, primaryHost);
- const historyId = `${idPrefix}-history-${i}`;
- const expanded = open.has(page.key);
- return (
- <Fragment key={page.key}>
- <TableRow
- className="cursor-pointer"
- data-state={selected.has(page.key) ? 'selected' : undefined}
- onClick={() => router.push(`/dashboard/audit/${page.auditId}`)}
- >
- <TableCell className="w-8 pr-0">
- <Checkbox
- aria-label={t('pages.select', { page: label })}
- disabled={page.status === 'running'}
- checked={selected.has(page.key)}
- onClick={(e) => e.stopPropagation()}
- onCheckedChange={(on) => onSelect([page.key], on === true)}
- />
- </TableCell>
- <TableCell className="w-9 pr-0">
- <Button
- variant="ghost"
- size="icon"
- className="h-7 w-7"
- aria-expanded={expanded}
- aria-controls={historyId}
- aria-label={t(expanded ? 'pages.hideHistory' : 'pages.showHistory', {
- page: label,
- })}
- onClick={(e) => {
- e.stopPropagation();
- toggle(page.key);
- }}
- >
- <ChevronRight
- className={cn('h-4 w-4 transition-transform', expanded && 'rotate-90')}
- />
- </Button>
- </TableCell>
- <TableCell className="max-w-0">
- <Link
- href={`/dashboard/audit/${page.auditId}`}
- onClick={(e) => e.stopPropagation()}
- title={page.url}
- className="block truncate font-medium hover:underline"
- >
- {label}
- </Link>
- </TableCell>
- <TableCell>
- <div className="flex items-center gap-2">
- <span
- className={cn('w-7 font-semibold tabular-nums', scoreColor(page.score))}
- >
- {pct(page.score) ?? '—'}
- </span>
- <ScoreSparkline
- points={page.trend}
- label={t('pages.trend', {
- scores: page.trend.map((s) => pct(s)).join(', '),
- })}
- />
- </div>
- </TableCell>
- <TableCell className="text-right tabular-nums">
- {page.issues === null ? '—' : formatNumber(page.issues)}
- </TableCell>
- <TableCell>
- <StatusPill status={page.status} />
- </TableCell>
- <TableCell className="text-muted-foreground">
- {formatDate(page.lastAuditedAt)}
+ {(templates
+ ? groupPagesByTemplate(pages, templates)
+ : [{ template: undefined, pages }]
+ ).map((group) => (
+ <Fragment
+ key={group.template === undefined ? 'all' : (group.template?.template ?? 'other')}
+ >
+ {group.template !== undefined && (
+ <TableRow className="bg-muted/40 hover:bg-muted/40">
+ <TableCell colSpan={7} className="py-2 text-xs whitespace-normal">
+ <TemplateHeader template={group.template} />
</TableCell>
</TableRow>
- {expanded && (
- <TableRow id={historyId} className="hover:bg-transparent">
- <TableCell colSpan={2} />
- <TableCell colSpan={5} className="pt-0 whitespace-normal">
- <ul className="divide-y rounded-md border">
- {page.runs.map((run) => (
- <HistoryRun key={run.id} run={run} onDelete={onDeleteRun} />
- ))}
- </ul>
- {page.runCount > page.runs.length && (
- <p className="mt-1.5 text-xs text-muted-foreground">
- {t('pages.moreRuns', { count: page.runCount - page.runs.length })}
- </p>
- )}
- </TableCell>
- </TableRow>
- )}
- </Fragment>
- );
- })}
+ )}
+ {group.pages.map((page) => {
+ const i = pages.indexOf(page);
+ const label = pageLabel(page, primaryHost);
+ const historyId = `${idPrefix}-history-${i}`;
+ const expanded = open.has(page.key);
+ return (
+ <Fragment key={page.key}>
+ <TableRow
+ className="cursor-pointer"
+ data-state={selected.has(page.key) ? 'selected' : undefined}
+ onClick={() => router.push(`/dashboard/audit/${page.auditId}`)}
+ >
+ <TableCell className="w-8 pr-0">
+ <Checkbox
+ aria-label={t('pages.select', { page: label })}
+ disabled={page.status === 'running'}
+ checked={selected.has(page.key)}
+ onClick={(e) => e.stopPropagation()}
+ onCheckedChange={(on) => onSelect([page.key], on === true)}
+ />
+ </TableCell>
+ <TableCell className="w-9 pr-0">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7"
+ aria-expanded={expanded}
+ aria-controls={historyId}
+ aria-label={t(expanded ? 'pages.hideHistory' : 'pages.showHistory', {
+ page: label,
+ })}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggle(page.key);
+ }}
+ >
+ <ChevronRight
+ className={cn(
+ 'h-4 w-4 transition-transform',
+ expanded && 'rotate-90',
+ )}
+ />
+ </Button>
+ </TableCell>
+ <TableCell className="max-w-0">
+ <Link
+ href={`/dashboard/audit/${page.auditId}`}
+ onClick={(e) => e.stopPropagation()}
+ title={page.url}
+ className="block truncate font-medium hover:underline"
+ >
+ {label}
+ </Link>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <span
+ className={cn(
+ 'w-7 font-semibold tabular-nums',
+ scoreColor(page.score),
+ )}
+ >
+ {pct(page.score) ?? '—'}
+ </span>
+ <ScoreSparkline
+ points={page.trend}
+ label={t('pages.trend', {
+ scores: page.trend.map((s) => pct(s)).join(', '),
+ })}
+ />
+ </div>
+ </TableCell>
+ <TableCell className="text-right tabular-nums">
+ {page.issues === null ? '—' : formatNumber(page.issues)}
+ </TableCell>
+ <TableCell>
+ <StatusPill status={page.status} />
+ </TableCell>
+ <TableCell className="text-muted-foreground">
+ {formatDate(page.lastAuditedAt)}
+ </TableCell>
+ </TableRow>
+ {expanded && (
+ <TableRow id={historyId} className="hover:bg-transparent">
+ <TableCell colSpan={2} />
+ <TableCell colSpan={5} className="pt-0 whitespace-normal">
+ <ul className="divide-y rounded-md border">
+ {page.runs.map((run) => (
+ <HistoryRun key={run.id} run={run} onDelete={onDeleteRun} />
+ ))}
+ </ul>
+ {page.runCount > page.runs.length && (
+ <p className="mt-1.5 text-xs text-muted-foreground">
+ {t('pages.moreRuns', { count: page.runCount - page.runs.length })}
+ </p>
+ )}
+ </TableCell>
+ </TableRow>
+ )}
+ </Fragment>
+ );
+ })}
+ </Fragment>
+ ))}
</TableBody>
</Table>
{pages.length < total && (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
index 104d1ed08..2bc1e19d7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
@@ -13,6 +13,7 @@ import {
RefreshCw,
Pin,
EyeOff,
+ Layers,
Settings,
} from 'lucide-react';
import { useRouter } from '@/i18n/navigation';
@@ -33,8 +34,12 @@ import {
getAuditQuota,
getAuditTrend,
getLatestAutoRun,
+ getAuditSettings,
+ getAuditTemplates,
+ saveAuditSettings,
deleteAudit,
type AutoAuditRun,
+ type AuditTemplate,
type AuditedPage,
type AuditOverview,
type AuditOpportunities,
@@ -47,7 +52,7 @@ import { ScoreTrendChart } from './_charts';
import { AuditPagesTable } from './_pages-table';
import { AuditBulkBar, ExportMenu } from './_bulk-bar';
import { AuditOverviewCards } from './_overview-cards';
-import { OpportunitiesTable } from './_opportunities-table';
+import { OpportunitiesTable, opportunityAuditUrls } from './_opportunities-table';
import { AuditSettingsDialog } from './_settings-dialog';
import { AutoRunNotice } from './_auto-run-notice';
import { AuditSummaryStrip } from './_summary-strip';
@@ -88,6 +93,9 @@ async function readLatestRun(brandId: string): Promise<AutoAuditRun | null> {
}
}
+/** Pages one bulk request may audit (the server's BULK_AUDIT_MAX). */
+const BULK_REQUEST_MAX = 50;
+
type ListTab = 'opportunities' | 'pages';
/** A tab's count, as the mockup's grey pill. */
@@ -142,6 +150,9 @@ export default function SiteAuditPage() {
const [startingBulk, setStartingBulk] = useState(false);
const [latestRun, setLatestRun] = useState<AutoAuditRun | null>(null);
const [settingsOpen, setSettingsOpen] = useState(false);
+ // Pages › Group by template (SA-007): the templates, read while it's on.
+ const [groupByTemplate, setGroupByTemplate] = useState(false);
+ const [templates, setTemplates] = useState<AuditTemplate[] | null>(null);
const { exporting, exportAll, exportPages } = usePagesExport(activeBrandId);
// Capture "now" once (impure call belongs in a lazy initializer, not render).
const [nowMs] = useState(() => Date.now());
@@ -201,6 +212,26 @@ export default function SiteAuditPage() {
};
}, [activeBrandId, refreshKey, t]);
+ useEffect(() => {
+ if (!groupByTemplate || !activeBrandId) return;
+ let cancelled = false;
+ getAuditTemplates(activeBrandId)
+ .then((next) => {
+ if (!cancelled) setTemplates(next);
+ })
+ .catch((err) => {
+ console.error('Failed to load the page templates:', err);
+ if (!cancelled) {
+ toast.error(t('pages.templatesFailed'));
+ setGroupByTemplate(false);
+ }
+ });
+ return () => {
+ cancelled = true;
+ setTemplates(null);
+ };
+ }, [groupByTemplate, activeBrandId, refreshKey, t]);
+
const quotaExhausted = quota !== null && quota.limit !== -1 && quota.remaining <= 0;
// Trend points within the selected range (oldest → newest).
@@ -371,14 +402,24 @@ export default function SiteAuditPage() {
const selectedOpps = (opps?.opportunities ?? []).filter((o) => oppSelected.has(o.key));
+ const oppAuditUrls = opportunityAuditUrls(selectedOpps);
+ // Pin and Exclude by page; a template is excluded by its pattern (SA-007).
+ const selectedOppUrls = selectedOpps.flatMap((o) => (!o.template && o.url ? [o.url] : []));
+ const selectedTemplates = selectedOpps.filter((o) => o.template).map((o) => o.path);
+
const handleAuditOpps = async () => {
- if (!activeBrandId || selectedOpps.length === 0) return;
+ if (!activeBrandId || oppAuditUrls.length === 0) return;
setStartingBulk(true);
try {
- const { started } = await runAuditsBulk(
- activeBrandId,
- selectedOpps.map((o) => o.url),
- );
+ // A template's pages can pass one request's limit: a request per 50.
+ let started = 0;
+ for (let i = 0; i < oppAuditUrls.length; i += BULK_REQUEST_MAX) {
+ const result = await runAuditsBulk(
+ activeBrandId,
+ oppAuditUrls.slice(i, i + BULK_REQUEST_MAX),
+ );
+ started += result.started;
+ }
toast.success(t('bulk.started', { count: started }));
setOppSelected(new Set());
await reloadInPlace(activeBrandId);
@@ -412,16 +453,52 @@ export default function SiteAuditPage() {
}
};
- const allPinned = selectedOpps.length > 0 && selectedOpps.every((o) => o.pinned);
+ const selectedPagesOpps = selectedOpps.filter((o) => !o.template);
+ const allPinned = selectedPagesOpps.length > 0 && selectedPagesOpps.every((o) => o.pinned);
const handlePin = () => {
- const urls = selectedOpps.map((o) => o.url);
+ const urls = selectedOppUrls;
return allPinned
? savePrefs(urls, null, t('opportunities.unpinnedToast', { count: urls.length }))
: savePrefs(urls, 'pinned', t('opportunities.pinnedToast', { count: urls.length }));
};
- const handleExclude = () => {
- const urls = selectedOpps.map((o) => o.url);
- return savePrefs(
+
+ // Excluding a template adds its pattern ("/blog/*") to the brand's exclude
+ // patterns, so its pages leave the inbox too; Undo puts the patterns back.
+ const savePatterns = async (patterns: string[], message: string, undo?: () => void) => {
+ if (!activeBrandId) return;
+ try {
+ await saveAuditSettings(activeBrandId, { excludePatterns: patterns });
+ setOppSelected(new Set());
+ toast.success(
+ message,
+ undo ? { action: { label: t('opportunities.undo'), onClick: undo } } : undefined,
+ );
+ await reloadInPlace(activeBrandId);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : t('opportunities.prefsFailed'));
+ }
+ };
+ const excludeTemplates = async (templates: string[]) => {
+ if (!activeBrandId) return;
+ let before: string[];
+ try {
+ before = (await getAuditSettings(activeBrandId)).excludePatterns;
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : t('opportunities.prefsFailed'));
+ return;
+ }
+ await savePatterns(
+ [...new Set([...before, ...templates])],
+ t('opportunities.templateExcludedToast', { count: templates.length, template: templates[0] }),
+ () => void savePatterns(before, t('opportunities.templateRestoredToast')),
+ );
+ };
+ const handleExclude = async () => {
+ const urls = selectedOppUrls;
+ const templates = selectedTemplates;
+ if (templates.length > 0) await excludeTemplates(templates);
+ if (urls.length === 0) return;
+ await savePrefs(
urls,
'excluded',
t('opportunities.excludedToast', { count: urls.length }),
@@ -704,6 +781,7 @@ export default function SiteAuditPage() {
selectedOpps.length > 0 && (
<AuditBulkBar
count={selectedOpps.length}
+ audits={oppAuditUrls.length}
quota={quota}
starting={startingBulk}
auditLabel={t('opportunities.auditSelected')}
@@ -714,6 +792,7 @@ export default function SiteAuditPage() {
variant="outline"
size="sm"
className="h-7 gap-1.5 text-xs"
+ disabled={selectedOppUrls.length === 0}
onClick={() => void handlePin()}
>
<Pin className="h-3 w-3" />
@@ -752,7 +831,22 @@ export default function SiteAuditPage() {
onDeleteRun={handleDelete}
selected={selected}
onSelect={handleSelect}
- headerAction={<ExportMenu busy={exporting} onExport={exportAll} />}
+ templates={groupByTemplate ? templates : null}
+ headerAction={
+ <div className="flex items-center gap-2">
+ <Button
+ variant={groupByTemplate ? 'secondary' : 'ghost'}
+ size="sm"
+ className="h-8 gap-1.5 text-xs"
+ aria-pressed={groupByTemplate}
+ onClick={() => setGroupByTemplate((on) => !on)}
+ >
+ <Layers className="h-3.5 w-3.5" />
+ {t('pages.groupByTemplate')}
+ </Button>
+ <ExportMenu busy={exporting} onExport={exportAll} />
+ </div>
+ }
toolbar={
selectedPages.length > 0 && (
<AuditBulkBar
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
index 96166c17f..be31afd9e 100644
--- a/web/src/lib/actions/audits.ts
+++ b/web/src/lib/actions/audits.ts
@@ -168,6 +168,8 @@ export interface AuditedPage {
/** Runs, newest first. */
runs: AuditRun[];
runCount: number;
+ /** The page's template on the primary domain ("/blog/*"), for Group by template (SA-007). */
+ template?: string | null;
}
async function getSession() {
@@ -349,6 +351,8 @@ export type OpportunityReason =
}
| { type: 'never_audited' }
| { type: 'stale_audit'; days: number }
+ /** A template's row (SA-007): the gaps most of its audited pages share. */
+ | { type: 'template_gaps'; gaps: { key: string; label: string }[] }
| {
type: 'competitor_cited';
/** Prompts a competitor is cited on and the brand never is, closest to this page. */
@@ -360,7 +364,9 @@ export type OpportunityReason =
/** A page worth auditing (SA-004). */
export interface AuditOpportunity {
key: string;
- url: string;
+ /** Null for a template's row, which stands for many pages. */
+ url: string | null;
+ /** The page's path, or a template's ("/blog/*"). */
path: string;
title: string | null;
reasons: OpportunityReason[];
@@ -373,6 +379,38 @@ export interface AuditOpportunity {
/** 0–100: the cube root of value × opportunity × ease (SA-005). */
priority: number;
priorityParts: { value: number; opportunity: number; ease: number };
+ /** A template's row (SA-007): its pages, those audited, and those an audit of it starts. */
+ template?: { pages: number; audited: number; toAudit: string[] };
+}
+
+/** A template of the brand's pages (SA-007): "/blog/* · 38 pages", and the gaps they share. */
+export interface AuditTemplate {
+ template: string;
+ pages: number;
+ audited: number;
+ sharedGaps: { key: string; label: string; category: string | null; pages: number }[];
+}
+
+export async function getAuditTemplates(brandId: string): Promise<AuditTemplate[]> {
+ const session = await getSession();
+
+ const res = await fetch(
+ `${AEO_SERVER_URL}/api/audits/templates?brandId=${encodeURIComponent(brandId)}`,
+ { headers: { Authorization: `Bearer ${session.access_token}` } },
+ );
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.message || `Server error: ${res.status}`);
+ }
+
+ const data = await res.json();
+ return (data.templates ?? []).map((t: AuditTemplate) => ({
+ template: t.template,
+ pages: t.pages,
+ audited: t.audited,
+ sharedGaps: t.sharedGaps,
+ }));
}
export interface ExcludedPage {