From 92eed19a5a4387c32502e152a70ab6911135e6eb Mon Sep 17 00:00:00 2001 From: KKKK Date: Tue, 10 Nov 2026 00:04:08 +0800 Subject: [PATCH 1/5] Connect official AI reports through the signed-in browser --- apps/browser-lab/server.mjs | 14 + apps/browser-lab/webmaster-reports.mjs | 254 ++++++++++++++++ apps/browser-lab/webmaster-reports.test.mjs | 138 +++++++++ .../src/components/ai-platform-reports.tsx | 272 +++--------------- .../src/components/ai-report-connections.tsx | 216 ++++++++++++++ apps/web/src/components/monitoring-start.tsx | 2 +- apps/web/src/components/trend-chart.tsx | 10 +- apps/web/src/lib/i18n/zh.json | 47 ++- .../__tests__/ai-report-connections.test.ts | 110 +++++++ apps/web/src/server/ai-report-connections.ts | 200 +++++++++++++ docs/beat-geo/ai-platform-reports.md | 18 +- packages/lib/src/ai-reports.test.ts | 48 +++- packages/lib/src/ai-reports.ts | 53 ++++ packages/lib/src/db/schema.ts | 6 +- scripts/start-local.mjs | 15 +- 15 files changed, 1154 insertions(+), 249 deletions(-) create mode 100644 apps/browser-lab/webmaster-reports.mjs create mode 100644 apps/browser-lab/webmaster-reports.test.mjs create mode 100644 apps/web/src/components/ai-report-connections.tsx create mode 100644 apps/web/src/server/__tests__/ai-report-connections.test.ts create mode 100644 apps/web/src/server/ai-report-connections.ts diff --git a/apps/browser-lab/server.mjs b/apps/browser-lab/server.mjs index 5f1c5ce..03cec3e 100644 --- a/apps/browser-lab/server.mjs +++ b/apps/browser-lab/server.mjs @@ -14,6 +14,7 @@ import { summarize, validateInput, } from "./core.mjs"; +import { readWebmasterReport } from "./webmaster-reports.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const directory = defaultRunDirectory(); @@ -134,6 +135,19 @@ async function handle(request, response) { const url = new URL(request.url, `http://127.0.0.1:${port}`); if (request.method === "GET") return handleRead(url, request, response); if (request.method === "POST" && url.pathname === "/api/browser/profile") return selectProfile(request, response); + if (request.method === "POST" && url.pathname === "/api/reports") { + if (!authorized(request)) return json(response, 403, { error: "Invalid local runner token" }); + const input = await bodyOf(request); + if (!["connect", "sync"].includes(input.action)) return json(response, 400, { error: "Invalid report action" }); + if (active) + return json(response, 409, { error: "The browser is busy. Retry after the current operation finishes." }); + active = { status: "reading-report" }; + try { + return json(response, 200, await readWebmasterReport(input)); + } finally { + active = null; + } + } if (request.method !== "POST" || !["/api/run", "/api/collect"].includes(url.pathname)) return json(response, 404, { error: "Not found" }); return handleCollection(request, response, url); diff --git a/apps/browser-lab/webmaster-reports.mjs b/apps/browser-lab/webmaster-reports.mjs new file mode 100644 index 0000000..5289221 --- /dev/null +++ b/apps/browser-lab/webmaster-reports.mjs @@ -0,0 +1,254 @@ +import { setTimeout as sleep } from "node:timers/promises"; +import { createBrowser, parseRows } from "./core.mjs"; + +export function reportUrl(source, property) { + if (!["bing", "google"].includes(source)) throw new Error("Unsupported report source."); + if (typeof property !== "string" || property.length > 2048) throw new Error("Invalid website."); + const domain = property.startsWith("sc-domain:"); + const parsed = new URL(domain ? `https://${property.slice(10)}` : property); + if (!["https:", "http:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.port) + throw new Error("Invalid website."); + if (source === "bing" && domain) throw new Error("Bing requires a website URL."); + const url = new URL( + source === "bing" + ? "https://www.bing.com/webmasters/aiperformance" + : "https://search.google.com/search-console/performance/search-analytics/ai", + ); + url.searchParams.set(source === "bing" ? "siteUrl" : "resource_id", property); + return url.href; +} + +// Read only responses generated by the official report page. No cookies, +// session tokens or undocumented request payloads are replayed or persisted. +export function responseJson(text) { + const start = text.indexOf("\n{"); + if (start < 0) throw new Error("Report response unavailable."); + const body = text + .slice(start + 1) + .split("\n")[0] + .trim(); + return JSON.parse(body); +} + +export function googleFrames(text) { + return text + .split("\n") + .filter((line) => line.startsWith('[["wrb.fr"')) + .flatMap((line) => JSON.parse(line)) + .filter((frame) => frame[0] === "wrb.fr" && typeof frame[2] === "string") + .map((frame) => ({ rpc: frame[1], data: JSON.parse(frame[2]) })); +} + +function count(value) { + if (!Number.isSafeInteger(value) || value < 0) throw new Error("Invalid report count."); + return value; +} +function dates(rows) { + if (!rows.length) throw new Error("The report has no dated observations yet."); + const sorted = rows.map((row) => row.key).sort(); + return { startDate: sorted[0], endDate: sorted.at(-1) }; +} + +export function parseBingHistory(data, property) { + if (data.SiteUrl !== property || !Array.isArray(data.CitationStats)) throw new Error("Report website mismatch."); + const rows = data.CitationStats.map((row) => ({ key: row.Date.slice(0, 10), value: count(row.Citations) })); + return { ...dates(rows), rows, total: count(data.TotalCitations) }; +} + +export function parseGoogleReport(text, property) { + const frames = googleFrames(text).filter(({ data }) => data?.[0]?.[0] === property); + const history = frames.findLast( + ({ rpc, data }) => + rpc === "OLiH4d" && + data?.[6]?.[2]?.length === 1 && + data[6][2][0][0] === "IMPRESSIONS" && + data?.[1]?.[0]?.length > 1, + )?.data; + const pages = frames.findLast( + ({ rpc, data }) => rpc === "nDAfwb" && data?.[1]?.[1]?.[0]?.[9] === "PAGES" && data[1][1][1]?.[9] === "IMPRESSIONS", + )?.data; + if (!history || !pages) throw new Error("AI report unavailable or its format has changed."); + // These observed request descriptors distinguish the AI report and its filters. + if ( + history[0][5]?.[15] !== 4 || + pages[0][5]?.[15] !== 4 || + JSON.stringify(history[0][5][2]) !== "[[null,null,null,3]]" || + JSON.stringify(history[0][5][3]) !== '[[6,["WEB"]]]' || + JSON.stringify(history[0][5].slice(1)) !== JSON.stringify(pages[0][5].slice(1)) + ) + throw new Error("AI report filters could not be verified."); + const daily = history[1][0].map((row) => { + if (!Number.isFinite(row[0]) || row[1]?.length !== 1) throw new Error("Invalid daily report."); + return { key: new Date(row[0]).toISOString().slice(0, 10), value: count(row[1][0]) }; + }); + const pageRows = pages[1][0].map((row) => { + const cells = row?.[0]; + if (typeof cells?.[0]?.[40] !== "string" || cells?.[1]?.[8] !== 6) + throw new Error("AI page report format changed."); + return { key: cells[0][40], value: count(cells[1][1]) }; + }); + return { ...dates(daily), daily, pages: pageRows, total: count(history[1][1][1][0]) }; +} + +async function waitFor(read, delay, accept = () => true) { + for (let attempt = 0; attempt < 12; attempt++) { + try { + const value = await read(); + if (accept(value)) return value; + } catch { + /* Page is still loading. */ + } + await delay(1500); + } + throw new Error( + "The AI report could not be read. Check website access, sign-in and report availability, then retry.", + ); +} + +function appendBingBatch(rows, batch, name, key, total) { + if (!Number.isSafeInteger(batch.TotalNumOfRecords) || batch.TotalNumOfRecords < 0) + throw new Error("Report pagination could not be verified."); + if (total !== undefined && total !== batch.TotalNumOfRecords) + throw new Error("Report changed during synchronization. Retry."); + for (const row of batch[name]) { + if (typeof row[key] !== "string" || rows.has(row[key])) throw new Error("Duplicate report page. Retry."); + rows.set(row[key], { key: row[key], value: count(row.Citations) }); + } + return batch.TotalNumOfRecords; +} + +async function bingTable(call, name, property, delay) { + const endpoint = `aiperformance/${name === "Pages" ? "pages" : "searchqueries"}/stats`; + const key = name === "Pages" ? "PageUrl" : "GroundingQuery"; + await call("snapshot", {}); + const tabs = parseRows(await call("query", { selector: '[role="tab"]', extract: { text: ".@text", id: ".@id" } })); + const tab = tabs.find((item) => item.text === (name === "Pages" ? "Pages" : "Grounding Queries")); + if (!tab?.id) throw new Error("AI report tab unavailable."); + await call("click", { selector: `[id=${JSON.stringify(tab.id)}]` }); + const rows = new Map(); + let total; + for (let page = 0; page < 80; page++) { + const batch = await waitFor( + async () => responseJson(await call("network", { body: endpoint, maxBody: 2_000_000 })), + delay, + (data) => + data.SiteUrl === property && + Array.isArray(data[name]) && + (data[name].length === 0 || !rows.has(data[name][0][key])), + ); + total = appendBingBatch(rows, batch, name, key, total); + if (rows.size === total) return [...rows.values()]; + if (rows.size > total || total > 2000 || !batch[name].length) + throw new Error("Report exceeds the supported row limit."); + await call("snapshot", {}); + await call("click", { selector: 'button[aria-label="Go to next Page"]' }); + } + throw new Error("Report pagination did not finish. No partial report was saved."); +} + +export async function readWebmasterReport(input, options = {}) { + const url = reportUrl(input.source, input.property); + const browser = options.browser || createBrowser(); + const delay = options.delay || sleep; + const openingUrl = + input.source === "google" + ? `https://search.google.com/search-console?resource_id=${encodeURIComponent(input.property)}` + : url; + const space = JSON.parse( + await browser("spaces", { + action: "open", + url: openingUrl, + label: `BeatGEO · ${input.source} AI reports`, + leaseMs: 600_000, + profileId: input.profileId || process.env.BEAT_BROWSER_PROFILE_ID || undefined, + }), + ); + if (!space.spaceId || !Number.isInteger(space.tabId) || space.state !== "running") + throw new Error("Connect your Chrome first."); + const call = (tool, params) => browser(tool, { ...params, spaceId: space.spaceId, tabId: space.tabId }); + let synced = false; + try { + let history; + if (input.source === "bing") { + history = await waitFor( + async () => + parseBingHistory( + responseJson( + await call("network", { + body: "aiperformance/citationstats", + maxBody: 2_000_000, + }), + ), + input.property, + ), + delay, + ); + if (input.action === "connect") return { ready: true, property: input.property, url }; + const queries = await bingTable(call, "Queries", input.property, delay); + const pages = await bingTable(call, "Pages", input.property, delay); + synced = true; + return { + ready: true, + property: input.property, + url, + ...dates(history.rows), + total: history.total, + tables: [ + { dimension: "date", rows: history.rows }, + { dimension: "page", rows: pages }, + { dimension: "query", rows: queries }, + ], + coverage: "All rows returned by the official report; platform sampling applies.", + }; + } + const sectionSelector = '[aria-label="“效果”报告部分"], [aria-label="Performance report section"]'; + const sections = await waitFor( + async () => + parseRows(await call("query", { selector: sectionSelector, extract: { expanded: ".@aria-expanded" } })), + delay, + (rows) => rows.length > 0, + ); + if (sections[0].expanded === "false") { + await call("snapshot", {}); + await call("click", { selector: sectionSelector }); + } + await waitFor( + async () => + parseRows( + await call("query", { selector: 'a[href*="/performance/search-analytics/ai"]', extract: { href: ".@href" } }), + ), + delay, + (rows) => rows.length > 0, + ); + await call("snapshot", {}); + await call("click", { selector: 'a[href*="/performance/search-analytics/ai"]' }); + history = await waitFor( + async () => + parseGoogleReport( + await call("network", { + body: "rpcids=OLiH4d", + maxBody: 2_000_000, + }), + input.property, + ), + delay, + ); + if (input.action === "connect") return { ready: true, property: input.property, url }; + synced = true; + return { + ready: true, + property: input.property, + url, + startDate: history.startDate, + endDate: history.endDate, + total: history.total, + tables: [ + { dimension: "date", rows: history.daily }, + { dimension: "page", rows: history.pages }, + ], + coverage: "Rows returned by the official AI report; page results may be limited by Google.", + }; + } finally { + await browser("spaces", { action: "finish", spaceId: space.spaceId, keep: synced ? [] : "all" }).catch(() => {}); + } +} diff --git a/apps/browser-lab/webmaster-reports.test.mjs b/apps/browser-lab/webmaster-reports.test.mjs new file mode 100644 index 0000000..8bd1c07 --- /dev/null +++ b/apps/browser-lab/webmaster-reports.test.mjs @@ -0,0 +1,138 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + parseBingHistory, + parseGoogleReport, + readWebmasterReport, + reportUrl, + responseJson, +} from "./webmaster-reports.mjs"; + +function googleFixture({ property = "sc-domain:example.com", metric = "IMPRESSIONS", value = 7, feature = 4 } = {}) { + const descriptor = (dimension) => [ + [dimension], + null, + [[null, null, null, 3]], + [[6, ["WEB"]]], + null, + null, + null, + null, + null, + null, + true, + null, + null, + 2, + null, + feature, + ]; + const history = [ + [property, 27, null, null, null, descriptor(1)], + [ + [ + [Date.UTC(2026, 9, 1), [value]], + [Date.UTC(2026, 9, 2), [3]], + ], + [null, [10]], + ], + 1, + [0], + null, + null, + [null, null, [[metric]]], + ]; + const key = Array(41).fill(null); + key[40] = "https://docs.example.com/a"; + const column = (name) => { + const c = Array(10).fill(null); + c[9] = name; + return c; + }; + const pages = [ + [property, 32, null, null, null, descriptor(3)], + [[[[key, [null, 10, null, null, null, null, null, null, 6]]]], [column("PAGES"), column(metric)]], + ]; + return `200 report\n\n)]}'\n\n${JSON.stringify([ + ["wrb.fr", "OLiH4d", JSON.stringify(history)], + ["wrb.fr", "nDAfwb", JSON.stringify(pages)], + ])}\n`; +} + +test("reads exact AI impressions and dates from matching official report frames", () => { + const result = parseGoogleReport(googleFixture(), "sc-domain:example.com"); + assert.deepEqual(result.daily, [ + { key: "2026-10-01", value: 7 }, + { key: "2026-10-02", value: 3 }, + ]); + assert.deepEqual(result.pages, [{ key: "https://docs.example.com/a", value: 10 }]); + assert.equal(result.total, 10); +}); +test("rejects other properties, ordinary search reports and changed metric contracts", () => { + for (const options of [{ property: "sc-domain:other.test" }, { metric: "CLICKS" }, { feature: 1 }, { value: -1 }]) + assert.throws(() => parseGoogleReport(googleFixture(options), "sc-domain:example.com")); +}); +test("Bing uses exact numeric counts and verifies the returned website", () => { + const data = { + SiteUrl: "https://example.com/", + CitationStats: [{ Date: "2026-10-01T00:00:00", Citations: 1234 }], + TotalCitations: 1234, + }; + assert.equal(parseBingHistory(data, data.SiteUrl).rows[0].value, 1234); + assert.throws(() => parseBingHistory(data, "https://other.test/")); + assert.throws(() => parseBingHistory({ ...data, TotalCitations: "1.2K" }, data.SiteUrl)); + assert.deepEqual(responseJson(`200 /report\n\n${JSON.stringify(data)}\n`), data); +}); +test("website selection cannot redirect the reader to an arbitrary host", () => { + assert.equal(new URL(reportUrl("google", "sc-domain:example.com")).hostname, "search.google.com"); + assert.throws(() => reportUrl("bing", "https://user:password@example.com/")); + assert.throws(() => reportUrl("other", "https://example.com/")); +}); +test("Bing follows every report page before returning a snapshot", async () => { + let page = 0, + table = "Queries"; + const site = "https://example.com/"; + const handlers = { + spaces: (args) => JSON.stringify(args.action === "open" ? { spaceId: "s", tabId: 1, state: "running" } : {}), + snapshot: () => "AI Performance", + query: () => + JSON.stringify([ + { id: "q", text: "Grounding Queries" }, + { id: "p", text: "Pages" }, + ]), + click: (args) => { + if (args.selector.includes('id="p"')) { + table = "Pages"; + page = 0; + } else if (args.selector.includes("next Page")) page++; + return "Clicked"; + }, + network: (args) => { + if (args.body.includes("citationstats")) + return `200\n\n${JSON.stringify({ SiteUrl: site, CitationStats: [{ Date: "2026-10-01", Citations: 9 }], TotalCitations: 9 })}`; + const key = table === "Pages" ? "PageUrl" : "GroundingQuery"; + return `200\n\n${JSON.stringify({ SiteUrl: site, TotalNumOfRecords: 2, [table]: [{ [key]: table === "Pages" ? `${site}${page}` : `query ${page}`, Citations: 4 }] })}`; + }, + }; + const browser = async (tool, args) => handlers[tool](args); + const result = await readWebmasterReport( + { source: "bing", property: site, action: "sync" }, + { browser, delay: async () => {} }, + ); + assert.equal(result.tables.find((t) => t.dimension === "page").rows.length, 2); + assert.equal(result.tables.find((t) => t.dimension === "query").rows.length, 2); +}); +test("a missing report never returns a successful empty snapshot", async () => { + const browser = async (tool, args) => + tool === "spaces" + ? JSON.stringify(args.action === "open" ? { spaceId: "s", tabId: 1, state: "running" } : {}) + : "Sign in"; + await assert.rejects( + () => + readWebmasterReport( + { source: "bing", property: "https://example.com/", action: "sync" }, + { browser, delay: async () => {} }, + ), + /could not be read/, + ); +}); diff --git a/apps/web/src/components/ai-platform-reports.tsx b/apps/web/src/components/ai-platform-reports.tsx index ded5f06..7950de6 100644 --- a/apps/web/src/components/ai-platform-reports.tsx +++ b/apps/web/src/components/ai-platform-reports.tsx @@ -1,18 +1,14 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { - type AiReport, - type AiReportDimension, - type AiReportInput, - type AiReportSource, - compareAiReports, - parseAiReport, -} from "@workspace/lib/ai-reports"; +import { type AiReport, compareAiReports } from "@workspace/lib/ai-reports"; import { Button } from "@workspace/ui/components/button"; import { Input } from "@workspace/ui/components/input"; -import { useMemo, useState } from "react"; +import { useState } from "react"; import { useBrandId } from "@/hooks/use-brand-id"; import { useT } from "@/lib/i18n"; -import { deleteAiReportFn, importAiReportFn, listAiReportsFn } from "@/server/ai-reports"; +import { deleteAiReportFn, listAiReportsFn } from "@/server/ai-reports"; + +import { AiReportConnections } from "./ai-report-connections"; +import { TrendChart } from "./trend-chart"; const fieldClass = "h-10 w-full min-w-0 rounded-md border bg-background px-3 text-sm"; export function AiPlatformReports() { @@ -24,17 +20,7 @@ function ReportWorkspace({ brandId }: { brandId: string }) { client = useQueryClient(); const queryKey = ["ai-platform-reports", brandId]; const query = useQuery({ queryKey, queryFn: () => listAiReportsFn({ data: { brandId } }) }); - const [input, setInput] = useState({ - source: "bing", - dimension: "page", - site: "", - startDate: "", - endDate: "", - scope: "", - content: "", - }); - const [confirmed, setConfirmed] = useState(false), - [busy, setBusy] = useState(false), + const [busy, setBusy] = useState(false), [message, setMessage] = useState(""); const [selected, setSelected] = useState(""), [previous, setPrevious] = useState(""), @@ -42,84 +28,15 @@ function ReportWorkspace({ brandId }: { brandId: string }) { [offset, setOffset] = useState(0); const reports = query.data ?? []; const { report, comparison, rows } = reportView(reports, selected, previous, filter); - const preview = useMemo(() => { - if (!input.content) return { data: null, error: "" }; - try { - return { data: parseAiReport(input), error: "" }; - } catch (error) { - return { data: null, error: error instanceof Error ? error.message : "Invalid report." }; - } - }, [input]); - function update(patch: Partial) { - setInput((v) => ({ ...v, ...patch })); - setConfirmed(false); - setMessage(""); - } - async function save() { - if (!preview.data || !confirmed || busy) return; - setBusy(true); - setMessage(""); - try { - const result = await importAiReportFn({ data: { ...input, brandId } }); - await client.invalidateQueries({ queryKey }); - setSelected(result.id); - setPrevious(""); - setOffset(0); - setMessage(result.duplicate ? "This report is already saved; no counts were added." : "AI report saved."); - } catch (error) { - setMessage(error instanceof Error ? error.message : "Could not save AI report."); - } finally { - setBusy(false); - } - } return (

{t("AI platform reports")}

- {t( - "Import platform observations separately from your monitored questions. Imports do not enable automatic synchronization.", - )} + {t("Connect your website accounts and sync AI visibility directly. No files to download or upload.")}

