Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Filter Search Performance by page and query (EVE-52) (#662)
Carter Smithc769d0af8fe2
diff --git a/.agents/PAPERCUTS.md b/.agents/PAPERCUTS.mdindex 98e6fc49..294c000b 100644--- a/.agents/PAPERCUTS.md+++ b/.agents/PAPERCUTS.md@@ -10,6 +10,7 @@ data, or sensitive paths.## Open+- [ ] `2026-09-22T02:21:38Z` — `codex` — The documented portless `.localhost` development URL produces a Google OAuth `invalid_request` because Google rejects that callback hostname. Document registering `http://localhost:<assigned-port>/api/gsc/oauth/callback` and starting the connection from that direct origin while the server remains managed by portless.- [ ] `2026-09-18T10:06:56Z` — `codex` — Website browser tests flood Vite output with "Assets in public directory cannot be imported from JavaScript" for MDX library images. Adjust the MDX image handling to retain public image URLs instead of generating imports, so useful test failures remain visible.- [ ] `2026-09-03T00:00:00Z` — `claude` — `pnpm ci:check` does not run `pnpm build`, so a route file that pulls `cloudflare:workers` into the client bundle passes every check and still breaks the build (hit on the dynamic-reports branch). Add a build step to `ci:check`, or document that `pnpm build` must be run separately before opening a PR.- [ ] `2026-09-11T00:13:05Z` — `codex` — The web-content review skill points to the removed `src/server/features/onboarding/openseo-fact-sheet.md`; the reference now lives at `src/server/features/sam/openseo-fact-sheet.md`. Update the skill's pointer so content reviews reach the current fact sheet.diff --git a/src/client/features/search-performance/SearchPerformancePage.tsx b/src/client/features/search-performance/SearchPerformancePage.tsxindex 182bd6b9..5a79f8b5 100644--- a/src/client/features/search-performance/SearchPerformancePage.tsx+++ b/src/client/features/search-performance/SearchPerformancePage.tsx@@ -2,16 +2,23 @@ import { useEffect, useState } from "react";import { Link } from "@tanstack/react-router";import {keepPreviousData,- queryOptions,useQuery,useQueryClient,} from "@tanstack/react-query";-import { Download, Loader2, Sheet } from "lucide-react";+import { Download, Loader2, Sheet, SlidersHorizontal } from "lucide-react";import { toast } from "sonner";import { TableExportMenu } from "@/client/components/table/TableBulkActionBar";import { TablePagination } from "@/client/components/table/TablePagination";import { SearchConsoleConnectionCard } from "@/client/features/gsc/SearchConsoleConnectionCard";import { SearchPerformanceLoadingState } from "@/client/features/search-performance/SearchPerformanceLoadingState";+import {+ tableQueryOptions,+ type FilterInput,+} from "@/client/features/search-performance/searchPerformanceQueries";+import {+ SearchPerformanceTextFilters,+ type TextFilters,+} from "@/client/features/search-performance/SearchPerformanceTextFilters";import {DimensionTable,exportDimensionRows,@@ -26,7 +33,6 @@ import { getStandardErrorMessage } from "@/client/lib/error-messages";import {exportSearchPerformanceTable,getSearchPerformanceReport,- getSearchPerformanceTable,} from "@/serverFunctions/searchPerformance";import {GSC_DEVICES,@@ -73,12 +79,6 @@ function tabDimension(tab: Tab): SearchPerformanceTableDimension {return tab === "pages" ? "page" : "query";}-type FilterInput = {- dateRange: SearchPerformanceDateRange;- device?: SearchPerformanceDevice;- country?: string;-};-// The server filter payload: drop device/country when set to the "ALL" sentinel.function buildFilterInput(range: SearchPerformanceDateRange,@@ -92,31 +92,6 @@ function buildFilterInput(};}-// Single source for the paginated table query, shared by the live query and the-// warm-on-connect prefetch so their key + fn can never drift apart.-function tableQueryOptions(- projectId: string,- dimension: SearchPerformanceTableDimension,- page: number,- pageSize: number,- filterInput: FilterInput,-) {- return queryOptions({- queryKey: [- "searchPerformanceTable",- projectId,- dimension,- page,- pageSize,- filterInput,- ],- queryFn: () =>- getSearchPerformanceTable({- data: { projectId, dimension, page, pageSize, ...filterInput },- }),- });-}-export function SearchPerformancePage({ projectId }: { projectId: string }) {const queryClient = useQueryClient();const [range, setRange] =@@ -125,21 +100,27 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {ALL,);const [country, setCountry] = useState<string>(ALL);+ const [textFilters, setTextFilters] = useState<TextFilters>({});+ const [showFilters, setShowFilters] = useState(false);+ const activeFilterCount =+ Number(Boolean(textFilters.pageFilter)) ++ Number(Boolean(textFilters.queryFilter)) ++ Number(country !== ALL) ++ Number(device !== ALL) ++ Number(range !== "last_28_days");const [tab, setTab] = useState<Tab>("striking");const [page, setPage] = useState(1);const [pageSize, setPageSize] = useState<number>(SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE,);- // Any change to the query set (tab, filters, page size) restarts at page 1.- useEffect(() => {- setPage(1);- }, [tab, range, device, country, pageSize]);-- const filterInput = buildFilterInput(range, device, country);+ const filterInput = {+ ...buildFilterInput(range, device, country),+ ...textFilters,+ };const reportQuery = useQuery({- queryKey: ["searchPerformance", projectId, range, device, country],+ queryKey: ["searchPerformance", projectId, filterInput],queryFn: () =>getSearchPerformanceReport({ data: { projectId, ...filterInput } }),placeholderData: keepPreviousData,@@ -151,7 +132,6 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {const tableQuery = useQuery({...tableQueryOptions(projectId, dimension, page, pageSize, filterInput),enabled: report?.connected === true && isTableTab,- placeholderData: keepPreviousData,});const tableData = tableQuery.data;const tableRows = tableData?.connected ? tableData.rows : [];@@ -167,13 +147,21 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {"query",1,SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE,- buildFilterInput(range, device, country),+ { ...buildFilterInput(range, device, country), ...textFilters },),);- }, [report?.connected, projectId, range, device, country, queryClient]);+ }, [+ report?.connected,+ projectId,+ range,+ device,+ country,+ textFilters,+ queryClient,+ ]);const handleExport = async (target: ExportTarget) => {- if (!report?.connected) return;+ if (!report?.connected || reportQuery.isPlaceholderData) return;try {if (tab === "striking") {exportStriking(report, target);@@ -188,6 +176,24 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {}};+ const filtersPanel = (+ <SearchPerformanceTextFilters+ value={textFilters}+ activeFilterCount={activeFilterCount}+ onApply={(filters) => {+ setPage(1);+ setTextFilters(filters);+ }}+ onReset={() => {+ setPage(1);+ setTextFilters({});+ setCountry(ALL);+ setDevice(ALL);+ setRange("last_28_days");+ }}+ />+ );+return (<div className="px-4 py-4 pb-24 overflow-auto md:px-6 md:py-6 md:pb-8"><div className="mx-auto max-w-7xl space-y-4">@@ -210,6 +216,7 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {) : null}</div>+ {reportQuery.isError ? filtersPanel : null}{reportQuery.isPending ? (<SearchPerformanceLoadingState />) : reportQuery.isError ? (@@ -224,95 +231,144 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {</div>) : (<>- <TotalsCards report={report} />+ {reportQuery.isPlaceholderData ? (+ <SearchPerformanceLoadingState />+ ) : (+ <TotalsCards report={report} />+ )}<div className="overflow-hidden rounded-xl border border-base-300 bg-base-100"><div className="flex flex-col gap-3 border-b border-base-300 px-4 py-3 lg:flex-row lg:items-center lg:justify-between"><div role="tablist" className="tabs tabs-border w-fit"><TabButtonactive={tab === "striking"}- onClick={() => setTab("striking")}- label={`Striking distance (${report.strikingDistance.length})`}+ onClick={() => {+ setPage(1);+ setTab("striking");+ }}+ label={+ reportQuery.isPlaceholderData+ ? "Striking distance"+ : `Striking distance (${report.strikingDistance.length})`+ }/><TabButtonactive={tab === "queries"}- onClick={() => setTab("queries")}+ onClick={() => {+ setPage(1);+ setTab("queries");+ }}label="Queries"/><TabButtonactive={tab === "pages"}- onClick={() => setTab("pages")}+ onClick={() => {+ setPage(1);+ setTab("pages");+ }}label="Pages"/></div>- <div className="flex flex-wrap items-center gap-2">- {reportQuery.isFetching && !reportQuery.isPending ? (- <Loader2 className="size-4 animate-spin text-base-content/40" />+ <TableExportMenu+ buttonClassName="btn btn-ghost btn-sm gap-1"+ actions={[+ {+ label: "Export to Sheets",+ disabled: reportQuery.isPlaceholderData,+ icon: <Sheet className="size-4" />,+ onClick: () => void handleExport("sheets"),+ },+ {+ label: "Download CSV",+ disabled: reportQuery.isPlaceholderData,+ icon: <Download className="size-4" />,+ onClick: () => void handleExport("csv"),+ },+ ]}+ />+ </div>+ <div className="flex flex-wrap items-center justify-end gap-2 px-4 py-2 border-b border-base-300">+ <button+ type="button"+ className={`btn btn-ghost btn-sm gap-1.5 ${showFilters ? "btn-active" : ""}`}+ aria-expanded={showFilters}+ aria-controls="search-performance-filters"+ onClick={() => setShowFilters((current) => !current)}+ title="Toggle table filters"+ >+ <SlidersHorizontal className="size-3.5" />+ Filters+ {activeFilterCount > 0 ? (+ <span className="badge badge-xs badge-primary border-0 text-primary-content">+ {activeFilterCount}+ </span>) : null}- <select- className="select select-bordered select-sm w-36"- value={device}- onChange={(event) => {- setDevice(- isDevice(event.target.value) ? event.target.value : ALL,- );- }}- aria-label="Device filter"- >- <option value={ALL}>All devices</option>- {DEVICE_OPTIONS.map((option) => (- <option key={option.value} value={option.value}>- {option.label}- </option>- ))}- </select>- <select- className="select select-bordered select-sm w-36"- value={country}- onChange={(event) => setCountry(event.target.value)}- aria-label="Country filter"- >- <option value={ALL}>All countries</option>- {report.countries.map((row) => (- <option key={row.key} value={row.key}>- {row.key.toUpperCase()}- </option>- ))}- </select>- <select- className="select select-bordered select-sm w-36"- value={range}- onChange={(event) => {- if (isDateRange(event.target.value)) {- setRange(event.target.value);- }- }}- aria-label="Date range"- >- {RANGE_OPTIONS.map((option) => (- <option key={option.value} value={option.value}>- {option.label}- </option>- ))}- </select>- <TableExportMenu- buttonClassName="btn btn-ghost btn-sm gap-1"- actions={[- {- label: "Export to Sheets",- icon: <Sheet className="size-4" />,- onClick: () => void handleExport("sheets"),- },- {- label: "Download CSV",- icon: <Download className="size-4" />,- onClick: () => void handleExport("csv"),- },- ]}- />- </div>+ </button>+ {reportQuery.isFetching && !reportQuery.isPending ? (+ <Loader2 className="size-4 animate-spin text-base-content/40" />+ ) : null}+ <select+ className="select select-bordered select-sm w-36"+ value={device}+ onChange={(event) => {+ setPage(1);+ setDevice(+ isDevice(event.target.value) ? event.target.value : ALL,+ );+ }}+ aria-label="Device filter"+ >+ <option value={ALL}>All devices</option>+ {DEVICE_OPTIONS.map((option) => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </select>+ <select+ className="select select-bordered select-sm w-36"+ value={country}+ onChange={(event) => {+ setPage(1);+ setCountry(event.target.value);+ }}+ aria-label="Country filter"+ >+ <option value={ALL}>All countries</option>+ {country !== ALL &&+ !report.countries.some((row) => row.key === country) ? (+ <option value={country}>{country.toUpperCase()}</option>+ ) : null}+ {report.countries.map((row) => (+ <option key={row.key} value={row.key}>+ {row.key.toUpperCase()}+ </option>+ ))}+ </select>+ <select+ className="select select-bordered select-sm w-36"+ value={range}+ onChange={(event) => {+ if (isDateRange(event.target.value)) {+ setPage(1);+ setRange(event.target.value);+ }+ }}+ aria-label="Date range"+ >+ {RANGE_OPTIONS.map((option) => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </select></div>- {tab === "striking" ? (+ {showFilters ? filtersPanel : null}+ {reportQuery.isPlaceholderData ? (+ <div className="p-8 text-sm" role="status">+ Loading matching results…+ </div>+ ) : tab === "striking" ? (<StrikingDistanceTableprojectId={projectId}rows={report.strikingDistance}@@ -341,11 +397,16 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {page={page}pageSize={pageSize}pageSizes={SEARCH_PERFORMANCE_PAGE_SIZES}- totalCount={null}+ totalCount={+ tableData?.connected ? tableData.totalCount : null+ }hasNextPage={hasNextPage}isLoading={tableQuery.isFetching}onPageChange={setPage}- onPageSizeChange={setPageSize}+ onPageSizeChange={(size) => {+ setPage(1);+ setPageSize(size);+ }}/></>)}diff --git a/src/client/features/search-performance/SearchPerformanceTextFilters.tsx b/src/client/features/search-performance/SearchPerformanceTextFilters.tsxnew file mode 100644index 00000000..7ab86d2a--- /dev/null+++ b/src/client/features/search-performance/SearchPerformanceTextFilters.tsx@@ -0,0 +1,182 @@+import { useState } from "react";+import { RotateCcw } from "lucide-react";+import type { z } from "zod";+import type { searchPerformanceInputSchema } from "@/types/schemas/search-performance";++export type TextFilters = Pick<+ z.infer<typeof searchPerformanceInputSchema>,+ "pageFilter" | "queryFilter"+>;++export function SearchPerformanceTextFilters({+ value,+ activeFilterCount,+ onApply,+ onReset,+}: {+ value: TextFilters;+ activeFilterCount: number;+ onApply: (filters: TextFilters) => void;+ onReset: () => void;+}) {+ const [page, setPage] = useState(value.pageFilter?.expression ?? "");+ const [query, setQuery] = useState(value.queryFilter?.expression ?? "");+ const [pageOperator, setPageOperator] = useState<"contains" | "equals">(+ value.pageFilter?.operator ?? "contains",+ );+ const [queryOperator, setQueryOperator] = useState<"contains" | "equals">(+ value.queryFilter?.operator ?? "contains",+ );+ const dirtyCount =+ Number(+ page.trim() !== (value.pageFilter?.expression ?? "") ||+ pageOperator !== (value.pageFilter?.operator ?? "contains"),+ ) ++ Number(+ query.trim() !== (value.queryFilter?.expression ?? "") ||+ queryOperator !== (value.queryFilter?.operator ?? "contains"),+ );+ const cancel = () => {+ setPage(value.pageFilter?.expression ?? "");+ setQuery(value.queryFilter?.expression ?? "");+ setPageOperator(value.pageFilter?.operator ?? "contains");+ setQueryOperator(value.queryFilter?.operator ?? "contains");+ };+ return (+ <form+ id="search-performance-filters"+ className="border-b border-base-300 bg-gradient-to-b from-base-100 to-base-200/30 px-4 py-3 space-y-3"+ onSubmit={(event) => {+ event.preventDefault();+ setPage(page.trim());+ setQuery(query.trim());+ if (!page.trim()) setPageOperator("contains");+ if (!query.trim()) setQueryOperator("contains");+ onApply({+ pageFilter: page.trim()+ ? { operator: pageOperator, expression: page.trim() }+ : undefined,+ queryFilter: query.trim()+ ? { operator: queryOperator, expression: query.trim() }+ : undefined,+ });+ }}+ >+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex items-center gap-2">+ <p className="text-sm font-semibold">Refine table results</p>+ {activeFilterCount > 0 ? (+ <span className="badge badge-xs badge-primary border-0 text-primary-content">+ {activeFilterCount} active+ </span>+ ) : null}+ {dirtyCount > 0 ? (+ <span className="badge badge-xs badge-warning border-0">+ {dirtyCount} unapplied+ </span>+ ) : null}+ </div>+ <button+ type="button"+ className="btn btn-xs btn-ghost gap-1"+ disabled={activeFilterCount === 0 && dirtyCount === 0}+ onClick={() => {+ setPage("");+ setQuery("");+ setPageOperator("contains");+ setQueryOperator("contains");+ onReset();+ }}+ >+ <RotateCcw className="size-3" />+ Clear all+ </button>+ </div>+ <div className="grid gap-3 md:grid-cols-2">+ <div className="space-y-1.5">+ <span className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">+ Page URL+ </span>+ <div className="flex flex-col gap-2 sm:flex-row">+ <select+ aria-label="Page match"+ className="select select-bordered select-sm bg-base-100 w-full sm:w-44 sm:shrink-0"+ value={pageOperator}+ onChange={(event) =>+ setPageOperator(+ event.target.value === "equals" ? "equals" : "contains",+ )+ }+ >+ <option value="contains">Contains</option>+ <option value="equals">Exactly matches</option>+ </select>+ <input+ className="input input-bordered input-sm bg-base-100 w-full min-w-0 sm:flex-1"+ aria-label="Page URL filter"+ value={page}+ maxLength={4096}+ onChange={(event) => setPage(event.target.value)}+ placeholder="URL or subfolder"+ />+ </div>+ </div>+ <div className="space-y-1.5">+ <span className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">+ Query+ </span>+ <div className="flex flex-col gap-2 sm:flex-row">+ <select+ aria-label="Query match"+ className="select select-bordered select-sm bg-base-100 w-full sm:w-44 sm:shrink-0"+ value={queryOperator}+ onChange={(event) =>+ setQueryOperator(+ event.target.value === "equals" ? "equals" : "contains",+ )+ }+ >+ <option value="contains">Contains</option>+ <option value="equals">Exactly matches</option>+ </select>+ <input+ className="input input-bordered input-sm bg-base-100 w-full min-w-0 sm:flex-1"+ aria-label="Query filter"+ value={query}+ maxLength={4096}+ onChange={(event) => setQuery(event.target.value)}+ placeholder="Search term"+ />+ </div>+ </div>+ </div>+ <p className="text-xs text-base-content/70">+ All filters must match. Contains ignores case and matches text anywhere,+ including a subfolder. Exactly matches compares the full URL or query,+ including case.+ </p>+ <div className="flex items-center justify-end gap-2 pt-1">+ <button+ type="button"+ className="btn btn-sm btn-ghost"+ onClick={cancel}+ disabled={dirtyCount === 0}+ >+ Cancel+ </button>+ <button+ className="btn btn-primary btn-sm"+ type="submit"+ disabled={dirtyCount === 0}+ >+ Apply filters+ {dirtyCount > 0 ? (+ <span className="badge badge-xs ml-1 border-0 bg-primary-content/20">+ {dirtyCount}+ </span>+ ) : null}+ </button>+ </div>+ </form>+ );+}diff --git a/src/client/features/search-performance/searchPerformanceQueries.ts b/src/client/features/search-performance/searchPerformanceQueries.tsnew file mode 100644index 00000000..28adfade--- /dev/null+++ b/src/client/features/search-performance/searchPerformanceQueries.ts@@ -0,0 +1,36 @@+import { queryOptions } from "@tanstack/react-query";+import type { z } from "zod";+import { getSearchPerformanceTable } from "@/serverFunctions/searchPerformance";+import type {+ searchPerformanceInputSchema,+ SearchPerformanceTableDimension,+} from "@/types/schemas/search-performance";++export type FilterInput = Omit<+ z.infer<typeof searchPerformanceInputSchema>,+ "projectId"+>;++// Shared by the live table and prefetch so the query key and request agree.+export function tableQueryOptions(+ projectId: string,+ dimension: SearchPerformanceTableDimension,+ page: number,+ pageSize: number,+ filterInput: FilterInput,+) {+ return queryOptions({+ queryKey: [+ "searchPerformanceTable",+ projectId,+ dimension,+ page,+ pageSize,+ filterInput,+ ],+ queryFn: () =>+ getSearchPerformanceTable({+ data: { projectId, dimension, page, pageSize, ...filterInput },+ }),+ });+}diff --git a/src/serverFunctions/searchPerformance.test.ts b/src/serverFunctions/searchPerformance.test.tsnew file mode 100644index 00000000..5b50dd52--- /dev/null+++ b/src/serverFunctions/searchPerformance.test.ts@@ -0,0 +1,140 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { z } from "zod";+import {+ exportSearchPerformanceTable,+ getSearchPerformanceReport,+ getSearchPerformanceTable,+} from "./searchPerformance";+import { searchPerformanceInputSchema } from "@/types/schemas/search-performance";++const { getPerformance } = vi.hoisted(() => ({ getPerformance: vi.fn() }));+vi.mock("@/server/features/gsc/services/GscService", () => ({+ GscService: { getPerformance },+ GscNotConnectedError: class extends Error {},+ isExpectedGrantFailure: () => false,+}));+vi.mock("@/serverFunctions/middleware", () => ({ requireProjectContext: [] }));+vi.mock("@tanstack/react-start", () => ({+ createServerFn: () => ({+ middleware: () => ({+ validator: (schema: z.ZodType) => ({+ handler:+ (+ handler: (input: {+ data: unknown;+ context: { projectId: string };+ }) => unknown,+ ) =>+ ({ data }: { data: unknown }) =>+ handler({+ data: schema.parse(data),+ context: { projectId: "authorized-project" },+ }),+ }),+ }),+ }),+}));++const data = {+ projectId: "authorized-project",+ dateRange: "last_28_days" as const,+ country: "SWE",+ device: "MOBILE" as const,+ pageFilter: { operator: "contains" as const, expression: "/collections/" },+ queryFilter: { operator: "equals" as const, expression: "OpenSEO" },+};+const filters = [+ { dimension: "device", operator: "equals", expression: "MOBILE" },+ { dimension: "page", ...data.pageFilter },+ { dimension: "query", ...data.queryFilter },+ { dimension: "country", operator: "equals", expression: "swe" },+];++describe("Search Performance combined filters", () => {+ beforeEach(() => getPerformance.mockResolvedValue({ rows: [] }));++ it("applies the same filters to both totals periods and striking distance, keeping country options available", async () => {+ await getSearchPerformanceReport({ data });+ expect(getPerformance).toHaveBeenCalledTimes(4);+ for (const index of [0, 1, 2]) {+ expect(getPerformance.mock.calls[index][0]).toMatchObject({+ projectId: "authorized-project",+ filters,+ });+ }+ expect(getPerformance.mock.calls[3][0]).toMatchObject({+ dimensions: ["country"],+ filters: filters.slice(0, 3),+ });+ });++ it.each(["query", "page"] as const)(+ "keeps %s pagination and exports on the same filtered dataset",+ async (dimension) => {+ await getSearchPerformanceTable({+ data: { ...data, dimension, page: 2, pageSize: 25 },+ });+ await exportSearchPerformanceTable({ data: { ...data, dimension } });+ expect(getPerformance.mock.calls[0][0]).toMatchObject({+ dimensions: [dimension],+ filters,+ startRow: 25,+ rowLimit: 26,+ });+ expect(getPerformance.mock.calls[1][0]).toMatchObject({+ dimensions: [dimension],+ filters,+ rowLimit: 1000,+ });+ },+ );++ it("rejects empty expressions and unsupported match operators", () => {+ for (const pageFilter of [+ { operator: "contains", expression: " " },+ { operator: "startsWith", expression: "/collections/" },+ { operator: "contains", expression: "a".repeat(4097) },+ ]) {+ expect(+ searchPerformanceInputSchema.safeParse({ ...data, pageFilter }).success,+ ).toBe(false);+ expect(+ searchPerformanceInputSchema.safeParse({+ ...data,+ queryFilter: pageFilter,+ }).success,+ ).toBe(false);+ }+ });++ it("reports the last-page row count instead of a full page for narrow filters", async () => {+ getPerformance.mockResolvedValue({+ rows: [+ {+ keys: ["soundsplitter"],+ clicks: 1,+ impressions: 1,+ ctr: 1,+ position: 6,+ },+ ],+ });+ const result = await getSearchPerformanceTable({+ data: { ...data, dimension: "query", page: 1, pageSize: 25 },+ });+ expect(result).toMatchObject({+ connected: true,+ hasNextPage: false,+ totalCount: 1,+ });+ getPerformance.mockResolvedValue({ rows: [] });+ const empty = await getSearchPerformanceTable({+ data: { ...data, dimension: "query", page: 1, pageSize: 25 },+ });+ expect(empty).toMatchObject({+ connected: true,+ hasNextPage: false,+ totalCount: 0,+ });+ });+});diff --git a/src/serverFunctions/searchPerformance.ts b/src/serverFunctions/searchPerformance.tsindex b3723b38..36dc9f74 100644--- a/src/serverFunctions/searchPerformance.ts+++ b/src/serverFunctions/searchPerformance.ts@@ -30,23 +30,32 @@ const COUNTRY_ROW_LIMIT = 25;// (GSC_MAX_ROW_LIMIT). Large stores get everything up to this ceiling.const EXPORT_ROW_LIMIT = 1000;-/** Build GSC filter groups shared by every call. Device applies everywhere;+/** Build GSC filter groups shared by every call. Device, page, and query apply everywhere;* country applies everywhere except the country breakdown itself (so the* dropdown keeps every option visible while one country is selected). */-function buildGscFilters(data: { device?: string; country?: string }): {- deviceFilters: GscPerformanceFilter[];+function buildGscFilters(data: {+ device?: string;+ country?: string;+ pageFilter?: { operator: "contains" | "equals"; expression: string };+ queryFilter?: { operator: "contains" | "equals"; expression: string };+}): {+ nonCountryFilters: GscPerformanceFilter[];filters: GscPerformanceFilter[];} {- const deviceFilters: GscPerformanceFilter[] = data.device+ const nonCountryFilters: GscPerformanceFilter[] = data.device? [{ dimension: "device", operator: "equals", expression: data.device }]: [];+ if (data.pageFilter)+ nonCountryFilters.push({ dimension: "page", ...data.pageFilter });+ if (data.queryFilter)+ nonCountryFilters.push({ dimension: "query", ...data.queryFilter });const filters: GscPerformanceFilter[] = data.country? [- ...deviceFilters,+ ...nonCountryFilters,{ dimension: "country", operator: "equals", expression: data.country },]- : deviceFilters;- return { deviceFilters, filters };+ : nonCountryFilters;+ return { nonCountryFilters, filters };}/** Not connected, or a dead/denied grant (token failure or 401/403): the page@@ -71,7 +80,7 @@ export const getSearchPerformanceReport = createServerFn({ method: "POST" })});const prev = previousPeriod(startDate, endDate);const projectId = context.projectId;- const { deviceFilters, filters } = buildGscFilters(data);+ const { nonCountryFilters, filters } = buildGscFilters(data);try {const [current, previous, queryPages, countries] = await Promise.all([@@ -104,7 +113,7 @@ export const getSearchPerformanceReport = createServerFn({ method: "POST" })startDate,endDate,dimensions: ["country"],- filters: deviceFilters,+ filters: nonCountryFilters,rowLimit: COUNTRY_ROW_LIMIT,}),]);@@ -167,6 +176,10 @@ export const getSearchPerformanceTable = createServerFn({ method: "POST" })page: data.page,pageSize: data.pageSize,hasNextPage,+ totalCount:+ !hasNextPage && (offset === 0 || rows.length > 0)+ ? offset + rows.length+ : null,rows,};} catch (error) {diff --git a/src/types/schemas/search-performance.ts b/src/types/schemas/search-performance.tsindex 88dfbed2..37822ed9 100644--- a/src/types/schemas/search-performance.ts+++ b/src/types/schemas/search-performance.ts@@ -19,6 +19,18 @@ export type SearchPerformanceDevice = (typeof GSC_DEVICES)[number];// Shared report/table filters. Spread into each request schema so the overview// and the paginated table calls always accept the exact same filter surface.const searchPerformanceFilterShape = {+ pageFilter: z+ .object({+ operator: z.enum(["contains", "equals"]),+ expression: z.string().trim().min(1).max(4096),+ })+ .optional(),+ queryFilter: z+ .object({+ operator: z.enum(["contains", "equals"]),+ expression: z.string().trim().min(1).max(4096),+ })+ .optional(),projectId: z.string().min(1),dateRange: z.enum(SEARCH_PERFORMANCE_RANGES).default("last_28_days"),device: z.enum(GSC_DEVICES).optional(),