-
- {(["bing", "google"] as const).map((source) => { - const latest = reports.find((r) => r.source === source); - return ( -
-

- {source === "bing" ? "Bing AI Performance" : "Google Search Console · AI"} -

-

- {t( - source === "bing" - ? "Citations · Microsoft and supported partners" - : "Impressions · Google AI Overviews and AI Mode", - )} -

-

- {query.isPending - ? t("Loading…") - : query.isError - ? t("Could not load AI reports.") - : latest - ? `${latest.startDate} – ${latest.endDate} · ${latest.site}` - : t("No AI report imported")} -

- - {t("Open official dashboard")} - -
- ); - })} -
+ client.invalidateQueries({ queryKey })} /> {query.isError && (

{t("Could not load AI reports.")}{" "} @@ -128,141 +45,31 @@ function ReportWorkspace({ brandId }: { brandId: string }) {

)} -
- {t("Import AI report CSV")} -

- {t( - "Export one table from the AI report, then provide its website, dates and filters. Supported: page, daily history, and Bing grounding queries. Use exact counts, not Topic Portfolio opportunity ranges. CSV only; extract ZIP exports first. Maximum 2 MB / 2,000 rows.", - )} -

-
- - - - - - - -
- {preview.error && ( -

- {t(preview.error)} -

- )} - {preview.data && ( -
-

- {t("Import preview")} · {preview.data.rows.length} {t("rows")} ·{" "} - {t(input.source === "bing" ? "Citations" : "Impressions")} -

-
- - - {preview.data.rows.slice(0, 5).map((r) => ( - - - - - ))} - -
{r.key}{r.value ?? "—"}
-
- -
- )} - -
{message && (

{t(message)}

)} + {!query.isPending && !query.isError && !report && ( +

+ {t("No AI data synchronized yet. Connect an account above, then choose Sync now.")} +

+ )} {report && (

{t("Saved AI observations")}

+
+
+

+ {t("Official report total")} · {t(report.source === "bing" ? "Citations" : "Impressions")} +

+

{report.total?.toLocaleString() ?? "—"}

+
+
+

{t("Returned observations")}

+

{report.rows.length.toLocaleString()}

+
+

- {report.site} · {report.startDate} – {report.endDate} · {report.scope} + {report.site} · {report.startDate} – {report.endDate} · {t(report.scope)}
- {t("Imported at")}: {new Date(report.importedAt).toLocaleString()} + {report.coverage && ( + <> + {t(report.coverage)} +
+ + )} + {t("Saved at")}: {new Date(report.importedAt).toLocaleString()}

{t( "Compare only equal-length, non-overlapping periods from the same source, dimension, website and filters. Missing rows are unknown, not zero. Daily reports remain separate observations. Row sums are not site totals; different platforms are never added together.", )}

+ {report.dimension === "date" && report.rows.length > 0 && ( + ({ date: row.key, value: row.value }))} + label={t(report.source === "bing" ? "Citations" : "Impressions")} + color="var(--primary)" + className="aspect-auto h-64 w-full" + unit="count" + /> + )} { - if (!window.confirm(t("Remove this imported report? The original file is unchanged."))) return; + if (!window.confirm(t("Remove this saved snapshot? The official report is unchanged."))) return; setBusy(true); try { await deleteAiReportFn({ data: { brandId, id: report.id } }); @@ -384,7 +206,7 @@ function ReportWorkspace({ brandId }: { brandId: string }) { } }} > - {t("Remove import")} + {t("Remove snapshot")}
diff --git a/apps/web/src/components/ai-report-connections.tsx b/apps/web/src/components/ai-report-connections.tsx new file mode 100644 index 0000000..71b6459 --- /dev/null +++ b/apps/web/src/components/ai-report-connections.tsx @@ -0,0 +1,216 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import type { AiReportSource } from "@workspace/lib/ai-reports"; +import { Button } from "@workspace/ui/components/button"; +import { useState } from "react"; +import { useBrandParams } from "@/hooks/use-route-params"; +import { useT } from "@/lib/i18n"; +import { disconnectAiConnectionFn, getAiConnectionsFn, readAiConnectionFn } from "@/server/ai-report-connections"; + +export function AiReportConnections({ brandId, onSynced }: { brandId: string; onSynced: () => Promise }) { + const params = useBrandParams(); + const t = useT(), + client = useQueryClient(); + const queryKey = ["ai-report-connections", brandId]; + const query = useQuery({ queryKey, queryFn: () => getAiConnectionsFn({ data: { brandId } }) }); + const [busy, setBusy] = useState(null), + [message, setMessage] = useState(""); + const [selected, setSelected] = useState>({}); + async function run(source: AiReportSource, property: string, action: "connect" | "sync" | "disconnect") { + setBusy(`${source}:${action}`); + setMessage(""); + try { + if (action === "disconnect") { + await disconnectAiConnectionFn({ data: { brandId, source } }); + setMessage("Connection removed. Saved reports are kept."); + } else { + const result = await readAiConnectionFn({ data: { brandId, source, property, action } }); + setMessage( + result.ok + ? action === "connect" + ? "Report access verified. Ready to sync." + : "AI report synchronized." + : result.error, + ); + } + await Promise.all([client.invalidateQueries({ queryKey }), onSynced()]); + } catch (error) { + setMessage(error instanceof Error ? error.message : "Could not sync AI report."); + } finally { + setBusy(null); + } + } + if (query.isPending) return

{t("Loading…")}

; + if (query.isError) + return ( +
+ {t("Could not load connections.")} +
+ ); + return ( +
+
+

{t("Connect → Choose website → Sync AI data")}

+

+ {t( + "AI reports are read from your signed-in Chrome through BeatBrowser. Keep Chrome and BeatGEO open. Connecting does not start question monitoring.", + )} +

+

+ {t( + "Google search performance continues to use your existing Google authorization. AI report access is checked separately.", + )} +

+ + {t("Choose Chrome workspace")} + +
+
+ {(["bing", "google"] as const).map((source) => ( + c.source === source)} + selected={selected[source]} + onSelect={(value) => setSelected((v) => ({ ...v, [source]: value }))} + busy={busy} + run={run} + /> + ))} +
+ {message && ( +

+ {t(message)} +

+ )} +
+ ); +} + +function statusLabel(ready: boolean, state: string) { + if (ready) return "Access verified"; + return state === "needs-attention" ? "Connection needs attention" : "Not connected"; +} +function connectLabel(source: AiReportSource, busy: string | null, ready: boolean) { + if (busy === `${source}:connect`) return "Checking connection…"; + if (ready) return "Check connection"; + return source === "bing" ? "Connect Bing" : "Connect Google AI"; +} +function connectionFields(stored?: Record) { + const text = (key: string) => (typeof stored?.[key] === "string" ? (stored[key] as string) : ""); + return { + property: text("property"), + state: text("state"), + error: text("error"), + lastSyncedAt: text("lastSyncedAt"), + checkedAt: text("checkedAt"), + }; +} +function SourceCard({ + source, + websites, + stored, + selected, + onSelect, + busy, + run, +}: { + source: AiReportSource; + websites: string[]; + stored?: Record; + selected?: string; + onSelect: (value: string) => void; + busy: string | null; + run: (source: AiReportSource, property: string, action: "connect" | "sync" | "disconnect") => Promise; +}) { + const t = useT(); + const connection = connectionFields(stored); + const properties = reportProperties(source, websites); + const saved = properties.includes(connection.property) ? connection.property : ""; + const property = selected ?? (saved || properties[0] || ""); + const ready = connection.state === "ready" && saved === property; + const official = + source === "bing" + ? `https://www.bing.com/webmasters/aiperformance?siteUrl=${encodeURIComponent(property)}` + : `https://search.google.com/search-console/performance/search-analytics/ai?resource_id=${encodeURIComponent(property)}`; + return ( +
+
+

{source === "bing" ? "Bing Webmaster Tools" : "Google Search Console"}

+

+ {t(source === "bing" ? "AI citations · Pages · Grounding queries" : "AI impressions · Pages · Daily history")} +

+
+ +

{t(statusLabel(ready, connection.state))}

+ {connection.error && ( +

+ {t(connection.error)} +

+ )} + {connection.lastSyncedAt && ( +

+ {t("Last synchronized")}: {new Date(connection.lastSyncedAt).toLocaleString()} +

+ )} + {connection.checkedAt && ( +

+ {t("Access last checked")}: {new Date(connection.checkedAt).toLocaleString()} +

+ )} +
+ + + {connection.state && ( + + )} +
+ + {t("Open official dashboard / sign in")} + +

+ {t( + "Reads the official default three-month report. Actual dates and available rows are saved with each snapshot. Sync runs when you click; no background schedule is enabled.", + )} +

+
+ ); +} + +function reportProperties(source: AiReportSource, websites: string[]) { + return source === "bing" + ? websites + : [...new Set(websites.flatMap((site) => [`sc-domain:${new URL(site).hostname}`, site]))]; +} diff --git a/apps/web/src/components/monitoring-start.tsx b/apps/web/src/components/monitoring-start.tsx index 709e356..d22e5dd 100644 --- a/apps/web/src/components/monitoring-start.tsx +++ b/apps/web/src/components/monitoring-start.tsx @@ -38,7 +38,7 @@ export function MonitoringStart() { search={{ view: "reports" }} className="text-sm underline" > - {t("Import Bing or Google AI reports")} + {t("Connect Bing or Google AI reports")} ); diff --git a/apps/web/src/components/trend-chart.tsx b/apps/web/src/components/trend-chart.tsx index 10908d1..5a0c425 100644 --- a/apps/web/src/components/trend-chart.tsx +++ b/apps/web/src/components/trend-chart.tsx @@ -26,15 +26,18 @@ export function TrendChart({ label, color, className = "aspect-auto h-full w-full", + unit = "percent", }: { data: TrendPoint[]; label: string; color: string; className?: string; + unit?: "percent" | "count"; }) { const { locale } = useLocale(); const dateLocale = locale === "zh" ? "zh-CN" : "en-US"; const config = { value: { label, color } } satisfies ChartConfig; + const formatValue = (value: number) => (unit === "percent" ? `${value}%` : value.toLocaleString(dateLocale)); const observedCount = data.filter((point) => point.value != null).length; const observedIndex = data.findIndex((point) => point.value != null); @@ -60,7 +63,8 @@ export function TrendChart({ tickMargin={8} tickCount={4} tick={{ fontSize: 11 }} - tickFormatter={(value: number) => `${value}%`} + tickFormatter={formatValue} + allowDecimals={unit === "percent"} />
{label} - {value}% + {formatValue(value)}
); @@ -93,7 +97,7 @@ export function TrendChart({ strokeWidth={2} fill={color} fillOpacity={0.18} - connectNulls + connectNulls={unit === "percent"} // A lone observation has no line to sit on, so it would otherwise not be drawn at all. dot={({ cx, cy, index }: { cx?: number; cy?: number; index?: number }) => observedCount === 1 && index === observedIndex && cx != null && cy != null ? ( diff --git a/apps/web/src/lib/i18n/zh.json b/apps/web/src/lib/i18n/zh.json index ade9c3f..b244d4f 100644 --- a/apps/web/src/lib/i18n/zh.json +++ b/apps/web/src/lib/i18n/zh.json @@ -877,7 +877,7 @@ "Google authorization could not be completed. Connect again.": "Google 授权未能完成,请重新连接。", "Google authorization was cancelled. No connection was changed.": "已取消 Google 授权,连接未作修改。", "Log input limit is 10 MiB.": "日志大小上限为 10 MiB。", - "This connection is busy. Try again shortly.": "连接正在处理,请稍后重试。", + "This connection is busy. Try again shortly.": "该连接正在处理其他请求,请稍后重试。", "Connect Google Analytics first.": "请先连接 Google Analytics。", "Choose a GA property first.": "请先选择 GA 属性。", "This Google account cannot read the selected property.": "该 Google 账号无法读取所选属性。", @@ -947,7 +947,7 @@ "Open workspace": "进入工作区", "Optional. Connect Google to add your site's search performance and traffic data.": "可选。连接 Google,查看这个网站的搜索表现与访问数据。", "Aliases and advanced settings": "别名与高级设置", - "Not connected": "未连接", + "Not connected": "尚未连接", "Manage monitored questions": "管理监控问题", "Choose AI platforms": "选择 AI 平台", "Connected": "已连接", @@ -1361,5 +1361,46 @@ "Add an entry to SCRAPE_TARGETS in .env and restart pnpm local:start, for example": "在 .env 的 SCRAPE_TARGETS 中添加一项并重启 pnpm local:start,例如", "Platform setup guide": "平台配置说明", "Available": "可用", - "Optimize": "优化" + "Optimize": "优化", + "Connect your website accounts and sync AI visibility directly. No files to download or upload.": "连接网站账号,直接同步 AI 展示与引用数据,无需下载或上传文件。", + "Connect → Choose website → Sync AI data": "连接账号 → 选择网站 → 同步 AI 数据", + "AI reports are read from your signed-in Chrome through BeatBrowser. Keep Chrome and BeatGEO open. Connecting does not start question monitoring.": "通过 BeatBrowser 读取已登录 Chrome 中的官方 AI 报表。同步时请保持 Chrome 和 BeatGEO 运行。连接账号不会启动问题监测。", + "Google search performance continues to use your existing Google authorization. AI report access is checked separately.": "Google 普通搜索表现继续使用已有授权;AI 报表将单独检查访问权限。", + "AI citations · Pages · Grounding queries": "AI 引用次数 · 页面 · 检索查询", + "AI impressions · Pages · Daily history": "AI 展示次数 · 页面 · 每日趋势", + "Domain property": "域名资源(含子域名)", + "Website property": "网址资源", + "Access verified": "已验证报表访问权限", + "Connection needs attention": "连接需要处理", + "Access last checked": "上次检查", + "Last synchronized": "最近同步", + "Checking connection…": "正在检查连接…", + "Connect Bing": "连接必应", + "Connect Google AI": "连接 Google AI", + "Syncing report…": "正在读取报表…", + "Sync now": "立即同步", + "Open official dashboard / sign in": "打开官方后台 / 登录账号", + "Reads the official default three-month report. Actual dates and available rows are saved with each snapshot. Sync runs when you click; no background schedule is enabled.": "读取官方默认近三个月报表,保存实际日期和可用数据范围。点击后执行同步,暂未开启后台定时任务。", + "Connection removed. Saved reports are kept.": "连接已移除,历史报表仍保留。", + "Report access verified. Ready to sync.": "报表访问权限已验证,可以同步。", + "AI report synchronized.": "AI 报表已同步。", + "Could not sync AI report.": "AI 报表同步失败,上次成功数据仍保留。", + "Could not load connections.": "无法加载连接状态。", + "The AI report could not be read. Check website access, sign-in and report availability, then retry.": "暂时无法读取 AI 报表。请打开官方后台,检查登录、网站权限及 AI 报表是否可用,然后重试。", + "Restart BeatGEO to enable report connections.": "请重启 BeatGEO 以启用报表连接。", + "The browser is busy. Retry after the current operation finishes.": "浏览器正在执行其他任务,请完成后重试。", + "All rows returned by the official report; platform sampling applies.": "已读取官方报表返回的全部行;平台数据本身可能为抽样统计。", + "Rows returned by the official AI report; page results may be limited by Google.": "数据来自官方 AI 报表;页面列表可能受 Google 返回条数限制。", + "Saved at": "保存时间", + "Remove this saved snapshot? The official report is unchanged.": "移除这份本地快照?官方报表不会受影响。", + "Remove snapshot": "移除快照", + "Connect Bing or Google AI reports": "连接 Bing / Google AI 报表", + "All browser platforms": "全部网页平台", + "Official report total": "官方报表总量", + "Returned observations": "返回的记录数", + "No AI data synchronized yet. Connect an account above, then choose Sync now.": "尚未同步 AI 数据。请先连接上方账号,再点击「立即同步」。", + "Choose Chrome workspace": "选择 Chrome 工作区", + "Official AI report · default 3-month window · all filters": "官方 AI 报表 · 默认近三个月 · 全部筛选范围", + "Report website mismatch.": "报表网站与所选网站不一致,数据未保存。", + "AI report unavailable or its format has changed.": "AI 报表暂不可用或格式已变化,数据未保存。" } diff --git a/apps/web/src/server/__tests__/ai-report-connections.test.ts b/apps/web/src/server/__tests__/ai-report-connections.test.ts new file mode 100644 index 0000000..f4cd78a --- /dev/null +++ b/apps/web/src/server/__tests__/ai-report-connections.test.ts @@ -0,0 +1,110 @@ +import { beforeEach, expect, it, vi } from "vitest"; + +const m = vi.hoisted(() => ({ + auth: vi.fn(), + brand: vi.fn(), + fetch: vi.fn(), + writes: [] as Array>, + config: null as unknown, + acquired: true, +})); +vi.mock("@tanstack/react-start", () => ({ + createServerFn: () => ({ validator: () => ({ handler: (fn: unknown) => fn }) }), +})); +vi.mock("@/lib/auth/helpers", () => ({ requireBrandSession: m.auth })); +vi.mock("../traffic-core", () => ({ trafficBrand: m.brand })); +vi.mock("@workspace/lib/db/db", () => ({ + db: { + transaction: async (fn: (tx: unknown) => unknown) => + fn({ + execute: async () => ({ rows: [{ acquired: m.acquired }] }), + select: () => ({ from: () => ({ where: async () => (m.config ? [{ config: m.config }] : []) }) }), + insert: () => ({ + values: (value: Record) => ({ + onConflictDoUpdate: async () => { + m.writes.push(value); + }, + }), + }), + }), + }, +})); + +import { readAiConnectionFn } from "../ai-report-connections"; + +const input = { brandId: "brand-a", source: "bing", property: "https://example.com/", action: "sync" }; +beforeEach(() => { + vi.clearAllMocks(); + m.writes = []; + m.config = null; + m.acquired = true; + vi.stubGlobal("fetch", m.fetch); + m.auth.mockResolvedValue({}); + m.brand.mockResolvedValue({ website: "https://example.com" }); + m.fetch.mockResolvedValue( + new Response( + JSON.stringify({ + ready: true, + property: input.property, + url: "https://www.bing.com/webmasters/aiperformance", + startDate: "2026-10-01", + endDate: "2026-10-02", + total: 10, + coverage: "Official rows", + tables: [{ dimension: "page", rows: [{ key: "https://example.com/a", value: 10 }] }], + }), + ), + ); +}); +it("requires brand access and website ownership before opening a report", async () => { + m.auth.mockRejectedValue(new Error("Forbidden")); + await expect(readAiConnectionFn({ data: input } as never)).rejects.toThrow("Forbidden"); + expect(m.fetch).not.toHaveBeenCalled(); + m.auth.mockResolvedValue({}); + await expect(readAiConnectionFn({ data: { ...input, property: "https://other.test/" } } as never)).rejects.toThrow( + "website saved", + ); + expect(m.fetch).not.toHaveBeenCalled(); +}); +it("saves a validated browser report and its last successful synchronization", async () => { + const result = await readAiConnectionFn({ data: input } as never); + expect(result.ok).toBe(true); + const report = m.writes[0].snapshot as Record; + expect(report.method).toBe("browser"); + expect(report.total).toBe(10); + expect(report.rows).toEqual([{ key: "https://example.com/a", value: 10 }]); + expect(m.writes[1].config).toMatchObject({ + aiReport: { state: "ready", property: input.property, lastSyncedAt: expect.any(String) }, + }); +}); +it("preserves the last successful sync and never writes an empty report after failure", async () => { + m.config = { site: "example.com", aiReport: { property: input.property, lastSyncedAt: "2026-10-01T00:00:00Z" } }; + m.fetch.mockRejectedValue(new Error("offline")); + const result = await readAiConnectionFn({ data: input } as never); + expect(result.ok).toBe(false); + expect(m.writes).toHaveLength(1); + expect(m.writes[0].config).toMatchObject({ + aiReport: { state: "needs-attention", lastSyncedAt: "2026-10-01T00:00:00Z" }, + }); +}); +it("does not accept a response for another website or an out-of-scope page", async () => { + m.fetch.mockResolvedValue( + new Response( + JSON.stringify({ + ready: true, + property: input.property, + url: "https://www.bing.com/webmasters/", + startDate: "2026-10-01", + endDate: "2026-10-02", + tables: [{ dimension: "page", rows: [{ key: "https://other.test/a", value: 5 }] }], + }), + ), + ); + expect((await readAiConnectionFn({ data: input } as never)).ok).toBe(false); + expect(m.writes.every((row) => String(row.kind).startsWith("ai-connection:"))).toBe(true); +}); +it("does not start another browser operation while a sync holds the lock", async () => { + m.acquired = false; + await expect(readAiConnectionFn({ data: input } as never)).rejects.toThrow("busy"); + expect(m.fetch).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/server/ai-report-connections.ts b/apps/web/src/server/ai-report-connections.ts new file mode 100644 index 0000000..741f21a --- /dev/null +++ b/apps/web/src/server/ai-report-connections.ts @@ -0,0 +1,200 @@ +import { createHash } from "node:crypto"; +import { createServerFn } from "@tanstack/react-start"; +import { reportHost, validateConnectedReport } from "@workspace/lib/ai-reports"; +import { db } from "@workspace/lib/db/db"; +import { brandDataSources } from "@workspace/lib/db/schema"; +import { and, eq, like, sql } from "drizzle-orm"; +import { z } from "zod"; +import { requireBrandSession } from "@/lib/auth/helpers"; +import { trafficBrand } from "./traffic-core"; + +const input = z.object({ + brandId: z.string().min(1).max(200), + source: z.enum(["bing", "google"]), + property: z.string().min(1).max(2048), +}); +const resultSchema = z.object({ + ready: z.literal(true), + property: z.string(), + url: z.string().url(), + startDate: z.string().optional(), + endDate: z.string().optional(), + coverage: z.string().max(500).optional(), + total: z.number().int().nonnegative().optional(), + tables: z + .array( + z.object({ + dimension: z.enum(["page", "query", "date"]), + rows: z + .array(z.object({ key: z.string().max(2048), value: z.number().int().nonnegative().nullable() })) + .max(2000), + }), + ) + .max(3) + .optional(), +}); +const where = (brandId: string, source: string) => + and(eq(brandDataSources.brandId, brandId), eq(brandDataSources.kind, `ai-connection:${source}`)); + +export async function reportBrowserRequest(data: { source: string; property: string; action: string }) { + const base = new URL(process.env.BROWSER_RUNNER_URL || "http://127.0.0.1:4318"); + if (base.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(base.hostname)) + throw new Error("The browser service must run on this computer."); + let response: Response; + try { + response = await fetch(new URL("/api/reports", base), { + method: "POST", + redirect: "error", + signal: AbortSignal.timeout(240_000), + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${process.env.BROWSER_RUNNER_TOKEN || ""}`, + }, + body: JSON.stringify(data), + }); + } catch { + throw new Error("Browser service unavailable. Start BeatGEO locally, then check again."); + } + if (response.status === 404) throw new Error("Restart BeatGEO to enable report connections."); + if (response.status === 409) throw new Error("The browser is busy. Retry after the current operation finishes."); + const result = await response.json(); + if (!response.ok) + throw new Error( + "The AI report could not be read. Check website access, sign-in and report availability, then retry.", + ); + return resultSchema.parse(result); +} + +export const getAiConnectionsFn = createServerFn({ method: "GET" }) + .validator(z.object({ brandId: z.string().min(1) })) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + const brand = await trafficBrand(data.brandId); + const rows = await db + .select({ kind: brandDataSources.kind, config: brandDataSources.config }) + .from(brandDataSources) + .where(and(eq(brandDataSources.brandId, data.brandId), like(brandDataSources.kind, "ai-connection:%"))); + const websites = [ + ...new Set( + [brand.website, ...(brand.additionalDomains ?? [])].map( + (site) => new URL(site.includes("://") ? site : `https://${site}`).href, + ), + ), + ]; + return { + websites, + connections: rows.map((row) => ({ source: row.kind.slice("ai-connection:".length), ...row.config?.aiReport })), + }; + }); + +export const readAiConnectionFn = createServerFn({ method: "POST" }) + .validator(input.extend({ action: z.enum(["connect", "sync"]) })) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + const brand = await trafficBrand(data.brandId); + const allowed = [brand.website, ...(brand.additionalDomains ?? [])].map(reportHost); + if (!allowed.includes(reportHost(data.property))) throw new Error("Choose a website saved in this brand."); + return db.transaction(async (tx) => { + const lock = await tx.execute<{ acquired: boolean }>( + sql`select pg_try_advisory_xact_lock(hashtextextended(${`ai-reports:${data.brandId}`},0)) as acquired`, + ); + if (!lock.rows[0]?.acquired) throw new Error("This connection is busy. Try again shortly."); + const [saved] = await tx.select().from(brandDataSources).where(where(data.brandId, data.source)); + let config: Record = saved?.config?.aiReport ?? {}; + try { + const result = await reportBrowserRequest(data); + if (result.property !== data.property) throw new Error("Report website mismatch."); + const now = new Date().toISOString(); + config = { + property: data.property, + checkedAt: now, + state: "ready", + error: "", + method: "browser", + lastSyncedAt: config.property === data.property ? config.lastSyncedAt : undefined, + }; + if (data.action === "sync") { + await saveReports(tx, data, result, now); + config.lastSyncedAt = now; + } + } catch (error) { + config = { + ...config, + state: "needs-attention", + attemptedProperty: data.property, + checkedAt: new Date().toISOString(), + error: error instanceof Error ? error.message : "Could not sync AI report.", + }; + } + await tx + .insert(brandDataSources) + .values({ + brandId: data.brandId, + kind: `ai-connection:${data.source}`, + config: { site: reportHost(data.property), aiReport: config }, + }) + .onConflictDoUpdate({ + target: [brandDataSources.brandId, brandDataSources.kind], + set: { config: { site: reportHost(data.property), aiReport: config }, updatedAt: new Date() }, + }); + return { ok: config.state === "ready", error: connectionError(config.error) }; + }); + }); + +export const disconnectAiConnectionFn = createServerFn({ method: "POST" }) + .validator(z.object({ brandId: z.string().min(1), source: z.enum(["bing", "google"]) })) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + await db.transaction(async (tx) => { + const lock = await tx.execute<{ acquired: boolean }>( + sql`select pg_try_advisory_xact_lock(hashtextextended(${`ai-reports:${data.brandId}`},0)) as acquired`, + ); + if (!lock.rows[0]?.acquired) throw new Error("This connection is busy. Try again shortly."); + await tx.delete(brandDataSources).where(where(data.brandId, data.source)); + }); + return { disconnected: true }; + }); + +type ReportTx = Parameters[0]>[0]; +async function saveReports( + tx: ReportTx, + data: z.infer, + result: z.infer, + now: string, +) { + const { startDate, endDate, tables } = result; + if (!tables?.length || !startDate || !endDate) throw new Error("AI report unavailable or its format has changed."); + const reports = tables.map((table) => + validateConnectedReport({ + ...table, + source: data.source, + site: reportHost(data.property), + property: data.property, + startDate, + endDate, + method: "browser", + scope: "Official AI report · default 3-month window · all filters", + coverage: result.coverage, + total: result.total, + }), + ); + for (const report of reports) { + const id = createHash("sha256").update(JSON.stringify(report)).digest("hex"); + await tx + .insert(brandDataSources) + .values({ + brandId: data.brandId, + kind: `ai-report:${id}`, + config: { site: report.site }, + snapshot: { ...report, id, importedAt: now }, + }) + .onConflictDoUpdate({ + target: [brandDataSources.brandId, brandDataSources.kind], + set: { updatedAt: new Date(), snapshot: { ...report, id, importedAt: now } }, + }); + } +} + +function connectionError(value: unknown) { + return typeof value === "string" ? value : ""; +} diff --git a/docs/beat-geo/ai-platform-reports.md b/docs/beat-geo/ai-platform-reports.md index b747469..7eb2128 100644 --- a/docs/beat-geo/ai-platform-reports.md +++ b/docs/beat-geo/ai-platform-reports.md @@ -1,17 +1,15 @@ -# AI platform reports +# Connected AI platform reports -Use **Visibility → AI platform reports** to keep platform-reported citations and impressions separate from question-monitoring samples. No API credential is needed for imports, and importing does not schedule collections or refresh Google/Bing data. +Use **Visibility → AI platform reports** to connect Bing Webmaster Tools or Google Search Console, select a website saved on the brand, and synchronize its AI report. No CSV or Excel upload is required. Connecting checks access; synchronization saves observations. Neither action starts question monitoring or a recurring schedule. -Export a single CSV table from Bing AI Performance or Google Search Console's generative AI report. Extract ZIP downloads before selecting a CSV. This release accepts two-column tables: +AI reports use the selected BeatBrowser Chrome profile and its existing login. Ordinary Google search performance continues to use the Google OAuth connection independently. Keep Chrome and BeatGEO running during synchronization. A disconnected browser, expired login, unavailable report or changed page format produces an actionable failure; existing snapshots remain available. -- Page / Citations or Page / Impressions -- Date / Citations or Date / Impressions -- Grounding Query / Citations (Bing only) +The reader opens the official report, observes the responses generated by normal page navigation and saves only normalized counts and report provenance. It does not copy browser cookies or replay private request credentials. These are browser integrations, not public AI-report API integrations. Their parsers fail closed if the observed contract changes. -Common English and Simplified Chinese headers are recognized. Use exact integer counts; opportunity ranges and abbreviated counts are rejected. Provide the export's website, inclusive date range and filters, including market/search type/timezone where relevant. Google ordinary-search exports must not be relabelled as AI data. CSV alone cannot authenticate its source; the importer explicitly asks the user to confirm provenance. Exports with additional dimensions must be reduced to a supported table without changing its meaning. +Bing synchronization reads dated citation counts, pages and grounding queries, following pagination before saving. Google synchronization reads AI impression history and the page rows returned by the official report; Google may limit those rows. Domain properties include subdomains, while URL-prefix properties retain their prefix scope. Platform totals are stored separately from row sums. A returned empty table is distinct from an inaccessible report. -Each import is an independent snapshot scoped to the current brand. The same normalized report is saved only once. Different or overlapping snapshots remain separate and are not summed. Page/query comparisons require identical source, website, dimension and filters, equal-length non-overlapping periods. Missing rows remain unknown; daily tables are not paired across unrelated calendar dates. Detail rows are not summed into site totals. User-supplied filters must match exactly for comparison. +This version reads the official default three-month view. Each snapshot records the actual date interval, property and coverage, rather than assuming Google and Bing have the same window. Comparison requires matching source, property, dimension and filters with equal-length non-overlapping periods. Missing rows remain unknown. Browser question samples, API answers, Google impressions and Bing citations are not combined into one metric. -Limits: 2 MB per CSV, 2,000 rows and 100 saved imports per brand. Remove an unused import to free a slot; its original file is unaffected. Page reports must use a hostname saved on the brand; import separate hostnames separately. +Previously saved snapshots remain readable. Disconnect removes the local connection record, not Google/Bing authorization, Chrome login or saved reports. Removing a snapshot only removes that local snapshot. Raw account evidence and credentials remain untracked. -Validation uses synthetic CSV fixtures and mocked persistence/authorization tests. A real browser check exercises file selection and preview without saving synthetic observations into the owner's brand. Actual Bing/GSC export variants and account data still require validation with their real files. Automatic AI-report API synchronization and Topic Portfolio opportunity imports are not included. +For a workspace whose database is already initialized and current, `pnpm local:start --skip-migrations` restarts the services without applying migrations. This option does not initialize or upgrade a database. diff --git a/packages/lib/src/ai-reports.test.ts b/packages/lib/src/ai-reports.test.ts index c1c77d6..9152692 100644 --- a/packages/lib/src/ai-reports.test.ts +++ b/packages/lib/src/ai-reports.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from "vitest"; -import { type AiReport, type AiReportInput, compareAiReports, parseAiReport } from "./ai-reports"; +import { + type AiReport, + type AiReportInput, + compareAiReports, + parseAiReport, + validateConnectedReport, +} from "./ai-reports"; const base: AiReportInput = { source: "bing", @@ -76,3 +82,43 @@ describe("AI platform report imports", () => { ); }); }); + +describe("connected AI reports", () => { + const report = { + source: "google" as const, + dimension: "page" as const, + site: "example.com", + property: "sc-domain:example.com", + startDate: "2026-10-01", + endDate: "2026-10-28", + scope: "Official AI report", + rows: [{ key: "https://docs.example.com/a", value: 5 }], + total: 12, + }; + it("keeps official totals separate from partial page rows and accepts domain subdomains", () => { + expect(validateConnectedReport(report)).toMatchObject({ total: 12, rows: report.rows }); + expect(validateConnectedReport({ ...report, rows: [] }).rows).toEqual([]); + }); + it.each(["https://example.com.evil.test/a", "https://other.test/a", "javascript:alert(1)"])( + "rejects unrelated page %s", + (key) => { + expect(() => validateConnectedReport({ ...report, rows: [{ key, value: 2 }] })).toThrow(); + }, + ); + it("restricts URL prefix properties", () => { + expect(() => + validateConnectedReport({ + ...report, + property: "https://example.com/docs/", + rows: [{ key: "https://example.com/blog/a", value: 2 }], + }), + ).toThrow(); + }); + it("rejects duplicate rows, invalid counts and dates outside the report", () => { + expect(() => validateConnectedReport({ ...report, rows: [...report.rows, ...report.rows] })).toThrow(); + expect(() => validateConnectedReport({ ...report, total: -1 })).toThrow(); + expect(() => + validateConnectedReport({ ...report, dimension: "date", rows: [{ key: "2026-11-01", value: 2 }] }), + ).toThrow(); + }); +}); diff --git a/packages/lib/src/ai-reports.ts b/packages/lib/src/ai-reports.ts index dfe9c1a..ca5b725 100644 --- a/packages/lib/src/ai-reports.ts +++ b/packages/lib/src/ai-reports.ts @@ -14,7 +14,59 @@ export type AiReport = Omit & { id: string; importedAt: string; rows: Array<{ key: string; value: number | null }>; + property?: string; + method?: "browser"; + coverage?: string; + total?: number; }; + +export function validateConnectedReport(report: Omit) { + if ( + !report.property || + !["bing", "google"].includes(report.source) || + !["page", "query", "date"].includes(report.dimension) || + (report.source === "google" && report.dimension === "query") + ) + throw new Error("Invalid AI report."); + if (!validDate(report.startDate) || !validDate(report.endDate) || report.startDate > report.endDate) + throw new Error("Invalid report period."); + const host = reportHost(report.property); + if (host !== report.site || report.rows.length > 2000) throw new Error("Invalid report website or row limit."); + const seen = new Set(); + for (const row of report.rows) { + validateConnectedRow(row, report, report.property); + if (seen.has(row.key)) throw new Error("Duplicate report row."); + seen.add(row.key); + } + if (report.total !== undefined && (!Number.isSafeInteger(report.total) || report.total < 0)) + throw new Error("Invalid total."); + return { + ...report, + schema: "beat-geo/ai-report@1" as const, + rows: [...report.rows].sort((a, b) => a.key.localeCompare(b.key)), + }; +} +function validateConnectedRow( + row: AiReport["rows"][number], + report: Omit, + property: string, +) { + if (!row.key || row.key.length > 2048 || (row.value !== null && (!Number.isSafeInteger(row.value) || row.value < 0))) + throw new Error("Invalid report row."); + if (report.dimension === "page") validatePropertyPage(row.key, property, report.source); + if (report.dimension === "date" && (!validDate(row.key) || row.key < report.startDate || row.key > report.endDate)) + throw new Error("Observation is outside the report period."); +} +function validatePropertyPage(key: string, property: string, source: AiReportSource) { + const page = new URL(key), + host = reportHost(property), + pageHost = reportHost(key); + const domainProperty = property.startsWith("sc-domain:") || source === "bing"; + const matches = domainProperty + ? pageHost === host || pageHost.endsWith(`.${host}`) + : page.origin === new URL(property).origin && page.href.startsWith(property); + if (!matches) throw new Error("Page URL is outside the connected property."); +} export function reportHost(value: string): string { const url = new URL( value.startsWith("sc-domain:") ? `https://${value.slice(10)}` : value.includes("://") ? value : `https://${value}`, @@ -148,6 +200,7 @@ export function compareAiReports(current: AiReport, previous: AiReport) { const days = (r: AiReport) => Date.parse(r.endDate) - Date.parse(r.startDate); if ( current.source !== previous.source || + current.property !== previous.property || current.dimension !== previous.dimension || current.site !== previous.site || current.scope !== previous.scope || diff --git a/packages/lib/src/db/schema.ts b/packages/lib/src/db/schema.ts index a82e329..986d9fe 100644 --- a/packages/lib/src/db/schema.ts +++ b/packages/lib/src/db/schema.ts @@ -388,7 +388,11 @@ export const brandDataSources = pgTable( .references(() => brands.id, { onDelete: "cascade" }), kind: text("kind").notNull(), encryptedCredentials: text("encrypted_credentials"), - config: jsonb("config").$type<{ property?: { id: string; name: string }; site: string }>(), + config: jsonb("config").$type<{ + property?: { id: string; name: string }; + site: string; + aiReport?: Record; + }>(), snapshot: jsonb("snapshot").$type< | import("../traffic/ga.mjs").GaSummary | import("../traffic/crawls.mjs").CrawlSummary diff --git a/scripts/start-local.mjs b/scripts/start-local.mjs index c03ec36..36823ea 100644 --- a/scripts/start-local.mjs +++ b/scripts/start-local.mjs @@ -30,8 +30,11 @@ if (process.platform !== "win32" && !process.env.BEATGEO_LAUNCHER) { } const root = fileURLToPath(new URL("../", import.meta.url)); -const envPath = process.argv[2] || path.join(root, ".env"); -ensureLocalSetup(root, { envFile: process.argv[2] }); +const startupArgs = process.argv.slice(2); +const skipMigrations = startupArgs.includes("--skip-migrations"); +const envFile = startupArgs.find((arg) => arg !== "--skip-migrations"); +const envPath = envFile || path.join(root, ".env"); +ensureLocalSetup(root, { envFile }); Object.assign(process.env, parseEnv(readFileSync(envPath, "utf8"))); requireBundledStorage(process.env); const app = new URL(process.env.APP_URL || "http://localhost:3140"); @@ -76,9 +79,11 @@ try { await prepareExtension(root); database = await startEmbeddedDatabase(root, process.env); // Migrations are applied before either application process starts. - execFileSync(process.execPath, ["node_modules/drizzle-kit/bin.cjs", "migrate"], { - cwd: path.join(root, "packages/lib"), stdio: "inherit", env: process.env, - }); + if (!skipMigrations) { + execFileSync(process.execPath, ["node_modules/drizzle-kit/bin.cjs", "migrate"], { + cwd: path.join(root, "packages/lib"), stdio: "inherit", env: process.env, + }); + } start(process.execPath, ["apps/browser-lab/server.mjs"]); // The shared bridge may serve other agents, so it is not stopped with BeatGEO. try { From 86192376e11acee641137c8908913b04bf5013c6 Mon Sep 17 00:00:00 2001 From: KKKK Date: Tue, 10 Nov 2026 00:04:59 +0800 Subject: [PATCH 2/5] Keep browser visibility separate from API answer samples --- .changeset/connect-ai-reports.md | 7 ++++ .../src/lib/__tests__/model-filter.test.ts | 11 +++++- .../postgres-read.integration.test.ts | 17 +++++--- apps/web/src/lib/model-filter.ts | 12 +++--- apps/web/src/lib/postgres-read.ts | 39 +++++++++---------- apps/web/src/server/brands.ts | 2 +- packages/config/src/model-filter.ts | 32 +++++---------- 7 files changed, 62 insertions(+), 58 deletions(-) create mode 100644 .changeset/connect-ai-reports.md diff --git a/.changeset/connect-ai-reports.md b/.changeset/connect-ai-reports.md new file mode 100644 index 0000000..1a05c6f --- /dev/null +++ b/.changeset/connect-ai-reports.md @@ -0,0 +1,7 @@ +--- +"@workspace/web": patch +"@workspace/lib": patch +"@workspace/config": patch +--- + +Connect Google and Bing AI reports through your signed-in browser without file uploads, and separate browser visibility from API answers. diff --git a/apps/web/src/lib/__tests__/model-filter.test.ts b/apps/web/src/lib/__tests__/model-filter.test.ts index 74e7c40..bfe2fe7 100644 --- a/apps/web/src/lib/__tests__/model-filter.test.ts +++ b/apps/web/src/lib/__tests__/model-filter.test.ts @@ -76,6 +76,15 @@ describe("labelForModelFilter", () => { }); it("labels the no-filter sentinel", () => { - expect(labelForModelFilter(ALL_MODELS_VALUE)).toBe("All models"); + expect(labelForModelFilter(ALL_MODELS_VALUE)).toBe("All browser platforms"); }); }); + +it("keeps browser observations and ungrounded API answers independently selectable", () => { + const browser = target("chatgpt"); + const api: TrackedTarget = { ...browser, value: targetFilterValue("chatgpt", false, "api"), tier: "api" }; + expect(getAvailableModels([browser, api])).toEqual(["all", "chatgpt", "chatgpt::api"]); + expect(parseModelFilter(api.value)).toEqual({ model: "chatgpt", premium: false, api: true }); + expect(labelForModelFilter(api.value)).toBe("ChatGPT · API"); + expect(getAvailableModels([api])).toEqual(["all", "chatgpt::api"]); +}); diff --git a/apps/web/src/lib/__tests__/postgres-read.integration.test.ts b/apps/web/src/lib/__tests__/postgres-read.integration.test.ts index a3db398..bd7907d 100644 --- a/apps/web/src/lib/__tests__/postgres-read.integration.test.ts +++ b/apps/web/src/lib/__tests__/postgres-read.integration.test.ts @@ -264,15 +264,23 @@ describe("model filter", () => { [promptId], "chatgpt::premium", ); - expect(standard).toMatchObject({ total_runs: 2, brand_mentioned_runs: 0 }); + expect(standard).toMatchObject({ total_runs: 1, brand_mentioned_runs: 0 }); expect(premium).toMatchObject({ total_runs: 1, brand_mentioned_runs: 1 }); }); + it("keeps API answers out of the default dashboard while allowing explicit API inspection", async () => { + const [summary] = await getDashboardSummary(brandId, "2026-03-02", "2026-03-02", "UTC"); + expect(summary).toMatchObject({ total_runs: 1, avg_visibility: 0 }); + const api = await getBrandMentionTotals(brandId, "2026-03-02", "2026-03-02", "UTC", [promptId], "chatgpt::api"); + expect(api).toMatchObject({ total_runs: 1, brand_mentioned_runs: 0 }); + }); + it("attributes citations through the run that produced them", async () => { const window: [string, string, string, string[]] = ["2026-03-02", "2026-03-02", "UTC", [promptId]]; expect(await getCitationsTotalCount(brandId, ...window, "chatgpt")).toBe(2); expect(await getCitationsTotalCount(brandId, ...window, "chatgpt::premium")).toBe(1); - expect(await getCitationsTotalCount(brandId, ...window)).toBe(3); + expect(await getCitationsTotalCount(brandId, ...window)).toBe(2); + expect(await getCitationsTotalCount(brandId, ...window, "chatgpt::api")).toBe(0); }); it("counts each model's citations the way its bare model filter does", async () => { @@ -284,10 +292,7 @@ describe("model filter", () => { it("breaks mention rate down by model", async () => { const rows = await getBrandMentionRateByModel(brandId, "2026-03-02", "2026-03-02", "UTC", [promptId]); - expect(rows).toEqual([ - { model: "chatgpt", runs: 3, brand_mentioned_count: 1 }, - { model: "claude", runs: 1, brand_mentioned_count: 1 }, - ]); + expect(rows).toEqual([{ model: "chatgpt", runs: 1, brand_mentioned_count: 0 }]); }); }); diff --git a/apps/web/src/lib/model-filter.ts b/apps/web/src/lib/model-filter.ts index e430f51..9004302 100644 --- a/apps/web/src/lib/model-filter.ts +++ b/apps/web/src/lib/model-filter.ts @@ -60,12 +60,10 @@ export function groupTrackedTargets(targets: readonly TrackedTarget[]): { .filter((group) => group.values.length > 0); } -/** - * Dropdown options for a brand's targets, with "All" on top once there is more - * than one. A single-target brand gets no "all" entry, since the filter is - * redundant (callers hide the dropdown entirely). - */ +/** Keep the browser aggregate available when a brand also samples API answers. */ export function getAvailableModels(targets: readonly TrackedTarget[]): string[] { - const values = targets.map((target) => target.value); - return values.length > 1 ? [ALL_MODELS_VALUE, ...values] : values; + const values = [...new Set(targets.map((target) => target.value))]; + return values.length > 1 || targets.some((target) => target.tier !== "scraped") + ? [ALL_MODELS_VALUE, ...values] + : values; } diff --git a/apps/web/src/lib/postgres-read.ts b/apps/web/src/lib/postgres-read.ts index 9a1cdb0..daa67b0 100644 --- a/apps/web/src/lib/postgres-read.ts +++ b/apps/web/src/lib/postgres-read.ts @@ -128,32 +128,19 @@ function promptIdFilter(enabledPromptIds?: string[]): SQL { return sql`AND prompt_id IN (${uuidList(enabledPromptIds)})`; } -/** - * Provider ids that reach a model by calling it directly. Combined with - * `web_search_enabled`, this is what separates a grounded API answer from the - * same model scraped off its consumer product — `prompt_runs` records the - * provider, and both rows carry `model = 'chatgpt'` with web search on. - * - * Caveat: a provider that picks its route per target (DataForSEO scrapes by - * default and calls the API when a target pins a version) is classified by its - * default here, since the row doesn't record which route ran. - */ +/** Grounded API filters also require a run to have web search enabled. */ const API_PROVIDER_IDS = getAllProviders() .filter((provider) => provider.access === "api") .map((provider) => provider.id); -/** - * Narrow to one target. A bare model id means the standard platform; the - * `::premium` variant means the grounded API call (the model's own web search). - * - * The provider list is bound one parameter per id rather than as an array: - * drizzle flattens a JS array into a single text parameter, which `ANY(...)` - * then can't compare element-wise. - */ +/** Default and bare model filters describe browser observations; API results require an explicit suffix. */ function modelFilter(model?: string, opts?: { alias?: string; source?: "prompt_runs" | "citations" }): SQL { const target = model ? parseModelFilter(model) : null; - if (!target) return sql``; const prefix = opts?.alias ? sql.raw(`${opts.alias}.`) : sql``; + if (!target?.premium) { + const channel = answerChannel(prefix, opts?.source, !!target?.api); + return sql`AND ${channel} ${target ? sql`AND ${prefix}model = ${target.model}` : sql``}`; + } const grounded = groundedCondition(prefix, opts?.source); // No API providers configured means nothing can be grounded, so the premium // side matches nothing and the standard side matches everything. @@ -163,6 +150,16 @@ function modelFilter(model?: string, opts?: { alias?: string; source?: "prompt_r return sql`AND ${prefix}model = ${target.model} AND ${target.premium ? grounded : sql`NOT ${grounded}`}`; } +function answerChannel(prefix: SQL, source: "prompt_runs" | "citations" | undefined, api: boolean): SQL { + const provider = api ? "beatapi" : "beat-browser"; + if (source === "citations") { + return sql`EXISTS (SELECT 1 FROM prompt_runs AS channel_run + WHERE channel_run.id = ${prefix}prompt_run_id AND channel_run.provider = ${provider} + ${api ? sql`AND NOT channel_run.web_search_enabled` : sql``})`; + } + return sql`${prefix}provider = ${provider} ${api ? sql`AND NOT ${prefix}web_search_enabled` : sql``}`; +} + function groundedCondition(prefix: SQL, source?: "prompt_runs" | "citations"): SQL | null { if (API_PROVIDER_IDS.length === 0) return null; const providers = sql.join( @@ -204,6 +201,7 @@ export async function getDashboardSummary( WHERE brand_id = ${brandId} ${dateFilter(fromDate, toDate, timezone)} ${promptIdFilter(enabledPromptIds)} + ${modelFilter()} `); return rows; } @@ -415,7 +413,6 @@ export async function getCitationsCountByModel( enabledPromptIds?: string[], ): Promise { if (enabledPromptIds && enabledPromptIds.length === 0) return []; - const grounded = groundedCondition(sql``, "citations"); const rows = await queryPg(sql` SELECT model, count(*)::int AS count FROM citations @@ -423,7 +420,7 @@ export async function getCitationsCountByModel( AND created_at >= ${windowStart(fromDate, timezone)} AND created_at < ${windowEnd(toDate, timezone)} ${promptIdFilter(enabledPromptIds)} - ${grounded ? sql`AND NOT ${grounded}` : sql``} + ${modelFilter(undefined, { source: "citations" })} GROUP BY model `); return rows.map((row) => ({ model: row.model, count: Number(row.count) })); diff --git a/apps/web/src/server/brands.ts b/apps/web/src/server/brands.ts index 34b6510..54b3761 100644 --- a/apps/web/src/server/brands.ts +++ b/apps/web/src/server/brands.ts @@ -54,7 +54,7 @@ function computeTrackedTargets(brand: Brand): TrackedTarget[] { return plan.targets.map((target) => { const premium = isGroundedApiTarget(target.config); return { - value: targetFilterValue(target.config.model, premium), + value: targetFilterValue(target.config.model, premium, resolveProviderAccess(target.config)), model: target.config.model, premium, // Scraped surface, bare API call, or grounded one — the same split the diff --git a/packages/config/src/model-filter.ts b/packages/config/src/model-filter.ts index 427ab61..7034cf2 100644 --- a/packages/config/src/model-filter.ts +++ b/packages/config/src/model-filter.ts @@ -1,44 +1,32 @@ -/** - * The model filter's vocabulary: what a brand can be filtered down to, how that - * travels in a URL, and what to call it. - * - * A brand can run the same model two ways — ChatGPT scraped from the consumer - * product and ChatGPT called directly with its own web search on — and those - * answer different questions, so they are separate entries. A model id alone - * cannot tell them apart (both are `chatgpt`, both web-search), which is why a - * filter keyed on model id listed ChatGPT twice and filtered to neither. - * - * The discriminator is grounded-API-or-not rather than the vendor behind it, so - * a URL survives an operator swapping BrightData for Olostep. - * - * Lives in config rather than in the dashboard because the deployment packages - * name targets too, and every surface that names one has to agree. - */ +/** Browser, API and grounded API answers need separate filters even when they share a model id. */ import { getModelMeta } from "./models"; import { premiumModelLabel } from "./platforms"; -/** Sentinel for "no model filter". */ +/** Default browser-platform aggregate. */ export const ALL_MODELS_VALUE = "all"; /** Marks the grounded-API variant of a model in a filter value. */ const PREMIUM_SUFFIX = "::premium"; -export function targetFilterValue(model: string, premium: boolean): string { - return premium ? `${model}${PREMIUM_SUFFIX}` : model; +export function targetFilterValue(model: string, premium: boolean, access?: string): string { + return premium ? `${model}${PREMIUM_SUFFIX}` : access === "api" ? `${model}::api` : model; } -export function parseModelFilter(value: string): { model: string; premium: boolean } | null { +export function parseModelFilter(value: string): { model: string; premium: boolean; api?: boolean } | null { if (!value || value === ALL_MODELS_VALUE) return null; + if (value.endsWith("::api")) return { model: value.slice(0, -5), premium: false, api: true }; return value.endsWith(PREMIUM_SUFFIX) ? { model: value.slice(0, -PREMIUM_SUFFIX.length), premium: true } : { model: value, premium: false }; } export function labelForModelFilter(value: string): string { - if (value === ALL_MODELS_VALUE) return "All models"; + if (value === ALL_MODELS_VALUE) return "All browser platforms"; const parsed = parseModelFilter(value); if (!parsed) return value; - return parsed.premium ? premiumModelLabel(parsed.model) : getModelMeta(parsed.model).label; + return parsed.premium + ? premiumModelLabel(parsed.model) + : `${getModelMeta(parsed.model).label}${parsed.api ? " · API" : ""}`; } export function iconIdForModelFilter(value: string): string { From 15a6c72d30680897962a73b204614263d4386e33 Mon Sep 17 00:00:00 2001 From: KKKK Date: Tue, 10 Nov 2026 00:05:16 +0800 Subject: [PATCH 3/5] Show the most visible report pages first --- apps/web/src/components/ai-platform-reports.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/web/src/components/ai-platform-reports.tsx b/apps/web/src/components/ai-platform-reports.tsx index 7950de6..62ae105 100644 --- a/apps/web/src/components/ai-platform-reports.tsx +++ b/apps/web/src/components/ai-platform-reports.tsx @@ -220,5 +220,7 @@ function reportView(reports: AiReport[], selected: string, previous: string, fil const baseline = reports.find((r) => r.id === previous); const comparison = report && baseline ? compareAiReports(report, baseline) : null; const rows = (comparison ?? report?.rows ?? []).filter((r) => r.key.toLowerCase().includes(filter.toLowerCase())); + if (report?.dimension !== "date") + rows.sort((a, b) => (b.value ?? -1) - (a.value ?? -1) || a.key.localeCompare(b.key)); return { report, comparison, rows }; } From 5e8318d435db0a1fcc1919959b4affca974c6cc2 Mon Sep 17 00:00:00 2001 From: KKKK Date: Mon, 30 Nov 2026 16:11:26 +0800 Subject: [PATCH 4/5] Add Cloudflare crawlers, Bing Webmaster, GSC deltas and AEO site audit --- .../__tests__/traffic-permissions.test.ts | 46 +- apps/web/src/server/traffic-core.ts | 203 ++++++- apps/web/src/server/traffic-fn.ts | 62 +++ packages/lib/package.json | 2 + packages/lib/src/db/schema.ts | 6 + packages/lib/src/public-page.ts | 20 +- packages/lib/src/site-audit.test.ts | 65 ++- packages/lib/src/site-audit.ts | 499 ++++++++++++++++-- packages/lib/src/traffic/bing.d.mts | 57 ++ packages/lib/src/traffic/bing.mjs | 200 +++++++ packages/lib/src/traffic/bing.test.ts | 96 ++++ packages/lib/src/traffic/cloudflare.d.mts | 57 ++ packages/lib/src/traffic/cloudflare.mjs | 186 +++++++ packages/lib/src/traffic/cloudflare.test.ts | 54 ++ packages/lib/src/traffic/gsc-analysis.test.ts | 74 ++- packages/lib/src/traffic/gsc.d.mts | 35 ++ packages/lib/src/traffic/gsc.mjs | 54 +- 17 files changed, 1668 insertions(+), 48 deletions(-) create mode 100644 packages/lib/src/traffic/bing.d.mts create mode 100644 packages/lib/src/traffic/bing.mjs create mode 100644 packages/lib/src/traffic/bing.test.ts create mode 100644 packages/lib/src/traffic/cloudflare.d.mts create mode 100644 packages/lib/src/traffic/cloudflare.mjs create mode 100644 packages/lib/src/traffic/cloudflare.test.ts diff --git a/apps/web/src/server/__tests__/traffic-permissions.test.ts b/apps/web/src/server/__tests__/traffic-permissions.test.ts index 35842c6..471e36c 100644 --- a/apps/web/src/server/__tests__/traffic-permissions.test.ts +++ b/apps/web/src/server/__tests__/traffic-permissions.test.ts @@ -8,8 +8,15 @@ const m = vi.hoisted(() => ({ importLog: vi.fn(), properties: vi.fn(), gscSync: vi.fn(), + gscInspect: vi.fn(), gscDisconnect: vi.fn(), gscProperties: vi.fn(), + cfConnect: vi.fn(), + cfSync: vi.fn(), + cfDisconnect: vi.fn(), + bingConnect: vi.fn(), + bingSync: vi.fn(), + bingDisconnect: vi.fn(), })); vi.mock("@tanstack/react-start", () => ({ createServerFn: () => ({ validator: () => ({ handler: (fn: unknown) => fn }) }), @@ -24,20 +31,34 @@ vi.mock("../traffic-core", () => ({ importCrawlTraffic: m.importLog, trafficReturnTo: vi.fn(), syncGsc: m.gscSync, + inspectGscPage: m.gscInspect, disconnectGsc: m.gscDisconnect, gscProperties: m.gscProperties, + connectCloudflare: m.cfConnect, + syncCloudflare: m.cfSync, + disconnectCloudflare: m.cfDisconnect, + connectBing: m.bingConnect, + syncBing: m.bingSync, + disconnectBing: m.bingDisconnect, })); import { + connectBingFn, + connectCloudflareFn, connectGaFn, connectGoogleFn, connectGscFn, + disconnectBingFn, + disconnectCloudflareFn, disconnectGaFn, disconnectGscFn, getGaPropertiesFn, getGscPropertiesFn, getTrafficFn, importCrawlsFn, + inspectGscUrlFn, + syncBingFn, + syncCloudflareFn, syncGaFn, syncGscFn, } from "../traffic-fn"; @@ -57,10 +78,26 @@ it.each([ connectGscFn, getGscPropertiesFn, syncGscFn, + inspectGscUrlFn, disconnectGscFn, + connectCloudflareFn, + syncCloudflareFn, + disconnectCloudflareFn, + connectBingFn, + syncBingFn, + disconnectBingFn, ])("checks brand access before reading data, storing credentials or making Google requests", async (fn) => { await expect( - fn({ data: { brandId: "other-brand", content: "private-log", format: "auto" } } as never), + fn({ + data: { + brandId: "other-brand", + content: "private-log", + format: "auto", + url: "https://example.com/", + token: "secret", + apiKey: "secret", + }, + } as never), ).rejects.toThrow("Forbidden"); for (const call of [ m.read, @@ -69,8 +106,15 @@ it.each([ m.importLog, m.properties, m.gscSync, + m.gscInspect, m.gscDisconnect, m.gscProperties, + m.cfConnect, + m.cfSync, + m.cfDisconnect, + m.bingConnect, + m.bingSync, + m.bingDisconnect, ]) expect(call).not.toHaveBeenCalled(); }); diff --git a/apps/web/src/server/traffic-core.ts b/apps/web/src/server/traffic-core.ts index ce22fa7..13d92e6 100644 --- a/apps/web/src/server/traffic-core.ts +++ b/apps/web/src/server/traffic-core.ts @@ -1,14 +1,54 @@ import { brandLinkParams } from "@workspace/lib/app-urls"; import { db } from "@workspace/lib/db/db"; import { analysisEvidence, brandDataSources, brands, organization } from "@workspace/lib/db/schema"; +import { decryptSecret, encryptSecret, getKeyring } from "@workspace/lib/secrets"; +import { fetchBingWebmaster, normalizeBingSiteUrl } from "@workspace/lib/traffic/bing"; +import { fetchCloudflareBots } from "@workspace/lib/traffic/cloudflare"; import { analyzeCrawls, siteHostname } from "@workspace/lib/traffic/crawls"; import { fetchGa, fetchGaPerformance, type GaSummary, gaProperty, listGaProperties } from "@workspace/lib/traffic/ga"; -import { fetchGscAnalysis, listGscProperties } from "@workspace/lib/traffic/gsc"; +import { fetchGscAnalysis, inspectGscUrl, listGscProperties } from "@workspace/lib/traffic/gsc"; import { and, eq, sql } from "drizzle-orm"; import { type GaTokens, gaClient, sealGa, usableGaTokens } from "./ga-oauth-core"; import type { GoogleGrant } from "./google-oauth-core"; import { type GscTokens, sealGsc, usableGscTokens } from "./gsc-oauth-core"; +function trafficKeyring() { + const keys = getKeyring(); + if (!keys) throw new Error("The workspace encryption key is required to store data source credentials."); + return keys; +} + +async function sealSourceSecret(kind: "cloudflare" | "bing", brandId: string, value: string) { + return encryptSecret(JSON.stringify({ secret: value }), { + key: trafficKeyring().primary, + aad: `${kind}:${brandId}`, + }); +} + +async function openSourceSecret(kind: "cloudflare" | "bing", brandId: string, encrypted: string): Promise { + const parsed = JSON.parse( + await decryptSecret(encrypted, { keyring: trafficKeyring(), aad: `${kind}:${brandId}` }), + ) as { + secret?: string; + }; + if (!parsed?.secret) throw new Error("Stored data source credentials could not be read. Reconnect this source."); + return parsed.secret; +} + +function ownedHosts(brand: { website: string; additionalDomains?: string[] | null }) { + return [brand.website, ...(brand.additionalDomains ?? [])].map(brandHostname); +} + +function hostMatchesBrand(candidateHost: string, hosts: string[]) { + const normalized = candidateHost.toLowerCase().replace(/\.$/, ""); + if (!normalized || !normalized.includes(".")) return false; + return hosts.some((host) => { + const base = host.toLowerCase().replace(/\.$/, ""); + const apex = base.startsWith("www.") && base.slice(4).includes(".") ? base.slice(4) : base; + return normalized === base || normalized === apex || normalized.endsWith(`.${apex}`); + }); +} + function sourceWhere(brandId: string, kind: string) { return and(eq(brandDataSources.brandId, brandId), eq(brandDataSources.kind, kind)); } @@ -45,6 +85,8 @@ export async function readTraffic(brandId: string) { ga: rows.find((r) => r.kind === "ga") ?? null, gsc: rows.find((r) => r.kind === "gsc") ?? null, crawls: rows.find((r) => r.kind === "crawls") ?? null, + cloudflare: rows.find((r) => r.kind === "cloudflare") ?? null, + bing: rows.find((r) => r.kind === "bing") ?? null, }; } type TrafficTx = Parameters[0]>[0]; @@ -213,7 +255,7 @@ export async function syncGsc(brandId: string, property?: string) { siteUrl: selected, startDate: date(31), endDate: date(4), - fetchImpl: boundedGoogleFetch(56), + fetchImpl: boundedGoogleFetch(64), }); await tx .update(brandDataSources) @@ -228,11 +270,168 @@ export async function syncGsc(brandId: string, property?: string) { return snapshot; }); } +export async function inspectGscPage(brandId: string, inspectionUrl: string) { + return withGsc(brandId, async (tx, row) => { + const tokens = await usableGscTokens(row.encryptedCredentials!, brandId); + const selected = row.config?.property?.id; + if (!selected) throw new Error("Choose a Search Console property first."); + const brand = await trafficBrand(brandId); + let parsed: URL; + try { + parsed = new URL(inspectionUrl.trim()); + } catch { + throw new Error("Enter a valid HTTP or HTTPS URL to inspect."); + } + if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.port) + throw new Error("Enter a valid HTTP or HTTPS URL without credentials or a custom port."); + parsed.hash = ""; + const targetHost = brandHostname(parsed.origin); + if (!hostMatchesBrand(targetHost, ownedHosts(brand))) + throw new Error("Inspect a URL on a hostname saved in this brand's settings."); + const result = await inspectGscUrl({ + token: tokens.accessToken, + siteUrl: selected, + inspectionUrl: parsed.href, + fetchImpl: boundedGoogleFetch(4), + }); + await tx + .update(brandDataSources) + .set({ encryptedCredentials: await sealGsc(tokens, brandId) }) + .where(sourceWhere(brandId, "gsc")); + return result; + }); +} export async function disconnectGsc(brandId: string) { await withGsc(brandId, async (tx) => { await tx.delete(brandDataSources).where(sourceWhere(brandId, "gsc")); }); } +export async function connectCloudflare(brandId: string, token: string, zoneNameInput?: string, days = 7) { + trafficKeyring(); + const brand = await trafficBrand(brandId); + const site = brandHostname(brand.website); + const zoneName = (zoneNameInput?.trim() || site) + .toLowerCase() + .replace(/^https?:\/\//, "") + .replace(/\/.*$/, ""); + if (!hostMatchesBrand(zoneName, ownedHosts(brand))) + throw new Error("Choose a Cloudflare zone matching a hostname saved in this brand."); + const summary = await fetchCloudflareBots({ token, zoneName, days }); + const encryptedCredentials = await sealSourceSecret("cloudflare", brandId, token.trim()); + await withTrafficLock(brandId, async (tx) => + tx + .insert(brandDataSources) + .values({ + brandId, + kind: "cloudflare", + encryptedCredentials, + config: { site, zoneId: summary.zoneId, zoneName: summary.zoneName, days: summary.days }, + snapshot: summary, + }) + .onConflictDoUpdate({ + target: [brandDataSources.brandId, brandDataSources.kind], + set: { + encryptedCredentials, + config: { site, zoneId: summary.zoneId, zoneName: summary.zoneName, days: summary.days }, + snapshot: summary, + updatedAt: new Date(), + }, + }), + ); + return summary; +} +export async function syncCloudflare(brandId: string, days?: number) { + return withTrafficLock(brandId, async (tx) => { + const [row] = await tx.select().from(brandDataSources).where(sourceWhere(brandId, "cloudflare")); + if (!row?.encryptedCredentials) throw new Error("Connect Cloudflare first."); + const token = await openSourceSecret("cloudflare", brandId, row.encryptedCredentials); + const brand = await trafficBrand(brandId); + const site = brandHostname(brand.website); + const zoneName = row.config?.zoneName || site; + if (!hostMatchesBrand(zoneName, ownedHosts(brand))) + throw new Error("Stored Cloudflare zone no longer matches this brand's domains. Reconnect Cloudflare."); + const lookback = days ?? row.config?.days ?? 7; + const summary = await fetchCloudflareBots({ + token, + zoneId: row.config?.zoneId, + zoneName, + days: lookback, + }); + await tx + .update(brandDataSources) + .set({ + config: { site, zoneId: summary.zoneId, zoneName: summary.zoneName, days: summary.days }, + snapshot: summary, + updatedAt: new Date(), + }) + .where(sourceWhere(brandId, "cloudflare")); + return summary; + }); +} +export async function disconnectCloudflare(brandId: string) { + await withTrafficLock(brandId, async (tx) => { + await tx.delete(brandDataSources).where(sourceWhere(brandId, "cloudflare")); + }); +} +export async function connectBing(brandId: string, apiKey: string, siteUrlInput?: string) { + trafficKeyring(); + const brand = await trafficBrand(brandId); + const site = brandHostname(brand.website); + const siteUrl = normalizeBingSiteUrl(siteUrlInput?.trim() || `https://${site}/`); + const targetHost = brandHostname(siteUrl); + if (!hostMatchesBrand(targetHost, ownedHosts(brand))) + throw new Error("Choose a Bing site URL matching a hostname saved in this brand."); + const summary = await fetchBingWebmaster({ apiKey, siteUrl }); + const encryptedCredentials = await sealSourceSecret("bing", brandId, apiKey.trim()); + await withTrafficLock(brandId, async (tx) => + tx + .insert(brandDataSources) + .values({ + brandId, + kind: "bing", + encryptedCredentials, + config: { site, siteUrl: summary.siteUrl }, + snapshot: summary, + }) + .onConflictDoUpdate({ + target: [brandDataSources.brandId, brandDataSources.kind], + set: { + encryptedCredentials, + config: { site, siteUrl: summary.siteUrl }, + snapshot: summary, + updatedAt: new Date(), + }, + }), + ); + return summary; +} +export async function syncBing(brandId: string) { + return withTrafficLock(brandId, async (tx) => { + const [row] = await tx.select().from(brandDataSources).where(sourceWhere(brandId, "bing")); + if (!row?.encryptedCredentials) throw new Error("Connect Bing Webmaster first."); + const apiKey = await openSourceSecret("bing", brandId, row.encryptedCredentials); + const brand = await trafficBrand(brandId); + const site = brandHostname(brand.website); + const siteUrl = row.config?.siteUrl || `https://${site}/`; + if (!hostMatchesBrand(brandHostname(siteUrl), ownedHosts(brand))) + throw new Error("Stored Bing site URL no longer matches this brand's domains. Reconnect Bing Webmaster."); + const summary = await fetchBingWebmaster({ apiKey, siteUrl }); + await tx + .update(brandDataSources) + .set({ + config: { site, siteUrl: summary.siteUrl }, + snapshot: summary, + updatedAt: new Date(), + }) + .where(sourceWhere(brandId, "bing")); + return summary; + }); +} +export async function disconnectBing(brandId: string) { + await withTrafficLock(brandId, async (tx) => { + await tx.delete(brandDataSources).where(sourceWhere(brandId, "bing")); + }); +} export async function importCrawlTraffic( brandId: string, content: string, diff --git a/apps/web/src/server/traffic-fn.ts b/apps/web/src/server/traffic-fn.ts index d48d5e0..9a0b78e 100644 --- a/apps/web/src/server/traffic-fn.ts +++ b/apps/web/src/server/traffic-fn.ts @@ -6,12 +6,19 @@ import { beginGaOAuth, GA_COOKIE, gaClient } from "./ga-oauth-core"; import { beginGoogleOAuth, GOOGLE_COOKIE, sharedGoogleClient } from "./google-oauth-core"; import { beginGscOAuth, GSC_COOKIE, gscClient } from "./gsc-oauth-core"; import { + connectBing, + connectCloudflare, + disconnectBing, + disconnectCloudflare, disconnectGa, disconnectGsc, gaProperties, gscProperties, importCrawlTraffic, + inspectGscPage, readTraffic, + syncBing, + syncCloudflare, syncGa, syncGsc, trafficReturnTo, @@ -141,3 +148,58 @@ export const importCrawlsFn = createServerFn({ method: "POST" }) await requireBrandSession(data.brandId); return importCrawlTraffic(data.brandId, data.content, data.format); }); +export const inspectGscUrlFn = createServerFn({ method: "POST" }) + .validator(brandInput.extend({ url: z.string().min(1).max(2048) })) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + return inspectGscPage(data.brandId, data.url); + }); +export const connectCloudflareFn = createServerFn({ method: "POST" }) + .validator( + brandInput.extend({ + token: z.string().min(1).max(512), + zoneName: z.string().max(253).optional(), + days: z.number().int().min(1).max(30).optional(), + }), + ) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + return connectCloudflare(data.brandId, data.token, data.zoneName, data.days); + }); +export const syncCloudflareFn = createServerFn({ method: "POST" }) + .validator(brandInput.extend({ days: z.number().int().min(1).max(30).optional() })) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + return syncCloudflare(data.brandId, data.days); + }); +export const disconnectCloudflareFn = createServerFn({ method: "POST" }) + .validator(brandInput) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + await disconnectCloudflare(data.brandId); + return { disconnected: true }; + }); +export const connectBingFn = createServerFn({ method: "POST" }) + .validator( + brandInput.extend({ + apiKey: z.string().min(1).max(512), + siteUrl: z.string().max(2048).optional(), + }), + ) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + return connectBing(data.brandId, data.apiKey, data.siteUrl); + }); +export const syncBingFn = createServerFn({ method: "POST" }) + .validator(brandInput) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + return syncBing(data.brandId); + }); +export const disconnectBingFn = createServerFn({ method: "POST" }) + .validator(brandInput) + .handler(async ({ data }) => { + await requireBrandSession(data.brandId); + await disconnectBing(data.brandId); + return { disconnected: true }; + }); diff --git a/packages/lib/package.json b/packages/lib/package.json index fabd680..7c88f9d 100644 --- a/packages/lib/package.json +++ b/packages/lib/package.json @@ -49,6 +49,8 @@ "./traffic/ga": "./src/traffic/ga.mjs", "./traffic/gsc": "./src/traffic/gsc.mjs", "./traffic/crawls": "./src/traffic/crawls.mjs", + "./traffic/cloudflare": "./src/traffic/cloudflare.mjs", + "./traffic/bing": "./src/traffic/bing.mjs", "./search-analysis": "./src/search-analysis.ts", "./ai-reports": "./src/ai-reports.ts" }, diff --git a/packages/lib/src/db/schema.ts b/packages/lib/src/db/schema.ts index 986d9fe..b5c214f 100644 --- a/packages/lib/src/db/schema.ts +++ b/packages/lib/src/db/schema.ts @@ -391,12 +391,18 @@ export const brandDataSources = pgTable( config: jsonb("config").$type<{ property?: { id: string; name: string }; site: string; + siteUrl?: string; + zoneId?: string; + zoneName?: string; + days?: number; aiReport?: Record; }>(), snapshot: jsonb("snapshot").$type< | import("../traffic/ga.mjs").GaSummary | import("../traffic/crawls.mjs").CrawlSummary | import("../traffic/gsc.mjs").GscSummary + | import("../traffic/cloudflare.mjs").CloudflareBotsSummary + | import("../traffic/bing.mjs").BingSummary | import("../ai-reports").AiReport >(), updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), diff --git a/packages/lib/src/public-page.ts b/packages/lib/src/public-page.ts index d70bb09..5a65510 100644 --- a/packages/lib/src/public-page.ts +++ b/packages/lib/src/public-page.ts @@ -59,9 +59,19 @@ export interface PublicPage { body: string; contentType: string; robots: string; + server?: string; + cfMitigated?: string; } -async function requestPage(url: URL, signal: AbortSignal): Promise { +export interface FetchPublicPageOptions { + userAgent?: string; +} + +async function requestPage( + url: URL, + signal: AbortSignal, + options?: FetchPublicPageOptions, +): Promise { const host = url.hostname.replace(/^\[|\]$/g, ""); const records = await Promise.race([ lookup(host, { all: true }), @@ -82,7 +92,7 @@ async function requestPage(url: URL, signal: AbortSignal): Promise { +export async function fetchPublicPage(value: string, options?: FetchPublicPageOptions): Promise { let url = publicUrl(value); const signal = AbortSignal.timeout(15_000); for (let redirects = 0; redirects <= 3; redirects++) { - const page = await requestPage(url, signal); + const page = await requestPage(url, signal, options); if (page.status < 300 || page.status >= 400 || !page.location) return page; url = publicUrl(new URL(page.location, url).href); } diff --git a/packages/lib/src/site-audit.test.ts b/packages/lib/src/site-audit.test.ts index 74893e5..a5559ff 100644 --- a/packages/lib/src/site-audit.test.ts +++ b/packages/lib/src/site-audit.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { isPublicAddress, publicUrl } from "./public-page"; -import { auditFailure, inspectHtml, scanSite } from "./site-audit"; +import { auditFailure, evaluateRobotsForBots, inspectHtml, scanSite } from "./site-audit"; const page = { url: "https://example.com/", @@ -53,7 +53,7 @@ describe("public website audit boundaries", () => { const result = await scanSite("example.com", async () => { throw new Error("timeout"); }); - expect(result).toMatchObject({ passed: 0, evaluated: 0, total: 9 }); + expect(result).toMatchObject({ passed: 0, evaluated: 0, total: 13 }); expect(result.checks.every((c) => c.state === "unknown")).toBe(true); expect(result.checks[0].suggestion).toContain("timed out"); }); @@ -72,4 +72,65 @@ describe("public website audit boundaries", () => { expect(result.checks.find((c) => c.id === "robots")?.state).toBe("pass"); expect(result.checks.find((c) => c.id === "sitemap")?.state).toBe("issue"); }); + it("evaluates robots.txt per AI crawler, detects llms.txt, SSR signals and WAF challenges", async () => { + const robotsText = [ + "User-agent: *", + "Allow: /", + "User-agent: OAI-SearchBot", + "Disallow: /", + "User-agent: GPTBot", + "Disallow: /", + ].join("\n"); + const matrix = evaluateRobotsForBots(robotsText, "/"); + expect(matrix.find((m) => m.bot === "OAI-SearchBot")?.allowed).toBe(false); + expect(matrix.find((m) => m.bot === "ChatGPT-User")?.allowed).toBe(true); + expect(matrix.find((m) => m.bot === "GPTBot")?.allowed).toBe(false); + + const richBody = `API Gateway

Unified AI API

Pricing

${"Developer API documentation and pricing starting at $0.05 per call. ".repeat(6)}

curl https://api.example.com`; + const result = await scanSite("example.com", async (url, options) => { + if (url.endsWith("/robots.txt")) + return { url, status: 200, contentType: "text/plain", robots: "", body: robotsText }; + if (url.endsWith("/sitemap.xml")) + return { url, status: 200, contentType: "application/xml", robots: "", body: "" }; + if (url.endsWith("/llms.txt")) + return { url, status: 200, contentType: "text/plain", robots: "", body: "# Example\n> API docs" }; + if (url.endsWith("/llms-full.txt")) return { url, status: 404, contentType: "text/plain", robots: "", body: "" }; + if (options?.userAgent?.includes("OAI-SearchBot")) { + return { + url, + status: 403, + contentType: "text/html", + robots: "", + cfMitigated: "challenge", + body: "Just a moment...", + }; + } + return { url, status: 200, contentType: "text/html", robots: "", body: richBody }; + }); + + expect(result.checks.find((c) => c.id === "llms_txt")?.state).toBe("pass"); + expect(result.checks.find((c) => c.id === "ssr_content")?.state).toBe("pass"); + expect(result.checks.find((c) => c.id === "ai_crawlers")?.state).toBe("issue"); + expect(result.checks.find((c) => c.id === "ua_access")?.state).toBe("issue"); + expect(result.aeo?.ssr.jsonLdTypes).toEqual(["SoftwareApplication"]); + expect(result.aeo?.ssr.hasPrice).toBe(true); + expect(result.aeo?.ssr.hasCode).toBe(true); + expect(result.aeo?.uaMatrix.find((u) => u.bot === "OAI-SearchBot")?.challenge).toBe(true); + }); + it("avoids false challenge detections on normal 200 copy and treats partial UA timeouts as unknown", async () => { + const normalBody = `Fast API Docs

API

${"Get started in just a moment with our fast developer SDK and documentation. ".repeat(5)}

`; + const result = await scanSite("example.com", async (url, options) => { + if (url.endsWith("/robots.txt")) + return { url, status: 200, contentType: "text/plain", robots: "", body: "User-agent: *\nAllow: /" }; + if (url.endsWith("/sitemap.xml")) + return { url, status: 200, contentType: "application/xml", robots: "", body: "" }; + if (url.endsWith("/llms.txt") || url.endsWith("/llms-full.txt")) + return { url, status: 404, contentType: "text/plain", robots: "", body: "" }; + if (options?.userAgent?.toLowerCase().includes("bingbot")) throw new Error("timeout"); + return { url, status: 200, contentType: "text/html", robots: "", body: normalBody }; + }); + expect(result.checks.find((c) => c.id === "ssr_content")?.state).toBe("pass"); + expect(result.aeo?.ssr.challengeDetected).toBe(false); + expect(result.checks.find((c) => c.id === "ua_access")?.state).toBe("unknown"); + }); }); diff --git a/packages/lib/src/site-audit.ts b/packages/lib/src/site-audit.ts index 4b21721..bdc97fd 100644 --- a/packages/lib/src/site-audit.ts +++ b/packages/lib/src/site-audit.ts @@ -1,5 +1,52 @@ import { parseHTML } from "linkedom"; -import { fetchPublicPage, type PublicPage, publicUrl } from "./public-page"; +import { type FetchPublicPageOptions, fetchPublicPage, type PublicPage, publicUrl } from "./public-page"; + +const STRICT_CHALLENGE_PATTERN = /cf-chl|challenge-platform|cf_chl_opt/i; +const TITLE_CHALLENGE_PATTERN = /Just a moment|Attention Required|Enable JavaScript and cookies/i; + +export const AEO_ROBOTS_BOTS = [ + { name: "OAI-SearchBot", role: "search" }, + { name: "ChatGPT-User", role: "user" }, + { name: "GPTBot", role: "training" }, + { name: "Bingbot", role: "search" }, + { name: "Googlebot", role: "search" }, + { name: "PerplexityBot", role: "search" }, + { name: "Claude-SearchBot", role: "search" }, + { name: "ClaudeBot", role: "training" }, +] as const; + +export const AEO_PROBE_USER_AGENTS = [ + { + name: "OAI-SearchBot", + role: "search" as const, + ua: "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-SearchBot/1.3; +https://openai.com/searchbot", + }, + { + name: "ChatGPT-User", + role: "user" as const, + ua: "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot", + }, + { + name: "PerplexityBot", + role: "search" as const, + ua: "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot", + }, + { + name: "Claude-SearchBot", + role: "search" as const, + ua: "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; Claude-SearchBot/1.0; +https://www.anthropic.com", + }, + { + name: "Bingbot", + role: "search" as const, + ua: "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm) Chrome/116.0.1938.76 Safari/537.36", + }, + { + name: "Googlebot", + role: "search" as const, + ua: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.6668.70 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", + }, +] as const; export async function readWebsiteContext(website: string) { const url = publicUrl(/^https?:\/\//i.test(website) ? website : `https://${website}`); @@ -26,6 +73,40 @@ export interface AuditCheck { evidence: string; suggestion: string; } + +export interface RobotsBotPolicy { + bot: string; + role: "search" | "user" | "training"; + allowed: boolean; + matchedAgent: string; +} + +export interface UaProbeResult { + bot: string; + role: "search" | "user"; + status: number; + bytes: number; + challenge: boolean; + server: string; + error?: string; +} + +export interface AeoSignals { + llmsTxt: { status: number; bytes: number; found: boolean }; + llmsFullTxt: { status: number; bytes: number; found: boolean }; + robotsMatrix: RobotsBotPolicy[]; + ssr: { + textChars: number; + h2Count: number; + hasPrice: boolean; + hasCode: boolean; + hreflang: string[]; + jsonLdTypes: string[]; + challengeDetected: boolean; + }; + uaMatrix: UaProbeResult[]; +} + export interface SiteAudit { url: string; checkedAt: string; @@ -33,6 +114,7 @@ export interface SiteAudit { passed: number; evaluated: number; total: number; + aeo?: AeoSignals; } export function auditFailure(error: unknown): string { @@ -45,14 +127,172 @@ export function auditFailure(error: unknown): string { return "The website could not be reached. Check network access and retry."; } +function isChallengePage(page: PublicPage) { + if (page.cfMitigated?.toLowerCase() === "challenge") return true; + const head = page.body.slice(0, 20_000); + if (STRICT_CHALLENGE_PATTERN.test(head)) return true; + if (page.status !== 200) return TITLE_CHALLENGE_PATTERN.test(head); + const titleMatch = head.match(/]*>([\s\S]*?)<\/title>/i); + return Boolean(titleMatch && TITLE_CHALLENGE_PATTERN.test(titleMatch[1])); +} + +function collectJsonLdTypes(node: unknown, types: Set) { + if (!node || typeof node !== "object") return; + if (Array.isArray(node)) { + for (const item of node) collectJsonLdTypes(item, types); + return; + } + const record = node as Record; + const type = record["@type"]; + if (typeof type === "string") types.add(type); + else if (Array.isArray(type)) { + for (const entry of type) if (typeof entry === "string") types.add(entry); + } + for (const value of Object.values(record)) collectJsonLdTypes(value, types); +} + +function extractJsonLdTypes(document: ReturnType["document"]) { + const structured = Array.from<{ textContent: string | null }>( + document.querySelectorAll('script[type="application/ld+json"]'), + ); + const types = new Set(); + let validJson = false; + for (const element of structured) { + try { + const parsed: unknown = JSON.parse(element.textContent ?? ""); + if (parsed && typeof parsed === "object") { + validJson = true; + collectJsonLdTypes(parsed, types); + } + } catch { + // Ignore malformed blocks; validJson tracks whether at least one valid block exists. + } + } + return { count: structured.length, validJson, types: [...types].sort() }; +} + +export function extractSsrSignals(page: PublicPage): AeoSignals["ssr"] { + if (page.status !== 200 || !/text\/html/i.test(page.contentType)) { + return { + textChars: 0, + h2Count: 0, + hasPrice: false, + hasCode: false, + hreflang: [], + jsonLdTypes: [], + challengeDetected: isChallengePage(page), + }; + } + const { document } = parseHTML(page.body); + const ld = extractJsonLdTypes(document); + const h2Count = document.querySelectorAll("h2").length; + const hasCode = Boolean(document.querySelector("pre,code")); + const hreflang = Array.from( + new Set( + Array.from<{ getAttribute(name: string): string | null }>(document.querySelectorAll("link[hreflang]")) + .map((el) => el.getAttribute("hreflang")?.trim() ?? "") + .filter(Boolean), + ), + ).sort(); + for (const el of document.querySelectorAll("script,style,noscript,svg")) el.remove(); + const text = (document.body?.textContent || document.documentElement?.textContent || "").replace(/\s+/g, " ").trim(); + return { + textChars: text.length, + h2Count, + hasPrice: /\$\s?\d|\d+\s?(?:USD|EUR|JPY|KRW)/i.test(text), + hasCode, + hreflang, + jsonLdTypes: ld.types, + challengeDetected: isChallengePage(page), + }; +} + +type RobotsRule = { type: "allow" | "disallow"; pattern: string }; +type RobotsGroup = { agents: string[]; rules: RobotsRule[] }; + +function parseRobotsLine(rawLine: string) { + const line = rawLine.replace(/#.*$/, "").trim(); + const colon = line.indexOf(":"); + if (colon === -1) return null; + return { directive: line.slice(0, colon).trim().toLowerCase(), value: line.slice(colon + 1).trim() }; +} + +function ensureRobotsGroup(groups: RobotsGroup[], current: RobotsGroup | null, sawRule: boolean) { + if (current && !sawRule) return current; + const created: RobotsGroup = { agents: [], rules: [] }; + groups.push(created); + return created; +} + +function parseRobotsGroups(robotsBody: string): RobotsGroup[] { + const groups: RobotsGroup[] = []; + let current: RobotsGroup | null = null; + let sawRule = false; + for (const parsed of robotsBody.split(/\r?\n/).map(parseRobotsLine)) { + if (!parsed) continue; + if (parsed.directive === "user-agent") { + current = ensureRobotsGroup(groups, current, sawRule); + sawRule = false; + if (parsed.value) current.agents.push(parsed.value.toLowerCase()); + continue; + } + if (!current) continue; + if (parsed.directive === "allow" || parsed.directive === "disallow") { + sawRule = true; + current.rules.push({ type: parsed.directive, pattern: parsed.value }); + } + } + return groups; +} + +function matchesRobotsPattern(pattern: string, target: string) { + if (!pattern) return false; + const collapsed = pattern.replace(/\*+/g, "*"); + const regexText = `^${collapsed + .replace(/[.+?^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\\\$$/, "$")}`; + return new RegExp(regexText).test(target); +} + +function evaluateBotPolicy(groups: RobotsGroup[], name: string, path: string) { + const needle = name.toLowerCase(); + const exactGroups = groups.filter((g) => g.agents.includes(needle)); + const wildcardGroups = groups.filter((g) => g.agents.includes("*")); + const matched = exactGroups.length ? exactGroups : wildcardGroups; + const matchedAgent = exactGroups.length ? name : wildcardGroups.length ? "*" : "none"; + let bestLen = -1; + let allowed = true; + for (const rule of matched.flatMap((g) => g.rules)) { + if ((rule.type === "disallow" && !rule.pattern) || !matchesRobotsPattern(rule.pattern, path)) continue; + const specificity = rule.pattern.length; + if (specificity > bestLen || (specificity === bestLen && rule.type === "allow")) { + bestLen = specificity; + allowed = rule.type === "allow"; + } + } + return { allowed, matchedAgent }; +} + +export function evaluateRobotsForBots(robotsBody: string, path = "/"): RobotsBotPolicy[] { + const groups = parseRobotsGroups(robotsBody); + return AEO_ROBOTS_BOTS.map(({ name, role }) => ({ + bot: name, + role, + ...evaluateBotPolicy(groups, name, path), + })); +} + export function inspectHtml(page: PublicPage): AuditCheck[] { if (page.status !== 200 || !/text\/html/i.test(page.contentType)) - return ["page", "title", "description", "heading", "indexing", "canonical", "structured_data"].map((id) => ({ - id, - state: "unknown", - evidence: `HTTP ${page.status}; ${page.contentType.slice(0, 100)}`, - suggestion: "Check homepage availability. This scan does not execute JavaScript or bypass website protection.", - })); + return ["page", "title", "description", "heading", "indexing", "canonical", "structured_data", "ssr_content"].map( + (id) => ({ + id, + state: "unknown", + evidence: `HTTP ${page.status}; ${page.contentType.slice(0, 100)}`, + suggestion: "Check homepage availability. This scan does not execute JavaScript or bypass website protection.", + }), + ); const { document } = parseHTML(page.body); const title = document.querySelector("title")?.textContent?.trim() ?? ""; const description = document.querySelector('meta[name="description" i]')?.getAttribute("content")?.trim() ?? ""; @@ -62,17 +302,8 @@ export function inspectHtml(page: PublicPage): AuditCheck[] { ) .map((el) => el.getAttribute("content") ?? "") .join(" ")}`; - const structured = Array.from<{ textContent: string | null }>( - document.querySelectorAll('script[type="application/ld+json"]'), - ); - const validJson = structured.some((element) => { - try { - const data: unknown = JSON.parse(element.textContent ?? ""); - return Boolean(data && typeof data === "object"); - } catch { - return false; - } - }); + const ld = extractJsonLdTypes(document); + const ssr = extractSsrSignals(page); const check = (id: string, pass: boolean, evidence: string, suggestion: string): AuditCheck => ({ id, state: pass ? "pass" : "issue", @@ -108,18 +339,40 @@ export function inspectHtml(page: PublicPage): AuditCheck[] { ), check( "structured_data", - validJson, - `${structured.length} JSON-LD blocks; JSON syntax checked only`, + ld.validJson, + `${ld.count} JSON-LD blocks${ld.types.length ? ` (${ld.types.join(", ")})` : ""}; JSON syntax checked only`, "Add relevant, accurate structured data and validate it against the applicable schema.", ), + check( + "ssr_content", + !ssr.challengeDetected && ssr.textChars >= 200, + ssr.challengeDetected + ? "Bot challenge detected in static HTML response" + : `${ssr.textChars} visible text chars in static HTML · ${ssr.h2Count} H2${ssr.hasPrice ? " · pricing detected" : ""}`, + "Ensure core copy and pricing render in initial server HTML without requiring JavaScript or bot challenges.", + ), ]; } -export async function scanSite(value: string, fetchPage = fetchPublicPage): Promise { +export async function scanSite( + value: string, + fetchPage: (url: string, options?: FetchPublicPageOptions) => Promise = fetchPublicPage, +): Promise { const url = publicUrl(/^https?:\/\//i.test(value) ? value : `https://${value}`); const checks: AuditCheck[] = []; + let ssr: AeoSignals["ssr"] = { + textChars: 0, + h2Count: 0, + hasPrice: false, + hasCode: false, + hreflang: [], + jsonLdTypes: [], + challengeDetected: false, + }; try { - checks.push(...inspectHtml(await fetchPage(url.href))); + const home = await fetchPage(url.href); + ssr = extractSsrSignals(home); + checks.push(...inspectHtml(home)); } catch (error) { checks.push( ...inspectHtml({ url: url.href, status: 0, body: "", contentType: "Unavailable", robots: "" }).map((check) => ({ @@ -129,12 +382,16 @@ export async function scanSite(value: string, fetchPage = fetchPublicPage): Prom })), ); } - checks.push( - ...(await Promise.all([ - inspectFile("robots", "/robots.txt", url, fetchPage), - inspectFile("sitemap", "/sitemap.xml", url, fetchPage), - ])), - ); + + const [robotsResult, sitemapCheck, llmsResult, uaMatrix] = await Promise.all([ + inspectRobots(url, fetchPage), + inspectFile("sitemap", "/sitemap.xml", url, fetchPage), + inspectLlmsFiles(url, fetchPage), + probeUserAgents(url, fetchPage), + ]); + + checks.push(robotsResult.robotsCheck, sitemapCheck, robotsResult.aiCrawlersCheck, llmsResult.check, uaMatrix.check); + return { url: url.href, checkedAt: new Date().toISOString(), @@ -142,28 +399,198 @@ export async function scanSite(value: string, fetchPage = fetchPublicPage): Prom passed: checks.filter((c) => c.state === "pass").length, evaluated: checks.filter((c) => c.state !== "unknown").length, total: checks.length, + aeo: { + llmsTxt: llmsResult.llmsTxt, + llmsFullTxt: llmsResult.llmsFullTxt, + robotsMatrix: robotsResult.matrix, + ssr, + uaMatrix: uaMatrix.rows, + }, + }; +} + +async function inspectRobots( + url: URL, + fetchPage: (url: string, options?: FetchPublicPageOptions) => Promise, +): Promise<{ robotsCheck: AuditCheck; aiCrawlersCheck: AuditCheck; matrix: RobotsBotPolicy[] }> { + try { + const page = await fetchPage(new URL("/robots.txt", url).href); + const found = page.status === 200 && /user-agent\s*:/i.test(page.body); + const matrix = found ? evaluateRobotsForBots(page.body, url.pathname || "/") : []; + const blockedSearchBots = matrix + .filter((item) => item.role !== "training" && !item.allowed) + .map((item) => item.bot); + return { + robotsCheck: { + id: "robots", + state: found ? "pass" : page.status === 404 ? "issue" : "unknown", + evidence: `/robots.txt · HTTP ${page.status}${found ? " · recognized" : ""}`, + suggestion: "Review crawler rules. File presence alone does not prove AI crawlers can access the site.", + }, + aiCrawlersCheck: found + ? { + id: "ai_crawlers", + state: blockedSearchBots.length ? "issue" : "pass", + evidence: blockedSearchBots.length + ? `Blocked in robots.txt: ${blockedSearchBots.join(", ")}` + : `Search & user bots allowed in robots.txt (${matrix.filter((m) => m.role !== "training").length} checked)`, + suggestion: blockedSearchBots.length + ? "Allow OAI-SearchBot, ChatGPT-User, PerplexityBot, Bingbot and Googlebot in robots.txt if you want AI search visibility." + : "Keep search and user-triggered AI crawlers allowed; training crawlers (GPTBot, ClaudeBot) remain a separate policy choice.", + } + : { + id: "ai_crawlers", + state: "unknown", + evidence: "/robots.txt unavailable or unrecognized", + suggestion: "Publish a readable /robots.txt to explicitly control search and AI crawler policies.", + }, + matrix, + }; + } catch (error) { + const failure = auditFailure(error); + return { + robotsCheck: { id: "robots", state: "unknown", evidence: "/robots.txt", suggestion: failure }, + aiCrawlersCheck: { id: "ai_crawlers", state: "unknown", evidence: "/robots.txt", suggestion: failure }, + matrix: [], + }; + } +} + +async function inspectLlmsFiles( + url: URL, + fetchPage: (url: string, options?: FetchPublicPageOptions) => Promise, +): Promise<{ + check: AuditCheck; + llmsTxt: AeoSignals["llmsTxt"]; + llmsFullTxt: AeoSignals["llmsFullTxt"]; +}> { + const read = async (route: string) => { + try { + const page = await fetchPage(new URL(route, url).href); + const bytes = Buffer.byteLength(page.body, "utf8"); + const isText = !/text\/html/i.test(page.contentType) && !/^\s* 0 && isText, error: "" }; + } catch (error) { + return { status: 0, bytes: 0, found: false, error: auditFailure(error) }; + } + }; + const [llms, llmsFull] = await Promise.all([read("/llms.txt"), read("/llms-full.txt")]); + if (llms.error && llmsFull.error) { + return { + check: { id: "llms_txt", state: "unknown", evidence: "/llms.txt · /llms-full.txt", suggestion: llms.error }, + llmsTxt: { status: 0, bytes: 0, found: false }, + llmsFullTxt: { status: 0, bytes: 0, found: false }, + }; + } + const state: AuditCheck["state"] = + llms.found || llmsFull.found ? "pass" : llms.status === 404 && llmsFull.status === 404 ? "issue" : "unknown"; + return { + check: { + id: "llms_txt", + state, + evidence: `/llms.txt: HTTP ${llms.status} (${llms.bytes} B) · /llms-full.txt: HTTP ${llmsFull.status} (${llmsFull.bytes} B)`, + suggestion: + "Publish /llms.txt (and optionally /llms-full.txt) with concise Markdown links to your key docs, pricing and product pages.", + }, + llmsTxt: { status: llms.status, bytes: llms.bytes, found: llms.found }, + llmsFullTxt: { status: llmsFull.status, bytes: llmsFull.bytes, found: llmsFull.found }, + }; +} + +async function probeUserAgents( + url: URL, + fetchPage: (url: string, options?: FetchPublicPageOptions) => Promise, +): Promise<{ check: AuditCheck; rows: UaProbeResult[] }> { + const rows = await Promise.all( + AEO_PROBE_USER_AGENTS.map(async (probe): Promise => { + try { + const page = await fetchPage(url.href, { userAgent: probe.ua }); + return { + bot: probe.name, + role: probe.role, + status: page.status, + bytes: Buffer.byteLength(page.body, "utf8"), + challenge: isChallengePage(page), + server: page.server ?? "", + }; + } catch (error) { + return { + bot: probe.name, + role: probe.role, + status: 0, + bytes: 0, + challenge: false, + server: "", + error: auditFailure(error), + }; + } + }), + ); + const reachable = rows.filter((row) => !row.error); + if (!reachable.length) { + return { + check: { + id: "ua_access", + state: "unknown", + evidence: "AI crawler UA probes could not reach the homepage", + suggestion: rows[0]?.error || "Retry when the website is reachable.", + }, + rows, + }; + } + const blocked = reachable.filter((row) => row.challenge || (row.status >= 400 && row.status < 500)); + if (blocked.length) { + return { + check: { + id: "ua_access", + state: "issue", + evidence: `Blocked or challenged UAs: ${blocked.map((b) => `${b.bot} (${b.challenge ? "challenge" : `HTTP ${b.status}`})`).join(", ")}`, + suggestion: + "Verify WAF/CDN bot rules do not challenge OAI-SearchBot, ChatGPT-User, PerplexityBot, Bingbot or Googlebot. Note: spoofed UA probes do not prove verified crawler IP access.", + }, + rows, + }; + } + const inconclusive = rows.filter((row) => Boolean(row.error) || row.status !== 200); + if (inconclusive.length) { + return { + check: { + id: "ua_access", + state: "unknown", + evidence: `Inconclusive probes (${inconclusive.length}/${rows.length}): ${inconclusive.map((r) => `${r.bot} (${r.error ? "unreachable" : `HTTP ${r.status}`})`).join(", ")}`, + suggestion: + "Some User-Agent probes timed out or returned non-200 server errors. Retry when the site is stable.", + }, + rows, + }; + } + return { + check: { + id: "ua_access", + state: "pass", + evidence: `All ${rows.length} probed search/AI User-Agents received HTTP 200 without challenge pages`, + suggestion: + "Verify WAF/CDN bot rules do not challenge OAI-SearchBot, ChatGPT-User, PerplexityBot, Bingbot or Googlebot. Note: spoofed UA probes do not prove verified crawler IP access.", + }, + rows, }; } async function inspectFile( - id: "robots" | "sitemap", + id: "sitemap", route: string, url: URL, - fetchPage: typeof fetchPublicPage, + fetchPage: (url: string, options?: FetchPublicPageOptions) => Promise, ): Promise { try { const page = await fetchPage(new URL(route, url).href); - const found = - page.status === 200 && - (id === "robots" ? /user-agent\s*:/i.test(page.body) : /<(urlset|sitemapindex)\b/i.test(page.body)); + const found = page.status === 200 && /<(urlset|sitemapindex)\b/i.test(page.body); return { id, state: found ? "pass" : page.status === 404 ? "issue" : "unknown", evidence: `${route} · HTTP ${page.status}${found ? " · recognized" : ""}`, suggestion: - id === "robots" - ? "Review crawler rules. File presence alone does not prove AI crawlers can access the site." - : "Provide a discoverable sitemap. This scan checks /sitemap.xml only; a custom sitemap may exist elsewhere.", + "Provide a discoverable sitemap. This scan checks /sitemap.xml only; a custom sitemap may exist elsewhere.", }; } catch (error) { return { diff --git a/packages/lib/src/traffic/bing.d.mts b/packages/lib/src/traffic/bing.d.mts new file mode 100644 index 0000000..305e989 --- /dev/null +++ b/packages/lib/src/traffic/bing.d.mts @@ -0,0 +1,57 @@ +export type BingTrafficDay = { + date: string; + clicks: number; + impressions: number; +}; + +export type BingTrafficWindow = { + from: string; + to: string; + clicks: number; + impressions: number; + dayCount: number; +}; + +export type BingCrawlDay = { + date: string; + crawledPages: number; + crawlErrors: number; + inIndex: number; + inLinks: number; + blockedByRobots: number; + code4xx: number; + code5xx: number; + code301: number; +}; + +export type BingRow = { + key: string; + clicks: number; + impressions: number; + ctr: number; + position: number; +}; + +export type BingSummary = { + schema: "beat-geo/bing-summary@1"; + site: string; + siteUrl: string; + fetchedAt: string; + cur7d: BingTrafficWindow | null; + prev7d: BingTrafficWindow | null; + latestCrawl: BingCrawlDay | null; + days: BingTrafficDay[]; + crawlDays: BingCrawlDay[]; + queries: BingRow[]; + pages: BingRow[]; + quota: { dailyQuota: number | null; monthlyQuota: number | null } | null; + warning: string; +}; + +export function normalizeBingSiteUrl(value: string): string; +export function parseBingDate(value: unknown): string | null; +export function fetchBingWebmaster(options: { + apiKey: string; + siteUrl: string; + fetchImpl?: typeof fetch; +}): Promise; diff --git a/packages/lib/src/traffic/bing.mjs b/packages/lib/src/traffic/bing.mjs new file mode 100644 index 0000000..b8e5c4e --- /dev/null +++ b/packages/lib/src/traffic/bing.mjs @@ -0,0 +1,200 @@ +// Read-only Bing Webmaster API client (Get* methods only; no URL submission or write methods). + +const BING_BASE = "https://ssl.bing.com/webmaster/api.svc/json/"; + +function cleanApiKey(apiKey) { + if (typeof apiKey !== "string" || !apiKey.trim()) throw new Error("Bing Webmaster API key is required."); + return apiKey.trim(); +} + +export function normalizeBingSiteUrl(value) { + if (typeof value !== "string" || !value.trim()) throw new Error("Bing site URL is required."); + const raw = /^https?:\/\//i.test(value.trim()) ? value.trim() : `https://${value.trim()}`; + let parsed; + try { + parsed = new URL(raw); + } catch { + throw new Error("Enter a valid HTTP or HTTPS site URL for Bing Webmaster."); + } + if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.port) + throw new Error("Enter a valid HTTP or HTTPS site URL for Bing Webmaster."); + parsed.hash = ""; + parsed.search = ""; + if (!parsed.pathname) parsed.pathname = "/"; + return parsed.href; +} + +export function parseBingDate(value) { + if (value === null || value === undefined) return null; + if (typeof value === "number" && Number.isFinite(value)) { + const ms = value > 10_000_000_000 ? value : value * 1000; + return new Date(ms).toISOString().slice(0, 10); + } + const text = String(value); + const msMatch = text.match(/-?\d{10,13}/); + if (msMatch) { + const raw = Number(msMatch[0]); + const ms = Math.abs(raw) > 10_000_000_000 ? raw : raw * 1000; + if (Number.isFinite(ms)) return new Date(ms).toISOString().slice(0, 10); + } + if (/^\d{4}-\d{2}-\d{2}/.test(text)) return text.slice(0, 10); + return null; +} + +async function bingGet(method, { apiKey, siteUrl, fetchImpl }) { + const url = new URL(`${BING_BASE}${method}`); + url.searchParams.set("apikey", apiKey); + url.searchParams.set("siteUrl", siteUrl); + let response; + try { + response = await fetchImpl(url.href, { + method: "GET", + redirect: "error", + signal: AbortSignal.timeout(30000), + }); + } catch { + throw new Error(`Bing Webmaster ${method} request failed or timed out.`); + } + if (!response.ok) { + throw new Error(`Bing Webmaster ${method} HTTP ${response.status}. Check your API key and verified site URL.`); + } + let payload; + try { + payload = await response.json(); + } catch { + throw new Error(`Invalid Bing Webmaster ${method} response.`); + } + return payload && typeof payload === "object" && "d" in payload ? payload.d : payload; +} + +function finiteNumber(value) { + const n = Number(value ?? 0); + return Number.isFinite(n) && n >= 0 ? n : 0; +} + +function sumTrafficWindow(days, from, to) { + let clicks = 0; + let impressions = 0; + let dayCount = 0; + for (const row of days) { + if (row.date >= from && row.date <= to) { + clicks += row.clicks; + impressions += row.impressions; + dayCount += 1; + } + } + return { from, to, clicks, impressions, dayCount }; +} + +function shiftDate(iso, deltaDays) { + return new Date(Date.parse(`${iso}T00:00:00Z`) + deltaDays * 86400 * 1000).toISOString().slice(0, 10); +} + +export async function fetchBingWebmaster({ apiKey, siteUrl, fetchImpl = fetch }) { + const key = cleanApiKey(apiKey); + const normalizedUrl = normalizeBingSiteUrl(siteUrl); + + const [rawTraffic, rawQueries, rawPages, rawCrawl, rawQuota] = await Promise.all([ + bingGet("GetRankAndTrafficStats", { apiKey: key, siteUrl: normalizedUrl, fetchImpl }), + bingGet("GetQueryStats", { apiKey: key, siteUrl: normalizedUrl, fetchImpl }), + bingGet("GetPageStats", { apiKey: key, siteUrl: normalizedUrl, fetchImpl }), + bingGet("GetCrawlStats", { apiKey: key, siteUrl: normalizedUrl, fetchImpl }), + bingGet("GetUrlSubmissionQuota", { apiKey: key, siteUrl: normalizedUrl, fetchImpl }).catch(() => null), + ]); + + const trafficDays = (Array.isArray(rawTraffic) ? rawTraffic : []) + .map((row) => ({ + date: parseBingDate(row?.Date), + clicks: finiteNumber(row?.Clicks), + impressions: finiteNumber(row?.Impressions), + })) + .filter((row) => Boolean(row.date)) + .sort((a, b) => a.date.localeCompare(b.date)); + + let cur7d = null; + let prev7d = null; + if (trafficDays.length) { + const latestDate = trafficDays[trafficDays.length - 1].date; + const curStart = shiftDate(latestDate, -6); + const prevEnd = shiftDate(curStart, -1); + const prevStart = shiftDate(curStart, -7); + cur7d = sumTrafficWindow(trafficDays, curStart, latestDate); + const prevCandidate = sumTrafficWindow(trafficDays, prevStart, prevEnd); + prev7d = prevCandidate.dayCount > 0 ? prevCandidate : null; + } + + const crawlDays = (Array.isArray(rawCrawl) ? rawCrawl : []) + .map((row) => ({ + date: parseBingDate(row?.Date), + crawledPages: finiteNumber(row?.CrawledPages), + crawlErrors: finiteNumber(row?.CrawlErrors), + inIndex: finiteNumber(row?.InIndex), + inLinks: finiteNumber(row?.InLinks), + blockedByRobots: finiteNumber(row?.BlockedByRobotsTxt), + code4xx: finiteNumber(row?.Code4xx), + code5xx: finiteNumber(row?.Code5xx), + code301: finiteNumber(row?.Code301), + })) + .filter((row) => Boolean(row.date)) + .sort((a, b) => a.date.localeCompare(b.date)); + + const queries = aggregateKeywordRows(Array.isArray(rawQueries) ? rawQueries : [], "Query").slice(0, 200); + const pages = aggregateKeywordRows(Array.isArray(rawPages) ? rawPages : [], "Query").slice(0, 200); + + const quota = + rawQuota && typeof rawQuota === "object" + ? { + dailyQuota: Number.isFinite(Number(rawQuota.DailyQuota)) ? Number(rawQuota.DailyQuota) : null, + monthlyQuota: Number.isFinite(Number(rawQuota.MonthlyQuota)) ? Number(rawQuota.MonthlyQuota) : null, + } + : null; + + return { + schema: "beat-geo/bing-summary@1", + site: new URL(normalizedUrl).hostname, + siteUrl: normalizedUrl, + fetchedAt: new Date().toISOString(), + cur7d, + prev7d, + latestCrawl: crawlDays.length ? crawlDays[crawlDays.length - 1] : null, + days: trafficDays.slice(-28), + crawlDays: crawlDays.slice(-14), + queries, + pages, + quota, + warning: + "Bing Webmaster API is read-only here and typically lags by ~1 day. Full 4xx/5xx URL lists are not returned by the API and require exporting from Bing Webmaster Tools.", + }; +} + +function mergeKeywordRow(map, row, keyField) { + const key = typeof row?.[keyField] === "string" ? row[keyField].trim() : ""; + if (!key) return; + const clicks = finiteNumber(row?.Clicks); + const impressions = finiteNumber(row?.Impressions); + const rawPos = Number(row?.AvgImpressionPosition); + const hasPos = Number.isFinite(rawPos) && rawPos > 0; + const weight = hasPos ? impressions || 1 : 0; + const existing = map.get(key) ?? { key, clicks: 0, impressions: 0, weightedPos: 0, weight: 0 }; + existing.clicks += clicks; + existing.impressions += impressions; + if (hasPos) { + existing.weightedPos += rawPos * weight; + existing.weight += weight; + } + map.set(key, existing); +} + +function aggregateKeywordRows(rows, keyField) { + const map = new Map(); + for (const row of rows) mergeKeywordRow(map, row, keyField); + return [...map.values()] + .map((item) => ({ + key: item.key, + clicks: item.clicks, + impressions: item.impressions, + ctr: item.impressions > 0 ? item.clicks / item.impressions : 0, + position: item.weight > 0 ? Number((item.weightedPos / item.weight).toFixed(1)) : 0, + })) + .sort((a, b) => b.clicks - a.clicks || b.impressions - a.impressions); +} diff --git a/packages/lib/src/traffic/bing.test.ts b/packages/lib/src/traffic/bing.test.ts new file mode 100644 index 0000000..d3a5300 --- /dev/null +++ b/packages/lib/src/traffic/bing.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it, vi } from "vitest"; +import { fetchBingWebmaster, parseBingDate } from "./bing.mjs"; + +describe("Bing Webmaster read-only evidence", () => { + it("parses Microsoft JSON dates and computes 7-day comparisons, crawl stats and top rows", async () => { + expect(parseBingDate("/Date(1795824000000)/")).toBe("2026-11-28"); + expect(parseBingDate("2026-11-28T00:00:00Z")).toBe("2026-11-28"); + + const api = vi.fn(async (url) => { + const href = String(url); + if (href.includes("GetRankAndTrafficStats")) { + return Response.json({ + d: [ + { Date: "2026-11-15", Clicks: 10, Impressions: 100 }, + { Date: "2026-11-20", Clicks: 15, Impressions: 200 }, + { Date: "2026-11-22", Clicks: 20, Impressions: 300 }, + { Date: "2026-11-28", Clicks: 30, Impressions: 500 }, + ], + }); + } + if (href.includes("GetQueryStats")) { + return Response.json({ + d: [ + { Query: "ai gateway", Clicks: 12, Impressions: 120, AvgImpressionPosition: 4 }, + { Query: "ai gateway", Clicks: 8, Impressions: 80, AvgImpressionPosition: 6 }, + ], + }); + } + if (href.includes("GetPageStats")) { + return Response.json({ + d: [{ Query: "https://example.com/pricing", Clicks: 25, Impressions: 400, AvgImpressionPosition: 5 }], + }); + } + if (href.includes("GetCrawlStats")) { + return Response.json({ + d: [ + { + Date: "2026-11-28", + CrawledPages: 120, + CrawlErrors: 3, + InIndex: 95, + InLinks: 40, + BlockedByRobotsTxt: 1, + Code4xx: 2, + Code5xx: 1, + Code301: 4, + }, + ], + }); + } + if (href.includes("GetUrlSubmissionQuota")) { + return Response.json({ d: { DailyQuota: 100, MonthlyQuota: 200 } }); + } + return new Response("Not found", { status: 404 }); + }); + + const summary = await fetchBingWebmaster({ + apiKey: "bing-secret-key", + siteUrl: "example.com", + fetchImpl: api, + }); + + expect(summary.siteUrl).toBe("https://example.com/"); + expect(summary.cur7d).toMatchObject({ from: "2026-11-22", to: "2026-11-28", clicks: 50, impressions: 800 }); + expect(summary.prev7d).toMatchObject({ from: "2026-11-15", to: "2026-11-21", clicks: 25, impressions: 300 }); + expect(summary.queries[0]).toMatchObject({ key: "ai gateway", clicks: 20, impressions: 200, ctr: 0.1 }); + expect(summary.pages[0]).toMatchObject({ key: "https://example.com/pricing", clicks: 25 }); + expect(summary.latestCrawl).toMatchObject({ inIndex: 95, code4xx: 2, code5xx: 1 }); + expect(summary.quota).toEqual({ dailyQuota: 100, monthlyQuota: 200 }); + expect(JSON.stringify(summary)).not.toContain("bing-secret-key"); + }); + + it("redacts API keys on HTTP failures", async () => { + const api = vi.fn(async () => new Response("bing-secret-key denied", { status: 401 })); + let message = ""; + try { + await fetchBingWebmaster({ apiKey: "bing-secret-key", siteUrl: "https://example.com/", fetchImpl: api }); + } catch (error) { + message = error instanceof Error ? error.message : ""; + } + expect(message).toContain("HTTP 401"); + expect(message).not.toContain("bing-secret-key"); + }); + + it("returns prev7d as null when no prior 7-day rows exist instead of fabricating zero", async () => { + const api = vi.fn(async (url) => { + if (String(url).includes("GetRankAndTrafficStats")) { + return Response.json({ d: [{ Date: "2026-11-28", Clicks: 12, Impressions: 100 }] }); + } + return Response.json({ d: [] }); + }); + const summary = await fetchBingWebmaster({ apiKey: "k", siteUrl: "https://example.com/", fetchImpl: api }); + expect(summary.cur7d?.clicks).toBe(12); + expect(summary.prev7d).toBeNull(); + }); +}); diff --git a/packages/lib/src/traffic/cloudflare.d.mts b/packages/lib/src/traffic/cloudflare.d.mts new file mode 100644 index 0000000..8fe9f05 --- /dev/null +++ b/packages/lib/src/traffic/cloudflare.d.mts @@ -0,0 +1,57 @@ +export type CloudflareBotPurpose = "search" | "user" | "training"; + +export type CloudflareBotDefinition = { + alias: string; + name: string; + platform: string; + purpose: CloudflareBotPurpose; +}; + +export type CloudflareBotRow = { + name: string; + platform: string; + purpose: CloudflareBotPurpose; + current: number; + previous: number; + delta: number; + changePct: number | null; +}; + +export type CloudflareBotsSummary = { + schema: "beat-geo/cloudflare-bots@1"; + site: string; + zoneId: string; + zoneName: string; + days: number; + fetchedAt: string; + windowsUtc: { + current: [string, string]; + previous: [string, string]; + }; + totals: { + allCurrent: number; + allPrevious: number; + aiCurrent: number; + aiPrevious: number; + }; + bots: CloudflareBotRow[]; + warning: string; +}; + +export const CLOUDFLARE_BOTS: readonly CloudflareBotDefinition[]; + +export function resolveCloudflareZone(options: { + token: string; + zoneName?: string; + zoneId?: string; + fetchImpl?: typeof fetch; +}): Promise<{ id: string; name: string }>; + +export function fetchCloudflareBots(options: { + token: string; + zoneName?: string; + zoneId?: string; + days?: number; + now?: number; + fetchImpl?: typeof fetch; +}): Promise; diff --git a/packages/lib/src/traffic/cloudflare.mjs b/packages/lib/src/traffic/cloudflare.mjs new file mode 100644 index 0000000..bedbcfc --- /dev/null +++ b/packages/lib/src/traffic/cloudflare.mjs @@ -0,0 +1,186 @@ +// Read-only Cloudflare GraphQL crawler counts. UA substring matches are unverified declarations. + +const CLOUDFLARE_API = "https://api.cloudflare.com/client/v4"; + +export const CLOUDFLARE_BOTS = Object.freeze( + [ + ["OAI-SearchBot", "OpenAI", "search"], + ["ChatGPT-User", "OpenAI", "user"], + ["GPTBot", "OpenAI", "training"], + ["Claude-SearchBot", "Anthropic", "search"], + ["Claude-User", "Anthropic", "user"], + ["ClaudeBot", "Anthropic", "training"], + ["PerplexityBot", "Perplexity", "search"], + ["Perplexity-User", "Perplexity", "user"], + ["Googlebot", "Google", "search"], + ["bingbot", "Bing", "search"], + ["Applebot", "Apple", "search"], + ["YandexBot", "Yandex", "search"], + ["DuckAssistBot", "DuckDuckGo", "search"], + ["MistralAI-User", "Mistral", "user"], + ["Bytespider", "ByteDance", "training"], + ["CCBot", "CommonCrawl", "training"], + ["meta-externalagent", "Meta", "training"], + ["Amazonbot", "Amazon", "training"], + ].map(([name, platform, purpose], index) => + Object.freeze({ + alias: `b${index}`, + name, + platform, + purpose, + }), + ), +); + +function cleanZoneName(value) { + if (typeof value !== "string") throw new Error("Cloudflare zone name is required."); + const trimmed = value + .trim() + .toLowerCase() + .replace(/^https?:\/\//, "") + .replace(/\/.*$/, "") + .replace(/\.$/, ""); + if (!trimmed || !/^[a-z0-9.-]+\.[a-z]{2,}$/.test(trimmed)) + throw new Error("Enter a valid domain name for the Cloudflare zone."); + return trimmed; +} + +function cleanToken(token) { + if (typeof token !== "string" || !token.trim()) throw new Error("Cloudflare API token is required."); + return token.trim(); +} + +async function cfRequest(url, token, body, fetchImpl) { + let response; + try { + response = await fetchImpl(url, { + method: body ? "POST" : "GET", + redirect: "error", + headers: { + Authorization: `Bearer ${token}`, + ...(body ? { "Content-Type": "application/json" } : {}), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + signal: AbortSignal.timeout(30000), + }); + } catch { + throw new Error("Cloudflare request failed or timed out."); + } + if (!response.ok) { + throw new Error( + `Cloudflare API HTTP ${response.status}. Check token permissions (Zone Analytics:Read and Logs:Read).`, + ); + } + try { + return await response.json(); + } catch { + throw new Error("Invalid Cloudflare API response."); + } +} + +export async function resolveCloudflareZone({ token, zoneName, zoneId, fetchImpl = fetch }) { + const auth = cleanToken(token); + if (typeof zoneId === "string" && zoneId.trim()) { + const id = zoneId.trim(); + if (!/^[a-f0-9]{32}$/i.test(id)) throw new Error("Cloudflare zone ID must be a 32-character hex string."); + return { id, name: zoneName ? cleanZoneName(zoneName) : id }; + } + const name = cleanZoneName(zoneName); + const url = `${CLOUDFLARE_API}/zones?name=${encodeURIComponent(name)}`; + const data = await cfRequest(url, auth, null, fetchImpl); + if (data.success === false) throw new Error("Cloudflare zone lookup failed. Check token permissions."); + const zones = Array.isArray(data.result) ? data.result : []; + if (!zones.length || typeof zones[0]?.id !== "string") + throw new Error(`No Cloudflare zone found for ${name}. Check the domain or Zone:Read permission.`); + return { id: zones[0].id, name: typeof zones[0].name === "string" ? zones[0].name : name }; +} + +function buildBotQuery() { + const fields = CLOUDFLARE_BOTS.map( + (bot) => + `${bot.alias}: httpRequestsAdaptiveGroups(limit:1,filter:{datetime_geq:$a,datetime_lt:$b,userAgent_like:"%${bot.name}%"}){count}`, + ).join("\n"); + return `query($z:String!,$a:Time!,$b:Time!){viewer{zones(filter:{zoneTag:$z}){\n${fields}\n}}}`; +} + +async function queryWindow({ token, zoneId, from, to, fetchImpl }) { + const data = await cfRequest( + `${CLOUDFLARE_API}/graphql`, + token, + { query: buildBotQuery(), variables: { z: zoneId, a: from, b: to } }, + fetchImpl, + ); + if (Array.isArray(data.errors) && data.errors.length) { + throw new Error("Cloudflare GraphQL query failed. Confirm the token has Zone Analytics:Read and Logs:Read."); + } + const zone = data?.data?.viewer?.zones?.[0]; + if (!zone || typeof zone !== "object") throw new Error("Cloudflare returned no zone analytics for this window."); + const counts = {}; + for (const bot of CLOUDFLARE_BOTS) { + const groups = zone[bot.alias]; + const count = Array.isArray(groups) && groups.length ? Number(groups[0]?.count ?? 0) : 0; + counts[bot.name] = Number.isFinite(count) && count >= 0 ? count : 0; + } + return counts; +} + +export async function fetchCloudflareBots({ token, zoneName, zoneId, days = 7, now = Date.now(), fetchImpl = fetch }) { + const auth = cleanToken(token); + if (!Number.isInteger(days) || days < 1 || days > 30) + throw new Error("Cloudflare lookback window must be between 1 and 30 days."); + const zone = await resolveCloudflareZone({ token: auth, zoneName, zoneId, fetchImpl }); + const endMs = Math.floor(now / 1000) * 1000; + const dayMs = 86400 * 1000; + const curStart = new Date(endMs - days * dayMs).toISOString(); + const curEnd = new Date(endMs).toISOString(); + const prevStart = new Date(endMs - days * 2 * dayMs).toISOString(); + + const [currentCounts, previousCounts] = await Promise.all([ + queryWindow({ token: auth, zoneId: zone.id, from: curStart, to: curEnd, fetchImpl }), + queryWindow({ token: auth, zoneId: zone.id, from: prevStart, to: curStart, fetchImpl }), + ]); + + const bots = CLOUDFLARE_BOTS.map((bot) => { + const current = currentCounts[bot.name] ?? 0; + const previous = previousCounts[bot.name] ?? 0; + const delta = current - previous; + const changePct = previous > 0 ? delta / previous : null; + return { + name: bot.name, + platform: bot.platform, + purpose: bot.purpose, + current, + previous, + delta, + changePct, + }; + }).sort((a, b) => b.current - a.current || b.previous - a.previous); + + const totalCurrent = bots.reduce((sum, item) => sum + item.current, 0); + const totalPrevious = bots.reduce((sum, item) => sum + item.previous, 0); + const aiFilter = (item) => !["Google", "Bing", "Apple", "Yandex"].includes(item.platform); + const aiCurrent = bots.filter(aiFilter).reduce((sum, item) => sum + item.current, 0); + const aiPrevious = bots.filter(aiFilter).reduce((sum, item) => sum + item.previous, 0); + + return { + schema: "beat-geo/cloudflare-bots@1", + site: zone.name, + zoneId: zone.id, + zoneName: zone.name, + days, + fetchedAt: new Date(endMs).toISOString(), + windowsUtc: { + current: [curStart, curEnd], + previous: [prevStart, curStart], + }, + totals: { + allCurrent: totalCurrent, + allPrevious: totalPrevious, + aiCurrent, + aiPrevious, + }, + bots, + warning: + "Counts are UTC HTTP request totals matched by User-Agent substring via Cloudflare GraphQL; spoofed User-Agents are included and requests do not prove indexing or citation.", + }; +} diff --git a/packages/lib/src/traffic/cloudflare.test.ts b/packages/lib/src/traffic/cloudflare.test.ts new file mode 100644 index 0000000..16cb321 --- /dev/null +++ b/packages/lib/src/traffic/cloudflare.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from "vitest"; +import { CLOUDFLARE_BOTS, fetchCloudflareBots } from "./cloudflare.mjs"; + +function mockCloudflareZoneData(isCurrent: boolean) { + const counts: Record = { + "OAI-SearchBot": isCurrent ? 120 : 80, + Googlebot: isCurrent ? 300 : 250, + }; + return Object.fromEntries( + CLOUDFLARE_BOTS.map((bot) => [bot.alias, bot.name in counts ? [{ count: counts[bot.name] }] : []]), + ); +} + +describe("Cloudflare AI crawler observations", () => { + it("resolves zone and fetches current vs previous UTC bot counts without leaking the token", async () => { + const gqlCalls: Array> = []; + const api = vi.fn(async (url, init) => { + if (String(url).includes("/zones?name=")) { + return Response.json({ success: true, result: [{ id: "a".repeat(32), name: "example.com" }] }); + } + gqlCalls.push(JSON.parse(String(init?.body))); + return Response.json({ data: { viewer: { zones: [mockCloudflareZoneData(gqlCalls.length === 1)] } } }); + }); + + const summary = await fetchCloudflareBots({ + token: "cf-secret-token", + zoneName: "https://example.com/pricing", + days: 7, + now: Date.parse("2026-11-30T00:00:00Z"), + fetchImpl: api, + }); + + expect(gqlCalls).toHaveLength(2); + expect(summary.zoneName).toBe("example.com"); + expect(summary.windowsUtc.current).toEqual(["2026-11-23T00:00:00.000Z", "2026-11-30T00:00:00.000Z"]); + expect(summary.windowsUtc.previous).toEqual(["2026-11-16T00:00:00.000Z", "2026-11-23T00:00:00.000Z"]); + expect(summary.totals).toEqual({ allCurrent: 420, allPrevious: 330, aiCurrent: 120, aiPrevious: 80 }); + const oai = summary.bots.find((b) => b.name === "OAI-SearchBot"); + expect(oai).toMatchObject({ current: 120, previous: 80, delta: 40, changePct: 0.5 }); + expect(JSON.stringify(summary)).not.toContain("cf-secret-token"); + }); + + it("redacts API failures and rejects invalid lookback windows before network access", async () => { + const api = vi.fn(async () => new Response("cf-secret-token", { status: 403 })); + await expect( + fetchCloudflareBots({ token: "cf-secret-token", zoneName: "example.com", days: 0, fetchImpl: api }), + ).rejects.toThrow("1 and 30"); + expect(api).not.toHaveBeenCalled(); + + await expect( + fetchCloudflareBots({ token: "cf-secret-token", zoneName: "example.com", days: 7, fetchImpl: api }), + ).rejects.toThrow("HTTP 403"); + }); +}); diff --git a/packages/lib/src/traffic/gsc-analysis.test.ts b/packages/lib/src/traffic/gsc-analysis.test.ts index a36ee85..3f4eee4 100644 --- a/packages/lib/src/traffic/gsc-analysis.test.ts +++ b/packages/lib/src/traffic/gsc-analysis.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { fetchGscAnalysis } from "./gsc.mjs"; +import { compareGscRows, fetchGscAnalysis, inspectGscUrl } from "./gsc.mjs"; describe("Search Console page/query evidence", () => { it("fetches actual joint rows and equal preceding periods, retaining truncation and missing days", async () => { @@ -80,3 +80,75 @@ it("rejects corrupt metrics and strips unrequested provider fields", async () => await expect(fetchGscAnalysis({ ...args, fetchImpl: make(true) })).rejects.toThrow("metrics"); expect(JSON.stringify(await fetchGscAnalysis({ ...args, fetchImpl: make(false) }))).not.toContain("private"); }); + +describe("Search Console country comparison and URL inspection", () => { + it("fetches countries in analysis and compares periods without inventing zero for missing keys", async () => { + const api = vi.fn(async (_url, init) => { + if (!init?.body) + return Response.json({ siteEntry: [{ siteUrl: "https://example.com/", permissionLevel: "siteOwner" }] }); + const body = JSON.parse(String(init.body)); + if (body.dimensions?.join() === "country") { + return Response.json({ + rows: + body.startDate === "2026-10-01" + ? [{ keys: ["usa"], clicks: 50, impressions: 1000, ctr: 0.05, position: 8.2 }] + : [{ keys: ["usa"], clicks: 20, impressions: 500, ctr: 0.04, position: 12.0 }], + }); + } + return Response.json({ rows: [] }); + }); + + const result = await fetchGscAnalysis({ + token: "secret", + siteUrl: "https://example.com/", + startDate: "2026-10-01", + endDate: "2026-10-28", + maxRows: 5, + fetchImpl: api, + }); + + expect(result.analysis.current.countries?.rows[0]).toMatchObject({ keys: ["usa"], clicks: 50 }); + const compared = compareGscRows(result.analysis.current.countries?.rows ?? [], [ + ...(result.analysis.previous.countries?.rows ?? []), + { keys: ["jpn"], clicks: 10, impressions: 100, ctr: 0.1, position: 9 }, + ]); + expect(compared.find((r) => r.key === "usa")).toMatchObject({ + clicksDelta: 30, + impressionsDelta: 500, + positionDelta: -3.8, + }); + expect(compared.find((r) => r.key === "jpn")).toMatchObject({ current: null, clicksDelta: null }); + }); + + it("inspects a single URL via URL Inspection API without leaking credentials", async () => { + const api = vi.fn(async () => + Response.json({ + inspectionResult: { + indexStatusResult: { + verdict: "PASS", + coverageState: "Submitted and indexed", + robotsTxtState: "ALLOWED", + indexingState: "INDEXING_ALLOWED", + pageFetchState: "SUCCESSFUL", + lastCrawlTime: "2026-11-29T06:00:00Z", + googleCanonical: "https://example.com/", + userCanonical: "https://example.com/", + crawledAs: "MOBILE", + }, + }, + }), + ); + const inspected = await inspectGscUrl({ + token: "secret-gsc-token", + siteUrl: "sc-domain:example.com", + inspectionUrl: "https://example.com/", + fetchImpl: api, + }); + expect(inspected).toMatchObject({ + verdict: "PASS", + coverageState: "Submitted and indexed", + robotsTxtState: "ALLOWED", + }); + expect(JSON.stringify(inspected)).not.toContain("secret-gsc-token"); + }); +}); diff --git a/packages/lib/src/traffic/gsc.d.mts b/packages/lib/src/traffic/gsc.d.mts index 0ffa3e8..1e8a367 100644 --- a/packages/lib/src/traffic/gsc.d.mts +++ b/packages/lib/src/traffic/gsc.d.mts @@ -36,6 +36,7 @@ export type GscWindow = Omit & { daily: GscDataset; queryPages: GscDataset; dailyPages: GscDataset; + countries?: GscDataset; }; export type GscAnalysis = { schema: "beat-geo/gsc-analysis@1"; @@ -51,3 +52,37 @@ export function fetchGscAnalysis(options: { maxRows?: number; fetchImpl?: typeof fetch; }): Promise; + +export type GscUrlInspection = { + schema: "beat-geo/gsc-inspection@1"; + url: string; + siteUrl: string; + inspectedAt: string; + verdict: string; + coverageState: string; + robotsTxtState: string; + indexingState: string; + pageFetchState: string; + lastCrawlTime: string | null; + googleCanonical: string | null; + userCanonical: string | null; + crawledAs: string | null; +}; + +export function inspectGscUrl(options: { + token: string; + siteUrl: string; + inspectionUrl: string; + fetchImpl?: typeof fetch; +}): Promise; + +export type GscRowComparison = { + key: string; + current: GscRow | null; + previous: GscRow | null; + clicksDelta: number | null; + impressionsDelta: number | null; + positionDelta: number | null; +}; + +export function compareGscRows(currentRows: GscRow[], previousRows: GscRow[]): GscRowComparison[]; diff --git a/packages/lib/src/traffic/gsc.mjs b/packages/lib/src/traffic/gsc.mjs index abbea89..0094d65 100644 --- a/packages/lib/src/traffic/gsc.mjs +++ b/packages/lib/src/traffic/gsc.mjs @@ -152,12 +152,13 @@ export async function fetchGscAnalysis({ token, siteUrl, startDate, endDate, max return { dimensions, rows, returnedRows: rows.length, limitReached: !exhausted, providerLimited: true }; } async function enrich(period) { - const [daily, queryPages, dailyPages] = await Promise.all([ + const [daily, queryPages, dailyPages, countries] = await Promise.all([ dataset(period, ["date"]), dataset(period, ["query", "page"]), dataset(period, ["date", "page"]), + dataset(period, ["country"]), ]); - return { ...period, daily, queryPages, dailyPages }; + return { ...period, daily, queryPages, dailyPages, countries }; } const [head, base] = await Promise.all([enrich(current), enrich(previous)]); return { @@ -166,6 +167,55 @@ export async function fetchGscAnalysis({ token, siteUrl, startDate, endDate, max }; } +const URL_INSPECTION_API = "https://searchconsole.googleapis.com/v1/urlInspection/index:inspect"; + +/** Read-only Google URL Inspection for a single URL within an authorized Search Console property. */ +export async function inspectGscUrl({ token, siteUrl, inspectionUrl, fetchImpl = fetch }) { + if (typeof inspectionUrl !== "string" || !/^https?:\/\//i.test(inspectionUrl.trim())) + throw new Error("Enter a valid HTTP or HTTPS URL to inspect."); + const data = await request(URL_INSPECTION_API, token, { inspectionUrl: inspectionUrl.trim(), siteUrl }, fetchImpl); + const result = data?.inspectionResult ?? {}; + const indexStatus = result?.indexStatusResult ?? {}; + return { + schema: "beat-geo/gsc-inspection@1", + url: inspectionUrl.trim(), + siteUrl, + inspectedAt: new Date().toISOString(), + verdict: typeof indexStatus.verdict === "string" ? indexStatus.verdict : "VERDICT_UNSPECIFIED", + coverageState: typeof indexStatus.coverageState === "string" ? indexStatus.coverageState : "", + robotsTxtState: typeof indexStatus.robotsTxtState === "string" ? indexStatus.robotsTxtState : "", + indexingState: typeof indexStatus.indexingState === "string" ? indexStatus.indexingState : "", + pageFetchState: typeof indexStatus.pageFetchState === "string" ? indexStatus.pageFetchState : "", + lastCrawlTime: typeof indexStatus.lastCrawlTime === "string" ? indexStatus.lastCrawlTime : null, + googleCanonical: typeof indexStatus.googleCanonical === "string" ? indexStatus.googleCanonical : null, + userCanonical: typeof indexStatus.userCanonical === "string" ? indexStatus.userCanonical : null, + crawledAs: typeof indexStatus.crawledAs === "string" ? indexStatus.crawledAs : null, + }; +} + +/** Compare single-key GSC rows across equal periods; missing rows stay null rather than inferred zero. */ +export function compareGscRows(currentRows, previousRows) { + const currentMap = new Map((currentRows ?? []).map((row) => [row.keys?.[0] ?? "", row])); + const previousMap = new Map((previousRows ?? []).map((row) => [row.keys?.[0] ?? "", row])); + const keys = new Set([...currentMap.keys(), ...previousMap.keys()]); + keys.delete(""); + return [...keys].map((key) => { + const cur = currentMap.get(key) ?? null; + const prev = previousMap.get(key) ?? null; + const clicksDelta = cur && prev ? cur.clicks - prev.clicks : null; + const impressionsDelta = cur && prev ? cur.impressions - prev.impressions : null; + const positionDelta = cur && prev ? Number((cur.position - prev.position).toFixed(1)) : null; + return { + key, + current: cur, + previous: prev, + clicksDelta, + impressionsDelta, + positionDelta, + }; + }); +} + function cleanRows(rows, dimensions) { if (!Array.isArray(rows)) throw new Error("Invalid Search Console rows."); return rows.map((row) => { From 6ef45e76d90400cdf8183cba5510f0e4ffd8ef95 Mon Sep 17 00:00:00 2001 From: KKKK Date: Mon, 30 Nov 2026 16:11:39 +0800 Subject: [PATCH 5/5] Improve navigation, overview pulse, data source setup and search UI --- .changeset/seo-sources-and-ux-polish.md | 6 + apps/web/.storybook/main.ts | 3 + apps/web/src/components/app-sidebar.tsx | 100 ++++++ apps/web/src/components/bing-panel.tsx | 289 +++++++++++++++ apps/web/src/components/brand-setup.tsx | 123 +++++-- apps/web/src/components/cloudflare-panel.tsx | 225 ++++++++++++ apps/web/src/components/gsc-panel.tsx | 333 +++++++++++++----- apps/web/src/components/overview-pulse.tsx | 271 ++++++++++++++ apps/web/src/components/page-header.tsx | 28 +- .../web/src/components/search-performance.tsx | 207 ++++++++--- apps/web/src/components/site-audit.tsx | 208 +++++++++-- apps/web/src/components/status-badges.tsx | 71 ++++ apps/web/src/components/traffic-panel.tsx | 5 +- apps/web/src/components/traffic-sources.tsx | 259 +++++++++++--- apps/web/src/lib/i18n/zh.json | 126 ++++++- .../app/org/$org/brand/$brand/index.tsx | 37 +- .../org/$org/brand/$brand/search-console.tsx | 14 +- .../org/$org/brand/$brand/settings/brand.tsx | 44 ++- .../web/src/stories/_mocks/server-workflow.ts | 36 ++ apps/web/src/stories/_mocks/tanstack-start.ts | 6 + apps/web/src/stories/gsc-panel.stories.tsx | 5 + apps/web/src/stories/traffic.stories.tsx | 10 +- 22 files changed, 2122 insertions(+), 284 deletions(-) create mode 100644 .changeset/seo-sources-and-ux-polish.md create mode 100644 apps/web/src/components/bing-panel.tsx create mode 100644 apps/web/src/components/cloudflare-panel.tsx create mode 100644 apps/web/src/components/overview-pulse.tsx create mode 100644 apps/web/src/components/status-badges.tsx diff --git a/.changeset/seo-sources-and-ux-polish.md b/.changeset/seo-sources-and-ux-polish.md new file mode 100644 index 0000000..ee33b5c --- /dev/null +++ b/.changeset/seo-sources-and-ux-polish.md @@ -0,0 +1,6 @@ +--- +"@workspace/web": patch +"@workspace/lib": patch +--- + +Add Cloudflare AI crawler and Bing Webmaster data sources, upgrade GSC period comparisons and AEO site audits, and improve sidebar, overview pulse, and data source setup UX. diff --git a/apps/web/.storybook/main.ts b/apps/web/.storybook/main.ts index b129b97..588260b 100644 --- a/apps/web/.storybook/main.ts +++ b/apps/web/.storybook/main.ts @@ -78,6 +78,9 @@ const config: StorybookConfig = { "workspace-fn", "evidence-summary", "site-audit-fn", + "connections", + "local-navigation", + "traffic-fn", ].map((module) => ({ find: new RegExp(`^@/server/${module}(\\.ts)?$`), replacement: path.resolve(mocksDir, "server-workflow.ts"), diff --git a/apps/web/src/components/app-sidebar.tsx b/apps/web/src/components/app-sidebar.tsx index 01c03b0..2e37484 100644 --- a/apps/web/src/components/app-sidebar.tsx +++ b/apps/web/src/components/app-sidebar.tsx @@ -13,9 +13,11 @@ import { IconPlugConnected, IconSchool, IconSearch, + IconShieldCheck, IconTarget, IconWorld, } from "@tabler/icons-react"; +import { useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { brandLinkParams, orgLinkParams } from "@workspace/lib/app-urls"; import type { BrandWithPrompts } from "@workspace/lib/db/schema"; @@ -30,14 +32,18 @@ import { SidebarMenuItem, useSidebar, } from "@workspace/ui/components/sidebar"; +import { FormSelect } from "@/components/form-select"; import { Logo } from "@/components/logo"; import { NavAppInfo } from "@/components/nav-app-info"; import { type NavGroup, type NavItem, NavMain } from "@/components/nav-main"; import { useLooseRouteContext } from "@/hooks/use-route-context"; +import { useT } from "@/lib/i18n"; import { INSIGHT_PAGES } from "@/lib/insight-navigation"; import type { OrganizationSummary } from "@/lib/organizations/types"; import { SEO_PAGES } from "@/lib/seo-navigation"; import type { ShellScope } from "@/lib/shell-scope"; +import { getConnectionsFn } from "@/server/connections"; +import { selectLocalWebsiteFn } from "@/server/local-navigation"; export type AppSidebarProps = ShellScope; @@ -63,6 +69,11 @@ function brandGroups(organization: OrganizationSummary, brand: SidebarBrand, seo link: { to: "/app/org/$org/brand/$brand/opportunities", params, hash: "search" }, icon: IconSearch, }, + { + title: "Website check", + link: { to: "/app/org/$org/brand/$brand/opportunities", params, hash: "website" }, + icon: IconShieldCheck, + }, ]; if (seoEnabled) seo.push( @@ -202,13 +213,102 @@ export function AppSidebar({ organization, brand }: AppSidebarProps) { + {organization && organization.brands.length > 0 && ( + + )} + {Boolean(context.canManageConnections) && } ); } + +function SidebarWebsiteSwitcher({ + organization, + current, +}: { + organization: OrganizationSummary; + current: SidebarBrand | undefined; +}) { + const t = useT(); + const currentKey = current ? current.slug || current.id : ""; + return ( +
+ { + if (value === currentKey) return; + const target = organization.brands.find((item) => (item.slug || item.id) === value); + if (!target) return; + try { + await selectLocalWebsiteFn({ data: { brandId: target.id } }); + window.location.assign("/app"); + } catch { + // Fall back silently if selection fails. + } + }} + options={organization.brands.map((item) => ({ + value: item.slug || item.id, + label: item.name, + }))} + /> +
+ ); +} + +function SidebarRuntimeStrip({ + organization, + brand, +}: { + organization: OrganizationSummary | undefined; + brand: SidebarBrand | undefined; +}) { + const t = useT(); + const { setOpenMobile } = useSidebar(); + const status = useQuery({ + queryKey: ["connections"], + queryFn: () => getConnectionsFn(), + refetchInterval: 30000, + retry: false, + }); + if (!status.data) return null; + const workerOk = status.data.runtime.worker === "ready"; + const browserOnline = Boolean(status.data.browser.online); + const chromeReady = Boolean(browserOnline && status.data.browser.selectedProfileId); + const chromeDot = chromeReady ? "bg-emerald-400" : browserOnline ? "bg-amber-400" : "bg-muted-foreground/50"; + const chromeLabel = chromeReady ? "Chrome ready" : browserOnline ? "Chrome setup" : "Chrome"; + const settingsLink = + organization && brand + ? { to: "/app/org/$org/brand/$brand/settings/brand" as const, params: brandLinkParams(organization, brand) } + : { to: "/setup" as const }; + return ( +
+ setOpenMobile(false)} + className="inline-flex items-center gap-1.5 hover:text-foreground" + > + + {t(workerOk ? "Worker ready" : "Worker offline")} + + setOpenMobile(false)} + className="inline-flex items-center gap-1.5 hover:text-foreground" + > + + {t(chromeLabel)} + +
+ ); +} diff --git a/apps/web/src/components/bing-panel.tsx b/apps/web/src/components/bing-panel.tsx new file mode 100644 index 0000000..d7161ba --- /dev/null +++ b/apps/web/src/components/bing-panel.tsx @@ -0,0 +1,289 @@ +import type { BingSummary } from "@workspace/lib/traffic/bing"; +import { Button } from "@workspace/ui/components/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@workspace/ui/components/card"; +import { Input } from "@workspace/ui/components/input"; +import { Label } from "@workspace/ui/components/label"; +import { useState } from "react"; +import { DeltaBadge, StatusPill } from "@/components/status-badges"; +import { TrendChart } from "@/components/trend-chart"; +import { useLocale, useT } from "@/lib/i18n"; +import type { TrafficData } from "@/server/traffic-core"; + +type Props = { + settingsOnly?: boolean; + data: TrafficData; + busy: boolean; + onConnect: (apiKey: string, siteUrl?: string) => void; + onSync: () => void; + onDisconnect: () => void; +}; + +function deltaText(cur: number, prev: number) { + const diff = cur - prev; + const sign = diff > 0 ? "+" : ""; + if (prev <= 0) return `${sign}${diff}`; + return `${sign}${diff} (${sign}${((diff / prev) * 100).toFixed(1)}%)`; +} + +export function BingPanel({ settingsOnly = false, data, busy, onConnect, onSync, onDisconnect }: Props) { + const t = useT(); + const summary = data.bing?.snapshot as BingSummary | null; + const connected = Boolean(data.bing?.connected); + const defaultSiteUrl = data.bing?.config?.siteUrl || `https://${data.site}/`; + + return ( + + + {t("Bing Webmaster")} +

+ {t("Read-only Bing search clicks, impressions, queries and crawl stats (used alongside Google for GEO).")} +

+
+ + {settingsOnly ? ( + + ) : ( + + )} + +
+ ); +} + +function BingSettingsForm({ + connected, + defaultSiteUrl, + busy, + onConnect, + onSync, + onDisconnect, +}: { + connected: boolean; + defaultSiteUrl: string; + busy: boolean; + onConnect: (apiKey: string, siteUrl?: string) => void; + onSync: () => void; + onDisconnect: () => void; +}) { + const t = useT(); + const [apiKey, setApiKey] = useState(""); + const [siteUrl, setSiteUrl] = useState(defaultSiteUrl); + return ( +
+
+ + setApiKey(e.target.value)} + /> +

+ {t("BeatGEO calls read-only Get* endpoints only and never submits URLs.")} +

+
+
+ + setSiteUrl(e.target.value)} + /> +
+
+ + {connected && ( + <> + + + + )} +
+
+ ); +} + +function BingOverview({ + connected, + siteUrl, + busy, + summary, + onSync, +}: { + connected: boolean; + siteUrl: string; + busy: boolean; + summary: BingSummary | null; + onSync: () => void; +}) { + const t = useT(); + if (!connected) { + return ( +

+ {t("Connect Bing Webmaster API in Brand settings to compare Bing traffic and crawl health.")} +

+ ); + } + return ( +
+
+ {siteUrl} + +
+ {summary && } +
+ ); +} + +function BingSummaryView({ summary }: { summary: BingSummary }) { + const t = useT(); + const { locale } = useLocale(); + const [view, setView] = useState<"queries" | "pages">("queries"); + const [filter, setFilter] = useState(""); + const num = (v: number) => new Intl.NumberFormat(locale).format(v); + const sourceRows = view === "queries" ? summary.queries : summary.pages; + const rows = sourceRows.filter((row) => row.key.toLowerCase().includes(filter.toLowerCase())); + const dailySeries = summary.days.map((day) => ({ date: day.date, value: day.clicks })); + + return ( +
+

+ {summary.cur7d ? `${summary.cur7d.from} – ${summary.cur7d.to}` : t("No recent traffic rows")} ·{" "} + {t("Last successful data fetch")}: {new Date(summary.fetchedAt).toLocaleString(locale)} +

+ {summary.cur7d && } + {dailySeries.length > 1 && ( +
+

{t("Daily Bing clicks")}

+
+ +
+
+ )} +
+ + + setFilter(e.target.value)} + /> +
+ {rows.length > 0 ? ( +
+ + + + {[ + view === "queries" ? t("Search query") : t("Page"), + t("Clicks"), + t("Impressions"), + t("CTR"), + t("Average position"), + ].map((h) => ( + + ))} + + + + {rows.slice(0, 50).map((row) => ( + + + + + + + + ))} + +
+ {h} +
{row.key}{num(row.clicks)}{num(row.impressions)}{(row.ctr * 100).toFixed(2)}%{row.position.toFixed(1)}
+
+ ) : ( +

{t("No Bing rows match this filter.")}

+ )} +

+ {t( + "Bing Webmaster API typically lags by ~1 day. Full 4xx/5xx URL lists are not exposed via API and require exporting from Bing Webmaster Tools.", + )} +

+
+ ); +} + +function BingMetricsGrid({ summary, num }: { summary: BingSummary; num: (v: number) => string }) { + const t = useT(); + const cur = summary.cur7d!; + const prev = summary.prev7d; + const crawl = summary.latestCrawl; + const hasErrors = Boolean(crawl && crawl.code4xx + crawl.code5xx > 0); + return ( +
+
+
{t("Bing clicks (7d)")}
+
+ {num(cur.clicks)} + {prev && } +
+
+
+
{t("Bing impressions (7d)")}
+
+ {num(cur.impressions)} + {prev && ( + + )} +
+
+
+
{t("Pages in Bing index")}
+
{crawl ? num(crawl.inIndex) : "—"}
+
+
+
{t("Crawl errors (4xx / 5xx)")}
+
+ + {crawl ? `${crawl.code4xx} / ${crawl.code5xx}` : "—"} + + {crawl && } +
+
+
+ ); +} diff --git a/apps/web/src/components/brand-setup.tsx b/apps/web/src/components/brand-setup.tsx index 6e01ea7..0467988 100644 --- a/apps/web/src/components/brand-setup.tsx +++ b/apps/web/src/components/brand-setup.tsx @@ -1,3 +1,4 @@ +import { IconCheck } from "@tabler/icons-react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; import { Button } from "@workspace/ui/components/button"; @@ -17,14 +18,20 @@ import { export function BrandSetup({ website, + sources, actions, monitoringActions, connectedWebsite = false, + connectedSourcesCount = 0, + defaultStep = "website", }: { website: ReactNode; + sources?: ReactNode; actions?: ReactNode; monitoringActions?: ReactNode; connectedWebsite?: boolean; + connectedSourcesCount?: number; + defaultStep?: string; }) { const t = useT(); const client = useQueryClient(); @@ -72,8 +79,8 @@ export function BrandSetup({ const hash = usePublicHash(); const navigate = useNavigate(); - const steps = setupSteps(connectedWebsite, status.data); - const active = steps.some((step) => step.id === hash) ? hash : "website"; + const steps = setupSteps(connectedWebsite, Boolean(sources), connectedSourcesCount, status.data); + const active = resolveActiveStep(steps, hash, defaultStep); return (
@@ -85,24 +92,12 @@ export function BrandSetup({
{actions} -
- +
+ void navigate({ hash: id, replace: true, resetScroll: false })} + />
{status.error && (

@@ -112,6 +107,11 @@ export function BrandSetup({

+ {sources && ( + + )} @@ -455,7 +464,10 @@ function useEarlySignalCaption(loading: boolean, totalRuns: number): string | un /** Website per brand or competitor name, so the ranking can show each one's icon. */ function rankingDomainsFor(brand: BrandWithPrompts | undefined): Record { if (!brand) return {}; - return Object.fromEntries([[brand.name, brand.website], ...brand.competitors.map((c) => [c.name, c.domains[0]])]); + return Object.fromEntries([ + [brand.name, brand.website], + ...(brand.competitors ?? []).map((c) => [c.name, c.domains[0]]), + ]); } function BaselineNotice({ totalRuns }: { totalRuns: number }) { @@ -473,6 +485,16 @@ function BaselineNotice({ totalRuns }: { totalRuns: number }) { ); } +function OnboardingShell({ brandId, children }: { brandId: string | undefined; children: ReactNode }) { + return ( +
+ + {brandId && } + {children} +
+ ); +} + function DashboardPage() { const t = useT(); const brandId = useBrandId(); @@ -501,27 +523,26 @@ function DashboardPage() { if (!isLoadingBrand && !brand?.onboarded) { return ( -
- + -
+ ); } // No runs yet: the dashboard has nothing to plot, so point at what to do next. if (!loadingVisibility && totalRuns === 0) { return ( -
- + 0} /> -
+ ); } return (
-
+
+ {brand?.id && } {earlySignal && }

{t( diff --git a/apps/web/src/routes/_authed/app/org/$org/brand/$brand/search-console.tsx b/apps/web/src/routes/_authed/app/org/$org/brand/$brand/search-console.tsx index 156f37a..03a6f99 100644 --- a/apps/web/src/routes/_authed/app/org/$org/brand/$brand/search-console.tsx +++ b/apps/web/src/routes/_authed/app/org/$org/brand/$brand/search-console.tsx @@ -1,6 +1,7 @@ -import { createFileRoute } from "@tanstack/react-router"; +import { createFileRoute, Link } from "@tanstack/react-router"; import { PageHeader } from "@/components/page-header"; import { TrafficSources } from "@/components/traffic-sources"; +import { useBrandParams } from "@/hooks/use-route-params"; import { useT } from "@/lib/i18n"; import { pageHead } from "@/lib/route-head"; export const Route = createFileRoute("/_authed/app/org/$org/brand/$brand/search-console")({ @@ -13,12 +14,23 @@ export const Route = createFileRoute("/_authed/app/org/$org/brand/$brand/search- }); function SearchConsolePage() { const t = useT(); + const params = useBrandParams(); return ( + {t("Manage data sources")} + + } > diff --git a/apps/web/src/routes/_authed/app/org/$org/brand/$brand/settings/brand.tsx b/apps/web/src/routes/_authed/app/org/$org/brand/$brand/settings/brand.tsx index c4172d3..12a4fa8 100644 --- a/apps/web/src/routes/_authed/app/org/$org/brand/$brand/settings/brand.tsx +++ b/apps/web/src/routes/_authed/app/org/$org/brand/$brand/settings/brand.tsx @@ -1,5 +1,5 @@ import { IconInfoCircle } from "@tabler/icons-react"; -import { useQueryClient } from "@tanstack/react-query"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import { createFileRoute, Link, useNavigate } from "@tanstack/react-router"; import { brandSegment, brandSlugPrefix, normalizeSlug } from "@workspace/lib/app-urls"; import { cleanAndValidateDomain } from "@workspace/lib/citations/domain-categories"; @@ -13,6 +13,7 @@ import { FormSelect } from "@/components/form-select"; import { SlugField } from "@/components/slug-field"; import { TagsInput } from "@/components/tags-input"; import { TrafficSources } from "@/components/traffic-sources"; +import { useBrandId } from "@/hooks/use-brand-id"; import { useBrand } from "@/hooks/use-brands"; import { citationKeys } from "@/hooks/use-citations"; import { dashboardKeys } from "@/hooks/use-dashboard-summary"; @@ -23,6 +24,7 @@ import { pageHead } from "@/lib/route-head"; import { useWriteErrorMessage } from "@/lib/write-errors"; import { updateBrandFn } from "@/server/brands"; import { selectLocalWebsiteFn } from "@/server/local-navigation"; +import { getTrafficFn } from "@/server/traffic-fn"; export const Route = createFileRoute("/_authed/app/org/$org/brand/$brand/settings/brand")({ staticData: { crumb: "Brand" }, @@ -36,11 +38,25 @@ export const Route = createFileRoute("/_authed/app/org/$org/brand/$brand/setting function BrandSettingsPage() { const t = useT(); const organization = useOrganization(); + const brandId = useBrandId(); const params = useBrandParams(); const [switchError, setSwitchError] = useState(""); const { google } = Route.useSearch(); + const traffic = useQuery({ + queryKey: ["traffic", brandId], + queryFn: () => getTrafficFn({ data: { brandId } }), + retry: false, + }); + const connectedSourcesCount = [ + traffic.data?.gsc?.connected, + traffic.data?.ga?.connected, + traffic.data?.bing?.connected, + traffic.data?.cloudflare?.connected, + ].filter(Boolean).length; return ( { const brand = organization.brands.find((brand) => (brand.slug || brand.id) === value); @@ -100,15 +116,19 @@ function BrandSettingsPage() {

-
-

Google Search Console · Analytics

-

- {t("Optional. Connect Google to add your site's search performance and traffic data.")} -

- -
} + sources={ +
+

{t("Search & traffic data sources")}

+

+ {t( + "Optional. Connect Google Search Console, GA4, Bing Webmaster and Cloudflare crawlers for this website.", + )} +

+ +
+ } /> ); } @@ -311,7 +331,11 @@ function BrandDetailsForm() {
{error &&
{error}
} - {success &&
{success}
} + {success && ( +
+ {t(success)} +
+ )}