Skip to content

Open-source status page, incident response and uptime monitoring

feat: dashboard data-table-filters logs (#2614)

Maximilian Kaskef4bf9a4c6ad7
diff --git a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/client.tsx b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/client.tsx
index 79df5d762..633922384 100644
--- a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/client.tsx
@@ -1,11 +1,31 @@
"use client";
+// REMINDER: React Compiler is not compatible with Tanstack Table v8
+// https://github.com/TanStack/table/issues/5567
+"use no memo";
+
+import type { RouterOutputs } from "@openstatus/api";
import { Lock } from "@openstatus/icons";
-import { useQuery } from "@tanstack/react-query";
-import type { PaginationState } from "@tanstack/react-table";
+import { DataTableFilterAICommand } from "@openstatus/ui/components/data-table-filters/data-table-filter-command-ai/index";
+import { DataTableInfinite } from "@openstatus/ui/components/data-table-filters/data-table-infinite";
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { defineFilters } from "@openstatus/ui/lib/data-table-filters/filters/index";
+import { useMemoryAdapter } from "@openstatus/ui/lib/data-table-filters/store/adapters/memory/index";
+import { useNuqsAdapter } from "@openstatus/ui/lib/data-table-filters/store/adapters/nuqs/index";
+import { useFilterState } from "@openstatus/ui/lib/data-table-filters/store/hooks/index";
+import { DataTableStoreProvider } from "@openstatus/ui/lib/data-table-filters/store/provider/DataTableStoreProvider";
+import {
+ getDefaultColumnVisibility,
+ resolveColumns,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+import {
+ keepPreviousData,
+ useInfiniteQuery,
+ useQuery,
+} from "@tanstack/react-query";
import { useParams } from "next/navigation";
-import { useQueryStates } from "nuqs";
-import { useCallback, useMemo } from "react";
+import { parseAsString, useQueryState } from "nuqs";
+import { useCallback, useEffect, useMemo } from "react";
import { Link } from "@/components/common/link";
import {
@@ -14,154 +34,337 @@ import {
BillingOverlayContainer,
BillingOverlayDescription,
} from "@/components/content/billing-overlay";
-import {
- SectionDescription,
- SectionGroup,
- SectionHeader,
- SectionTitle,
-} from "@/components/content/section";
-import { Section } from "@/components/content/section";
-import { ButtonReset } from "@/components/controls-search/button-reset";
-import { CommandRegion } from "@/components/controls-search/command-region";
-import { DropdownStatus } from "@/components/controls-search/dropdown-status";
-import { DropdownTrigger } from "@/components/controls-search/dropdown-trigger";
-import { PopoverDate } from "@/components/controls-search/popover-date";
-import { getColumns } from "@/components/data-table/response-logs/columns";
import { Sheet } from "@/components/data-table/response-logs/data-table-sheet";
-import { DataTable } from "@/components/ui/data-table/data-table";
-import { DataTablePagination } from "@/components/ui/data-table/data-table-pagination";
-import { DataTableSkeleton } from "@/components/ui/data-table/data-table-skeleton";
import { exampleLogs } from "@/data/response-logs";
import { useTRPC } from "@/lib/trpc/client";
-import { searchParamsParsers } from "./search-params";
+import {
+ createLogsTable,
+ RETENTION_DAYS,
+ type ResponseLog,
+} from "./table-schema";
+
+const TABLE_ID = "response-logs";
+const PAGE_SIZE = 50;
+const MAX_WINDOW_MS = RETENTION_DAYS * 24 * 60 * 60 * 1000;
+
+type Monitor = RouterOutputs["monitor"]["get"];
+
+/** The shape the generated filter schema keeps in the URL. */
+type LogsFilterState = {
+ requestStatus?: string[];
+ timestamp?: Date[];
+ statusCode?: number[];
+ latency?: number[];
+ region?: string[];
+ trigger?: string[];
+};
export function Client() {
const trpc = useTRPC();
const { id } = useParams<{ id: string }>();
- const [
- { regions, status, selected, trigger, from, to, pageIndex, pageSize },
- setSearchParams,
- ] = useQueryStates(searchParamsParsers);
const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
const { data: monitor } = useQuery(
trpc.monitor.get.queryOptions({ id: Number.parseInt(id) }),
);
- const enabled = workspace && workspace?.plan !== "free";
- const { data: _logs, isLoading } = useQuery({
- ...trpc.tinybird.list.queryOptions({ monitorId: id, from, to }),
- enabled,
- });
- const { data: _log } = useQuery({
- ...trpc.tinybird.get.queryOptions({ id: selected, monitorId: id }),
- enabled: !!selected && enabled,
+
+ if (!workspace || !monitor) return null;
+
+ // No `SectionGroup` here: it centres content in a `max-w-4xl` column, and the
+ // table renders its own filter sidebar + toolbar shell that needs the full
+ // width of the content area. The box is pinned to the space left below the
+ // app header and the monitor tabs so the document never scrolls: the filter
+ // sidebar and the table body each own their scroll instead.
+ return (
+ <div className="relative flex h-[calc(100svh-var(--spacing-app-header)-var(--spacing-app-tabs))] w-full flex-col overflow-hidden">
+ {workspace.plan === "free" ? (
+ <BillingPlaceholder />
+ ) : (
+ <LogsTable monitor={monitor} />
+ )}
+ </div>
+ );
+}
+
+function LogsTable({ monitor }: { monitor: Monitor }) {
+ const { schema, columns, filterFields, filterSchema } = useMemo(
+ () =>
+ createLogsTable({
+ regions: monitor.regions,
+ privateLocations: monitor.privateLocations ?? [],
+ jobType: monitor.jobType,
+ }),
+ [monitor.regions, monitor.privateLocations, monitor.jobType],
+ );
+
+ const adapter = useNuqsAdapter(filterSchema.definition, { id: TABLE_ID });
+
+ return (
+ <DataTableStoreProvider adapter={adapter}>
+ <LogsTableInner
+ monitor={monitor}
+ columns={columns}
+ filterFields={filterFields}
+ schema={schema}
+ filterSchema={filterSchema}
+ />
+ </DataTableStoreProvider>
+ );
+}
+
+function LogsTableInner({
+ monitor,
+ columns,
+ filterFields,
+ schema,
+ filterSchema,
+}: {
+ monitor: Monitor;
+ columns: ReturnType<typeof createLogsTable>["columns"];
+ filterFields: ReturnType<typeof createLogsTable>["filterFields"];
+ schema: ReturnType<typeof createLogsTable>["schema"];
+ filterSchema: ReturnType<typeof createLogsTable>["filterSchema"];
+}) {
+ const trpc = useTRPC();
+ const state = useFilterState<LogsFilterState>();
+ const [selected, setSelected] = useQueryState("selected", parseAsString);
+
+ // The table re-runs every filter over the fetched rows, so the range sent to
+ // the pipes has to be the one `filterFn` will apply — a single date means
+ // that whole day there, not "everything since".
+ const filterDefs = useMemo(() => defineFilters(schema.definition), [schema]);
+
+ const filters = useMemo(() => {
+ const range = filterDefs
+ .plan({ timestamp: state.timestamp })
+ .find((op) => op.op === "dateRange");
+ const from = range?.from;
+ const to = range?.to;
+ // The facet and list pipes only reach back `RETENTION_DAYS`, so a wider
+ // range would silently truncate instead of returning what the picker shows.
+ const floor = (to ?? new Date()).getTime() - MAX_WINDOW_MS;
+
+ return {
+ monitorId: monitor.id,
+ from: from ? new Date(Math.max(from.getTime(), floor)) : undefined,
+ to,
+ regions: state.region?.length ? state.region : undefined,
+ status: state.requestStatus?.length
+ ? (state.requestStatus as ("success" | "error" | "degraded")[])
+ : undefined,
+ trigger: state.trigger?.length
+ ? (state.trigger as ("cron" | "api")[])
+ : undefined,
+ statusCodes: state.statusCode?.length ? state.statusCode : undefined,
+ latencyMin: state.latency?.[0],
+ latencyMax: state.latency?.[1],
+ };
+ }, [state, monitor.id, filterDefs]);
+
+ const { data, isFetching, isLoading, hasNextPage, fetchNextPage, refetch } =
+ useInfiniteQuery(
+ trpc.tinybird.listInfinite.infiniteQueryOptions(
+ { ...filters, limit: PAGE_SIZE },
+ {
+ getNextPageParam: (page) => page.nextCursor ?? undefined,
+ getPreviousPageParam: (page) => page.prevCursor ?? undefined,
+ },
+ ),
+ );
+
+ // Hold the previous counts while the next request is in flight. Without it
+ // every filter change empties `facets`, and the checkbox filters — which
+ // derive their option list from it — collapse to their declared set and
+ // rebuild a moment later. `isPending` is then only true on the first load,
+ // which is the one time there is nothing to hold on to.
+ const { data: facets, isPending: isFacetsPending } = useQuery({
+ ...trpc.tinybird.listFacets.queryOptions(filters),
+ placeholderData: keepPreviousData,
+ staleTime: 30_000,
});
- const pagination = useMemo(
- () => ({ pageIndex, pageSize }),
- [pageIndex, pageSize],
+ const rows = useMemo(
+ () => data?.pages.flatMap((page) => page.data) ?? [],
+ [data],
);
- const setPagination = useCallback(
- (p: PaginationState | ((old: PaginationState) => PaginationState)) => {
- const next = typeof p === "function" ? p({ pageIndex, pageSize }) : p;
+ // `.hidden()` columns from the schema, plus the one that carries no value for
+ // the non-HTTP checkers. The status code column is dropped from the schema
+ // itself, so it needs no entry here.
+ const columnVisibility = useMemo(
+ () => ({
+ ...getDefaultColumnVisibility(schema.definition),
+ // gRPC carries HTTP's phase timings.
+ ...(monitor.jobType === "http" || monitor.jobType === "grpc"
+ ? {}
+ : { timing: false }),
+ }),
+ [schema, monitor.jobType],
+ );
- if (next.pageIndex !== pageIndex || next.pageSize !== pageSize) {
- setSearchParams({
- pageIndex: next.pageIndex,
- pageSize: next.pageSize,
- });
+ // A checkbox filter looks its count up by the option's own value, and
+ // `col.presets.httpStatus()` options are numbers. The facet pipes return
+ // every value as a string, so numeric columns need the key coerced back.
+ const numericColumns = useMemo(
+ () =>
+ new Set(
+ resolveColumns(schema.definition)
+ .filter((column) => column.kind === "number")
+ .map((column) => column.key),
+ ),
+ [schema],
+ );
+
+ const getFacetedUniqueValues = useCallback(
+ (_table: unknown, columnId: string) => {
+ const map = new Map<string | number, number>();
+ const toKey = numericColumns.has(columnId) ? Number : String;
+ for (const row of facets?.facets[columnId]?.rows ?? []) {
+ map.set(toKey(row.value), row.total);
}
+ return map;
},
- [pageIndex, pageSize, setSearchParams],
+ [facets, numericColumns],
);
- const columns = useMemo(
- () => getColumns(monitor?.privateLocations ?? []),
- [monitor?.privateLocations],
+ const getFacetedMinMaxValues = useCallback(
+ (_table: unknown, columnId: string): [number, number] | undefined => {
+ if (columnId !== "latency") return undefined;
+ const latency = facets?.facets.latency;
+ if (latency?.min === undefined || latency.max === undefined) {
+ return undefined;
+ }
+ return [latency.min, latency.max];
+ },
+ [facets],
);
- if (!workspace || !monitor) return null;
-
return (
- <SectionGroup>
- <Section>
- <SectionHeader>
- <SectionTitle>{monitor.name}</SectionTitle>
- <SectionDescription>
- {monitor.jobType === "http" ? (
- <a href={monitor.url} target="_blank" rel="noopener noreferrer">
- {monitor.url}
- </a>
- ) : (
- monitor.url
- )}
- </SectionDescription>
- </SectionHeader>
- <div className="flex flex-wrap items-center gap-2">
- <PopoverDate />
- {monitor.jobType === "http" ? <DropdownStatus /> : null}
- <DropdownTrigger />
- <CommandRegion
- regions={monitor.regions}
- privateLocations={monitor?.privateLocations}
- />
- <ButtonReset />
- </div>
- </Section>
- <Section>
- {isLoading ? (
- <DataTableSkeleton rows={10} />
- ) : !enabled ? (
- <BillingPlaceholder />
- ) : (
- <DataTable
- data={_logs?.data ?? []}
- columns={columns}
- onRowClick={(row) => {
- if (!row.original.id) return;
- setSearchParams({ selected: row.original.id });
- }}
- columnFilters={[
- { id: "trigger", value: trigger },
- { id: "requestStatus", value: status },
- { id: "region", value: regions },
- ].filter((i) => Boolean(i.value))}
- pagination={pagination}
- setPagination={setPagination}
- paginationComponent={DataTablePagination}
- defaultColumnVisibility={
- // gRPC carries HTTP's phase timings, so only its status code
- // column is meaningless.
- monitor.jobType === "grpc"
- ? { statusCode: false }
- : monitor.jobType === "tcp" ||
- monitor.jobType === "dns" ||
- monitor.jobType === "icmp"
- ? { timing: false, statusCode: false }
- : {}
- }
- // NOTE: required to control the pagination
- autoResetPageIndex={false}
+ <>
+ <DataTableInfinite
+ columns={columns}
+ data={rows}
+ filterFields={filterFields}
+ defaultColumnVisibility={columnVisibility}
+ getRowId={(row: ResponseLog, index: number) => row.id ?? String(index)}
+ defaultRowSelection={selected ? { [selected]: true } : {}}
+ getFacetedUniqueValues={
+ getFacetedUniqueValues as React.ComponentProps<
+ typeof DataTableInfinite<ResponseLog, unknown>
+ >["getFacetedUniqueValues"]
+ }
+ getFacetedMinMaxValues={
+ getFacetedMinMaxValues as React.ComponentProps<
+ typeof DataTableInfinite<ResponseLog, unknown>
+ >["getFacetedMinMaxValues"]
+ }
+ totalRows={facets?.totalRowCount}
+ filterRows={facets?.filterRowCount}
+ totalRowsFetched={rows.length}
+ isFetching={isFetching}
+ isLoading={isLoading}
+ isFacetsLoading={isFacetsPending}
+ hasNextPage={hasNextPage}
+ fetchNextPage={fetchNextPage}
+ refetch={refetch}
+ tableId={TABLE_ID}
+ commandSlot={
+ <DataTableFilterAICommand
+ schema={filterSchema.definition}
+ tableSchema={schema.definition}
+ api="/api/ai-filters"
+ tableId={TABLE_ID}
/>
- )}
- <Sheet
- data={_log?.data?.length ? _log.data[0] : null}
- privateLocations={monitor?.privateLocations ?? []}
- onClose={() =>
- setTimeout(() => setSearchParams({ selected: null }), 300)
- }
- />
- </Section>
- </SectionGroup>
+ }
+ sheetSlot={<LogsSheet monitor={monitor} onSelect={setSelected} />}
+ />
+ </>
+ );
+}
+
+/**
+ * Bridges the table's row selection to the existing response-log sheet, and
+ * mirrors it into `selected` so a row survives a reload. Rows written before
+ * the checker stamped an id have no detail to fetch, so they resolve to null.
+ */
+function LogsSheet({
+ monitor,
+ onSelect,
+}: {
+ monitor: Monitor;
+ onSelect: (value: string | null) => void;
+}) {
+ const trpc = useTRPC();
+ const { table, rowSelection } = useDataTable<ResponseLog, unknown>();
+ const selectedRow = table.getSelectedRowModel().rows[0];
+ // The row model only holds fetched rows, so a bookmarked log from a later
+ // page would resolve to null and wipe `selected` from the URL. The selection
+ // record carries the id whether or not its row has been fetched.
+ const selectedId = selectedRow
+ ? (selectedRow.original.id ?? null)
+ : (Object.keys(rowSelection).find((key) => rowSelection[key]) ?? null);
+
+ useEffect(() => {
+ onSelect(selectedId);
+ }, [selectedId, onSelect]);
+
+ const { data: log } = useQuery({
+ ...trpc.tinybird.get.queryOptions({
+ id: selectedId ?? "",
+ monitorId: String(monitor.id),
+ }),
+ enabled: Boolean(selectedId),
+ });
+
+ return (
+ <Sheet
+ data={log?.data?.length ? log.data[0] : null}
+ privateLocations={monitor.privateLocations ?? []}
+ onClose={() => {
+ table.resetRowSelection();
+ setTimeout(() => onSelect(null), 300);
+ }}
+ />
);
}
function BillingPlaceholder() {
- const columns = useMemo(() => getColumns([]), []);
+ const { columns, filterFields, filterSchema, schema } = useMemo(
+ () =>
+ createLogsTable({
+ regions: Array.from(new Set(exampleLogs.map((log) => log.region))),
+ privateLocations: [],
+ }),
+ [],
+ );
+ const adapter = useMemoryAdapter(filterSchema.definition, {
+ id: `${TABLE_ID}-example`,
+ });
+
return (
- <BillingOverlayContainer>
- <DataTable data={exampleLogs} columns={columns} />
+ <BillingOverlayContainer className="flex min-h-0 flex-1 flex-col">
+ <DataTableStoreProvider adapter={adapter}>
+ <DataTableInfinite
+ columns={columns}
+ data={exampleLogs as unknown as ResponseLog[]}
+ filterFields={filterFields}
+ totalRowsFetched={exampleLogs.length}
+ hasNextPage={false}
+ fetchNextPage={() => Promise.resolve()}
+ refetch={() => {}}
+ isFetching={false}
+ isLoading={false}
+ tableId={`${TABLE_ID}-example`}
+ commandSlot={
+ <DataTableFilterAICommand
+ schema={filterSchema.definition}
+ tableSchema={schema.definition}
+ api="/api/ai-filters"
+ tableId={`${TABLE_ID}-example`}
+ />
+ }
+ />
+ </DataTableStoreProvider>
<BillingOverlay>
<BillingOverlayButton asChild>
<Link href="/settings/billing">
@@ -172,7 +375,7 @@ function BillingPlaceholder() {
<BillingOverlayDescription>
Access response headers, timing phases and more for each request.{" "}
<Link
- href="https://www.openstatus.dev/docs/monitoring/monitor-data-collected/"
+ href="https://www.openstatus.dev/docs/concept/latency-vs-response-time/"
rel="noreferrer"
target="_blank"
>
diff --git a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/page.tsx b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/page.tsx
index 14d03f214..e3dc7ede6 100644
--- a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/page.tsx
@@ -1,15 +1,5 @@
-import type { SearchParams } from "nuqs/server";
-
import { Client } from "./client";
-import { searchParamsCache } from "./search-params";
-
-export default async function Page({
- searchParams,
-}: {
- searchParams: Promise<SearchParams>;
-}) {
- // NOTE: store in cache to avoid flicker on clients first render
- await searchParamsCache.parse(searchParams);
+export default function Page() {
return <Client />;
}
diff --git a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/search-params.ts b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/search-params.ts
deleted file mode 100644
index ae09140d7..000000000
--- a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/search-params.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { endOfDay } from "date-fns";
-import { startOfDay } from "date-fns";
-import {
- createSearchParamsCache,
- parseAsArrayOf,
- parseAsInteger,
- parseAsIsoDateTime,
- parseAsString,
- parseAsStringLiteral,
-} from "nuqs/server";
-
-import { PERIODS, STATUS, TRIGGER } from "@/data/metrics.client";
-
-export const searchParamsParsers = {
- period: parseAsStringLiteral(PERIODS).withDefault("1d"),
- regions: parseAsArrayOf(parseAsString),
- status: parseAsStringLiteral(STATUS),
- trigger: parseAsStringLiteral(TRIGGER),
- selected: parseAsString,
- from: parseAsIsoDateTime.withDefault(startOfDay(new Date())),
- to: parseAsIsoDateTime.withDefault(endOfDay(new Date())),
- pageIndex: parseAsInteger.withDefault(0),
- pageSize: parseAsInteger.withDefault(20),
-};
-
-export const searchParamsCache = createSearchParamsCache(searchParamsParsers);
diff --git a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/table-schema.tsx b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/table-schema.tsx
new file mode 100644
index 000000000..197b26007
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/table-schema.tsx
@@ -0,0 +1,261 @@
+import type { RouterOutputs } from "@openstatus/api";
+import type { PrivateLocation } from "@openstatus/db/src/schema";
+import { monitorRegions } from "@openstatus/db/src/schema/constants";
+import { ApiTrigger, Clock } from "@openstatus/icons";
+import { getRegionInfo } from "@openstatus/regions";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui/components/ui/tooltip";
+import {
+ col,
+ createTableSchema,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+import {
+ generateColumns,
+ generateFilterFields,
+ generateFilterSchema,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+import { addDays, addHours, endOfDay, startOfDay } from "date-fns";
+
+import { HoverCardTiming } from "@/components/common/hover-card-timing";
+import { TableCellNumber } from "@/components/data-table/table-cell-number";
+import { TableCellRegion } from "@/components/data-table/table-cell-region";
+import { cn } from "@/lib/utils";
+
+export type ResponseLog =
+ RouterOutputs["tinybird"]["listInfinite"]["data"][number];
+
+type JobType = RouterOutputs["monitor"]["get"]["jobType"];
+
+export const REQUEST_STATUS = ["success", "degraded", "error"] as const;
+export const TRIGGERS = ["cron", "api"] as const;
+
+const STATUS_SWATCH: Record<string, string> = {
+ success: "bg-success",
+ degraded: "bg-warning",
+ error: "bg-destructive",
+};
+
+function Dash() {
+ return <div className="text-muted-foreground">-</div>;
+}
+
+/** The same square the table cell draws, so the filter row reads as its legend. */
+function StatusSwatch({ value }: { value: string }) {
+ const swatch = STATUS_SWATCH[value];
+ if (!swatch) return null;
+ return <div className={cn(swatch, "size-2.5 shrink-0 rounded-[2px]")} />;
+}
+
+/**
+ * The slider needs static bounds at schema-build time; the real ones arrive
+ * with the facets and are fed to the table through `getFacetedMinMaxValues`.
+ */
+const LATENCY_BOUNDS = { min: 0, max: 30_000 };
+
+/** How far back the list and facet pipes reach. */
+export const RETENTION_DAYS = 14;
+
+/**
+ * The ranges the logs date popover offered before the table rewrite, capped at
+ * retention: the picker derives its selectable window from these bounds, so
+ * anything wider would query days the pipes cannot answer.
+ */
+function createTimestampPresets() {
+ const now = new Date();
+ return [
+ { label: "Today", from: startOfDay(now), to: endOfDay(now), shortcut: "t" },
+ {
+ label: "Yesterday",
+ from: startOfDay(addDays(now, -1)),
+ to: endOfDay(addDays(now, -1)),
+ shortcut: "y",
+ },
+ { label: "Last hour", from: addHours(now, -1), to: now, shortcut: "h" },
+ { label: "Last 6 hours", from: addHours(now, -6), to: now, shortcut: "s" },
+ {
+ label: "Last 24 hours",
+ from: addHours(now, -24),
+ to: now,
+ shortcut: "d",
+ },
+ {
+ label: "Last 7 days",
+ from: startOfDay(addDays(now, -6)),
+ to: endOfDay(now),
+ shortcut: "w",
+ },
+ {
+ label: `Last ${RETENTION_DAYS} days`,
+ from: startOfDay(addDays(now, -(RETENTION_DAYS - 1))),
+ to: endOfDay(now),
+ shortcut: "b",
+ },
+ ];
+}
+
+export function createLogsTableSchema(options: {
+ regions: string[];
+ privateLocations: PrivateLocation[];
+ /** Defaults to the widest schema — every column the checkers can fill. */
+ jobType?: JobType;
+}) {
+ const { regions, privateLocations, jobType = "http" } = options;
+
+ // Only the HTTP checker records a status code. Leaving the column in would
+ // expose a filter whose every option matches nothing on the other job types.
+ const hasStatusCode = jobType === "http";
+
+ // `regions` is only what the monitor runs in *today*, but the window still
+ // holds rows from regions since removed. Every known region therefore gets a
+ // label and an enum value — otherwise those rows are unfilterable and a
+ // hand-written region would parse back to null — and the facets decide which
+ // of them the filter actually offers. Configured regions stay first so the
+ // common case keeps the monitor's own order.
+ const regionOptions = [
+ ...[
+ ...regions,
+ ...monitorRegions.filter((region) => !regions.includes(region)),
+ ].map((region) => {
+ const info = getRegionInfo(region);
+ return { label: `${info.flag} ${info.code}`, value: region };
+ }),
+ ...privateLocations.map((location) => ({
+ label: `\u{1F310} ${location.name}`,
+ value: String(location.id),
+ })),
+ ];
+
+ return createTableSchema({
+ requestStatus: col
+ .enum(REQUEST_STATUS)
+ .label("Result")
+ .hideHeader()
+ .size(28)
+ .defaultOpen()
+ .filterable("checkbox", {
+ options: REQUEST_STATUS.map((value) => ({ label: value, value })),
+ // A closed set of three. A window with no degraded rows must still
+ // offer the box, or the filter reads as broken rather than empty.
+ keepEmptyOptions: true,
+ component: ({ label, value }) => (
+ <span className="flex items-center gap-2 truncate font-normal">
+ <StatusSwatch value={String(value)} />
+ {label}
+ </span>
+ ),
+ })
+ .display("custom", {
+ cell: (value) => {
+ const swatch = STATUS_SWATCH[String(value)];
+ if (!swatch) return <Dash />;
+ return (
+ <div className="flex justify-center">
+ <div className={cn(swatch, "size-2.5 rounded-[2px]")} />
+ </div>
+ );
+ },
+ }),
+
+ // `col.presets.timestamp()` but without `.sortable()`: the cursor pages on
+ // the pipe's own DESC order, so a header sort would only reorder the rows
+ // already fetched.
+ timestamp: col
+ .timestamp()
+ .label("Timestamp")
+ .display("timestamp")
+ .size(200)
+ .filterable("timerange", { presets: createTimestampPresets() }),
+
+ ...(hasStatusCode
+ ? { statusCode: col.presets.httpStatus().label("Status").size(90) }
+ : {}),
+
+ latency: col.presets
+ .duration("ms", LATENCY_BOUNDS)
+ .label("Latency")
+ .size(110)
+ .display("custom", {
+ cell: (value) => (
+ <TableCellNumber value={value as number | null} unit="ms" />
+ ),
+ }),
+
+ region: col
+ .enum(
+ regionOptions.map((option) => option.value) as [string, ...string[]],
+ )
+ .label("Region")
+ .size(120)
+ .filterable("checkbox", { options: regionOptions })
+ .display("custom", {
+ cell: (value) => (
+ <TableCellRegion
+ value={String(value)}
+ privateLocations={privateLocations}
+ variant="code"
+ />
+ ),
+ }),
+
+ timing: col
+ .record()
+ .label("Timing")
+ .size(130)
+ .display("custom", {
+ cell: (_value, row) => {
+ const log = row as ResponseLog;
+ if (!log.timing) return <Dash />;
+ return <HoverCardTiming timing={log.timing} latency={log.latency} />;
+ },
+ }),
+
+ trigger: col
+ .enum(TRIGGERS)
+ .label("Trigger")
+ .size(80)
+ .hidden()
+ .filterable("checkbox", {
+ options: TRIGGERS.map((value) => ({
+ label: value === "cron" ? "Scheduled" : "API",
+ value,
+ })),
+ })
+ .display("custom", {
+ cell: (value) => {
+ if (value !== "cron" && value !== "api") return <Dash />;
+ const Icon = value === "cron" ? Clock : ApiTrigger;
+ const label = value === "cron" ? "Scheduled" : "API";
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <Icon className="text-muted-foreground size-3" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>{label}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+ },
+ }),
+ });
+}
+
+export function createLogsTable(options: {
+ regions: string[];
+ privateLocations: PrivateLocation[];
+ jobType?: JobType;
+}) {
+ const schema = createLogsTableSchema(options);
+ return {
+ schema,
+ columns: generateColumns<ResponseLog>(schema.definition),
+ filterFields: generateFilterFields<ResponseLog>(schema.definition),
+ filterSchema: generateFilterSchema(schema.definition),
+ };
+}
diff --git a/apps/dashboard/src/app/(dashboard)/settings/private-locations/client.tsx b/apps/dashboard/src/app/(dashboard)/settings/private-locations/client.tsx
index 8b8f4dfa5..86d4a57c3 100644
--- a/apps/dashboard/src/app/(dashboard)/settings/private-locations/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/settings/private-locations/client.tsx
@@ -85,7 +85,7 @@ export function Client() {
<BillingOverlayDescription>
Create private locations to monitor your internal services.{" "}
<Link
- href="https://www.openstatus.dev/docs/tutorial/how-to-create-private-location/"
+ href="https://www.openstatus.dev/docs/guides/how-to-create-private-location/"
rel="noreferrer"
target="_blank"
>
diff --git a/apps/dashboard/src/app/api/ai-filters/route.ts b/apps/dashboard/src/app/api/ai-filters/route.ts
new file mode 100644
index 000000000..1bbf2eb5e
--- /dev/null
+++ b/apps/dashboard/src/app/api/ai-filters/route.ts
@@ -0,0 +1,88 @@
+import { resolveChatModel } from "@openstatus/ai";
+import { monitorRegions } from "@openstatus/db/src/schema/constants";
+import {
+ createTableSchema,
+ type TableSchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+import { cookies } from "next/headers";
+import { type NextRequest, NextResponse } from "next/server";
+
+import { createLogsTableSchema } from "@/app/(dashboard)/monitors/[id]/logs/table-schema";
+import { getChatServiceContext } from "@/lib/agent-tools/context";
+import { createAIFilterHandler } from "@/lib/ai/create-ai-filter-handler";
+import { chatRateLimit } from "@/lib/rate-limit/chat";
+import { WORKSPACE_SLUG_COOKIE } from "@/lib/workspace-cookie";
+
+// Used when the request carries no usable schema. Covers every region the
+// product offers, which is a superset of any single monitor's.
+const fallbackSchema: TableSchemaDefinition = createLogsTableSchema({
+ regions: [...monitorRegions],
+ privateLocations: [],
+}).definition;
+
+/** Above this the payload is not a table schema, whatever it claims to be. */
+const MAX_SCHEMA_BYTES = 64_000;
+
+/**
+ * The client sends the schema of the table it is filtering, so the prompt and
+ * the output schema describe that monitor's regions and private locations —
+ * inferring against a generic schema silently drops both. `fromJSON` normalises
+ * and validates the untrusted JSON; anything it rejects falls back.
+ */
+function resolveSchema(raw: unknown): TableSchemaDefinition {
+ if (!raw) return fallbackSchema;
+ try {
+ if (JSON.stringify(raw).length > MAX_SCHEMA_BYTES) return fallbackSchema;
+ return createTableSchema.fromJSON(raw).definition;
+ } catch {
+ return fallbackSchema;
+ }
+}
+
+export async function POST(req: NextRequest) {
+ const workspaceSlug = (await cookies()).get(WORKSPACE_SLUG_COOKIE)?.value;
+ const ctx = await getChatServiceContext({ workspaceSlug });
+ if (!ctx || ctx.actor.type !== "user") {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ if (!ctx.workspace.limits["response-logs"]) {
+ return NextResponse.json(
+ { error: "Response logs are not enabled on this plan." },
+ { status: 403 },
+ );
+ }
+
+ const model = resolveChatModel({ plan: ctx.workspace.plan ?? "free" });
+ if (!model) {
+ return NextResponse.json(
+ { error: "AI filters are not configured on this deployment." },
+ { status: 503 },
+ );
+ }
+
+ // Same carve-out as `api/chat`: the Redis counter only guards production.
+ if (process.env.NODE_ENV === "production") {
+ const limit = await chatRateLimit({ ctx });
+ if (!limit.success) {
+ return NextResponse.json(
+ {
+ error: `Rate limit exceeded. Reset at ${new Date(limit.reset).toISOString()}`,
+ reset: limit.reset,
+ },
+ { status: 429 },
+ );
+ }
+ }
+
+ // Read from a clone: the handler consumes the original body itself.
+ let schema = fallbackSchema;
+ try {
+ const body = await req.clone().json();
+ schema = resolveSchema(body?.schema);
+ } catch {
+ // Malformed body — the handler reports it.
+ }
+
+ return createAIFilterHandler({ model, schema })(req);
+}
diff --git a/apps/dashboard/src/app/globals.css b/apps/dashboard/src/app/globals.css
index 3ecbe2c96..01323f24a 100644
--- a/apps/dashboard/src/app/globals.css
+++ b/apps/dashboard/src/app/globals.css
@@ -9,6 +9,11 @@
@theme {
--breakpoint-xs: 30rem;
+ /* Heights of the sticky app chrome. Pages that fill the viewport instead of
+ * growing the document (monitor logs) subtract both. */
+ --spacing-app-header: 3.5rem;
+ --spacing-app-tabs: 41px;
+
/* A 0.3s hold, then a 0.3s half-turn, on repeat. The mark is symmetric under
* a half turn, so every cycle ends where it visually began and the loop never
* jumps. ease-in-out because a linear turn that stops dead looks broken. */
@@ -31,6 +36,10 @@
--font-sans: var(--font-inter);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
+ --color-success: var(--success);
+ --color-warning: var(--warning);
+ --color-error: var(--destructive);
+ --color-info: var(--info);
}
@layer base {
@@ -52,4 +61,4 @@
[data-status-preview] .rounded-full {
border-radius: calc(var(--radius) * 99999999);
}
-}
\ No newline at end of file
+}
diff --git a/apps/dashboard/src/components/content/billing-overlay.tsx b/apps/dashboard/src/components/content/billing-overlay.tsx
index 7303642df..f520b046b 100644
--- a/apps/dashboard/src/components/content/billing-overlay.tsx
+++ b/apps/dashboard/src/components/content/billing-overlay.tsx
@@ -21,7 +21,7 @@ export function BillingOverlay({
return (
<div
className={cn(
- "to-background absolute inset-0 flex flex-col items-center justify-center gap-2 bg-gradient-to-b from-transparent to-50% p-2",
+ "to-background absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-gradient-to-b from-transparent to-50% p-2",
className,
)}
{...props}
diff --git a/apps/dashboard/src/components/controls-search/popover-date.tsx b/apps/dashboard/src/components/controls-search/popover-date.tsx
deleted file mode 100644
index 27bafc4cc..000000000
--- a/apps/dashboard/src/components/controls-search/popover-date.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-import { Button } from "@openstatus/ui/components/ui/button";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@openstatus/ui/components/ui/popover";
-import { endOfDay, startOfDay, subDays, subHours } from "date-fns";
-import { parseAsIsoDateTime, useQueryState } from "nuqs";
-import { useEffect, useMemo, useRef, useState } from "react";
-import type { DateRange } from "react-day-picker";
-
-import { DatePicker } from "@/components/date-picker";
-import { formatDateRange } from "@/lib/formatter";
-
-export function PopoverDate() {
- const [open, setOpen] = useState(false);
- const today = useRef(new Date());
- const [from, setFrom] = useQueryState(
- "from",
- parseAsIsoDateTime.withDefault(startOfDay(today.current)),
- );
- const [to, setTo] = useQueryState(
- "to",
- parseAsIsoDateTime.withDefault(endOfDay(today.current)),
- );
- const [range, setRange] = useState<DateRange>({ from, to });
-
- const presets = useMemo(
- () => [
- {
- id: "today",
- label: "Today",
- values: {
- from: startOfDay(today.current),
- to: endOfDay(today.current),
- },
- shortcut: "t",
- },
- {
- id: "yesterday",
- label: "Yesterday",
- values: {
- from: startOfDay(subDays(today.current, 1)),
- to: endOfDay(subDays(today.current, 1)),
- },
- shortcut: "y",
- },
- {
- id: "lastHour",
- label: "Last hour",
- values: {
- from: subHours(today.current, 1),
- to: today.current,
- },
- shortcut: "h",
- },
- {
- id: "last6Hours",
- label: "Last 6 hours",
- values: {
- from: subHours(today.current, 5),
- to: today.current,
- },
- shortcut: "s",
- },
- {
- id: "last24Hours",
- label: "Last 24 hours",
- values: {
- from: subHours(today.current, 23),
- to: today.current,
- },
- shortcut: "d",
- },
- {
- id: "last7Days",
- label: "Last 7 days",
- values: {
- from: subDays(today.current, 6),
- to: today.current,
- },
- shortcut: "w",
- },
- {
- id: "last14Days",
- label: "Last 14 days",
- values: {
- from: subDays(today.current, 13),
- to: today.current,
- },
- shortcut: "b",
- },
- ],
- [today],
- );
-
- // instead use `range` state
- const selected = presets.find((period) => {
- return (
- from.getTime() === period.values.from.getTime() &&
- to.getTime() === period.values.to.getTime()
- );
- });
-
- useEffect(() => {
- if (!open) {
- setFrom(range.from ?? null);
- setTo(range.to ?? null);
- }
- }, [open]);
-
- useEffect(() => {
- const down = (e: KeyboardEvent) => {
- if (!open) return;
-
- presets.map((preset) => {
- if (preset.shortcut === e.key) {
- setFrom(preset.values.from);
- setTo(preset.values.to);
- setRange({ from: preset.values.from, to: preset.values.to });
- }
- });
- };
- document.addEventListener("keydown", down);
- return () => document.removeEventListener("keydown", down);
- }, [presets, open, setFrom, setTo]);
-
- return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <Button variant="outline" size="sm">
- {selected?.label ?? formatDateRange(from, to)}
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-auto p-0" side="bottom" align="start">
- <DatePicker presets={presets} range={range} onSelect={setRange} />
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/apps/dashboard/src/components/data-table/response-logs/columns.tsx b/apps/dashboard/src/components/data-table/response-logs/columns.tsx
index 3173d5711..b8f575ff6 100644
--- a/apps/dashboard/src/components/data-table/response-logs/columns.tsx
+++ b/apps/dashboard/src/components/data-table/response-logs/columns.tsx
@@ -18,7 +18,7 @@ import { TableCellNumber } from "@/components/data-table/table-cell-number";
import { TableCellRegion } from "@/components/data-table/table-cell-region";
import { getStatusCodeVariant, textColors } from "@/data/status-codes";
-type ResponseLog = RouterOutputs["tinybird"]["list"]["data"][number];
+type ResponseLog = RouterOutputs["tinybird"]["get"]["data"][number];
// export const columns: ColumnDef<ResponseLog>[] =
export function getColumns(
diff --git a/apps/dashboard/src/components/data-table/response-logs/data-table-toolbar.tsx b/apps/dashboard/src/components/data-table/response-logs/data-table-toolbar.tsx
deleted file mode 100644
index 2e6459d87..000000000
--- a/apps/dashboard/src/components/data-table/response-logs/data-table-toolbar.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-"use client";
-
-import type { RouterOutputs } from "@openstatus/api";
-import { Monitor, Region, Warning, Close } from "@openstatus/icons";
-import { Button } from "@openstatus/ui/components/ui/button";
-import type { Table } from "@tanstack/react-table";
-
-import { DataTableFacetedFilter } from "@/components/ui/data-table/data-table-faceted-filter";
-import { regions } from "@/data/regions";
-import { statusCodes } from "@/data/status-codes";
-
-type ResponseLog = RouterOutputs["tinybird"]["list"]["data"][number];
-
-export interface ResponseLogsDataTableToolbarProps {
- table: Table<ResponseLog>;
-}
-
-export function ResponseLogsDataTableToolbar({
- table,
-}: ResponseLogsDataTableToolbarProps) {
- const isFiltered = table.getState().columnFilters.length > 0;
-
- return (
- <div className="flex items-center justify-between">
- <div className="flex-warp flex flex-1 flex-wrap items-center gap-2">
- {table.getColumn("status") && (
- <DataTableFacetedFilter
- column={table.getColumn("status")}
- title="Status"
- options={statusCodes.map((code) => ({
- label: code.code.toString(),
- value: code.code.toString(),
- }))}
- icon={Monitor}
- />
- )}
- {table.getColumn("region") && (
- <DataTableFacetedFilter
- column={table.getColumn("region")}
- title="Region"
- options={regions.map((region) => ({
- label: region.location,
- value: region.code,
- }))}
- icon={Region}
- />
- )}
- {table.getColumn("error") && (
- <DataTableFacetedFilter
- column={table.getColumn("error")}
- title="Error"
- options={[
- { label: "Yes", value: "true" },
- { label: "No", value: "false" },
- ]}
- icon={Warning}
- />
- )}
- {isFiltered && (
- <Button
- variant="ghost"
- onClick={() => table.resetColumnFilters()}
- className="h-8 px-2 lg:px-3"
- >
- Reset
- <Close />
- </Button>
- )}
- </div>
- {/* <DataTableViewOptions table={table} /> */}
- </div>
- );
-}
diff --git a/apps/dashboard/src/components/data-table/table-cell-region.tsx b/apps/dashboard/src/components/data-table/table-cell-region.tsx
index 9996e7a10..3f5cfc6dd 100644
--- a/apps/dashboard/src/components/data-table/table-cell-region.tsx
+++ b/apps/dashboard/src/components/data-table/table-cell-region.tsx
@@ -1,16 +1,25 @@
import type { PrivateLocation } from "@openstatus/db/src/schema";
import { getRegionInfo } from "@openstatus/regions";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui/components/ui/tooltip";
import { cn } from "@/lib/utils";
export function TableCellRegion({
value,
privateLocations,
+ variant = "location",
className,
...props
}: React.ComponentProps<"div"> & {
value: unknown;
privateLocations?: PrivateLocation[];
+ /** `"code"` trades the city name for the flag + region code, with the full name in a tooltip. */
+ variant?: "location" | "code";
}) {
if (typeof value !== "string" || value.length === 0) {
return (
@@ -23,6 +32,28 @@ export function TableCellRegion({
location: privateLocations?.find((loc) => String(loc.id) === String(value))
?.name,
});
+
+ if (variant === "code") {
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className={cn("truncate", className)} {...props}>
+ <span aria-hidden="true">{info.flag}</span>{" "}
+ <span className="font-mono">{info.code}</span>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ {info.location}{" "}
+ <span className="text-muted-foreground">({info.provider})</span>
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+ }
+
return (
<div className={cn(className)} {...props}>
{info.location}{" "}
diff --git a/apps/dashboard/src/components/nav/app-header.tsx b/apps/dashboard/src/components/nav/app-header.tsx
index a66e29d12..6e6bf639d 100644
--- a/apps/dashboard/src/components/nav/app-header.tsx
+++ b/apps/dashboard/src/components/nav/app-header.tsx
@@ -8,7 +8,7 @@ export function AppHeader({
return (
<header
className={cn(
- "bg-background sticky top-0 z-10 flex h-14 shrink-0 items-center gap-2 border-b px-2",
+ "bg-background h-app-header sticky top-0 z-10 flex shrink-0 items-center gap-2 border-b px-2",
className,
)}
{...props}
diff --git a/apps/dashboard/src/components/nav/nav-tabs.tsx b/apps/dashboard/src/components/nav/nav-tabs.tsx
index 3c9adfc9f..6650d0568 100644
--- a/apps/dashboard/src/components/nav/nav-tabs.tsx
+++ b/apps/dashboard/src/components/nav/nav-tabs.tsx
@@ -20,7 +20,7 @@ export function NavTabs({ items }: NavTabsProps) {
const normalizedPath = pathname.replace(/\/+$/, "") || "/";
return (
- <nav className="bg-background sticky top-14 z-10 h-[41px] w-full overflow-x-auto border-b px-2">
+ <nav className="bg-background top-app-header h-app-tabs sticky z-10 w-full overflow-x-auto border-b px-2">
<ul className="inline-flex h-full items-center gap-1 px-3 text-sm">
{items.map((item) => {
const normalizedHref = item.href.replace(/\/+$/, "") || "/";
diff --git a/apps/dashboard/src/components/onboarding/checks-table.tsx b/apps/dashboard/src/components/onboarding/checks-table.tsx
index 9effdba8f..14f825ab4 100644
--- a/apps/dashboard/src/components/onboarding/checks-table.tsx
+++ b/apps/dashboard/src/components/onboarding/checks-table.tsx
@@ -23,13 +23,11 @@ import { getColumns } from "@/components/data-table/response-logs/columns";
import { Sheet } from "@/components/data-table/response-logs/data-table-sheet";
import { DataTableSkeleton } from "@/components/ui/data-table/data-table-skeleton";
-// Use the wider `get`-shape so the row also satisfies the Sheet's input.
-// The column defs are typed against `list` shape, but every list field
-// is also present on `get`, so casting is safe.
+// The `get` shape, so the row also satisfies the Sheet's input.
export type OnboardingChecksRow =
RouterOutputs["tinybird"]["get"]["data"][number];
-const COLUMNS = getColumns([]) as unknown as ColumnDef<OnboardingChecksRow>[];
+const COLUMNS: ColumnDef<OnboardingChecksRow>[] = getColumns([]);
export function OnboardingChecksTable({
rows,
diff --git a/apps/dashboard/src/components/onboarding/feature-badges.tsx b/apps/dashboard/src/components/onboarding/feature-badges.tsx
index 14be8a261..e19a144c9 100644
--- a/apps/dashboard/src/components/onboarding/feature-badges.tsx
+++ b/apps/dashboard/src/components/onboarding/feature-badges.tsx
@@ -65,7 +65,7 @@ const FEATURE_CATEGORIES: { label: string; items: FeatureLinkItem[] }[] = [
},
{
name: "Private locations",
- href: `${DOCS}/tutorial/how-to-create-private-location`,
+ href: `${DOCS}/guides/how-to-create-private-location`,
icon: PrivateLocation,
external: true,
},
diff --git a/apps/dashboard/src/data/response-logs.ts b/apps/dashboard/src/data/response-logs.ts
index 608f6947b..b17cf9e56 100644
--- a/apps/dashboard/src/data/response-logs.ts
+++ b/apps/dashboard/src/data/response-logs.ts
@@ -2,11 +2,11 @@ import type { RouterOutputs } from "@openstatus/api";
import { monitorRegions } from "@openstatus/db/src/schema/constants";
import { startOfDay } from "date-fns";
-type ResponseLog = RouterOutputs["tinybird"]["list"]["data"][number];
+type ResponseLog = RouterOutputs["tinybird"]["get"]["data"][number];
const today = startOfDay(new Date());
-export const exampleLogs: ResponseLog[] = Array.from({ length: 10 }).map(
+export const exampleLogs: ResponseLog[] = Array.from({ length: 30 }).map(
(_, i) => ({
id: i.toString(),
type: "http",
@@ -22,8 +22,8 @@ export const exampleLogs: ResponseLog[] = Array.from({ length: 10 }).map(
ttfb: 40,
transfer: 50,
},
- assertions: [],
- region: monitorRegions[i],
+ assertions: "[]",
+ region: monitorRegions[i % 6],
error: false,
timestamp: today.getTime() + i * 1000 * 60,
headers: {
@@ -34,6 +34,8 @@ export const exampleLogs: ResponseLog[] = Array.from({ length: 10 }).map(
Server: "Vercel",
},
workspaceId: "1",
+ message: null,
+ body: null,
monitorId: "1",
cronTimestamp: today.getTime() + i * 1000 * 60,
trigger: "cron" as const satisfies "cron" | "api",
diff --git a/apps/dashboard/src/lib/ai/create-ai-filter-handler.ts b/apps/dashboard/src/lib/ai/create-ai-filter-handler.ts
new file mode 100644
index 000000000..a855c78bf
--- /dev/null
+++ b/apps/dashboard/src/lib/ai/create-ai-filter-handler.ts
@@ -0,0 +1,91 @@
+import { generateAIOutputSchema } from "@openstatus/ui/lib/data-table-filters/ai/output-schema";
+import { generateAIPrompt } from "@openstatus/ui/lib/data-table-filters/ai/prompt";
+import type { TableSchemaDefinition } from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+import { streamObject } from "ai";
+import type { LanguageModel } from "ai";
+
+export type AIFilterHandlerOptions = {
+ model: LanguageModel;
+ schema: TableSchemaDefinition;
+};
+
+/**
+ * Creates a POST handler that streams AI-inferred filter state from a natural language query.
+ *
+ * The consumer provides a model and table schema. The handler generates the system prompt
+ * and Zod output schema automatically, then streams the structured object response.
+ *
+ * The static schema description is cached via Anthropic's prompt caching
+ * (`cache_control: { type: "ephemeral" }`). Only the dynamic timestamp and
+ * user query are sent fresh on each request.
+ *
+ * @example
+ * ```ts
+ * import { createAnthropic } from "@ai-sdk/anthropic";
+ * import { createAIFilterHandler } from "@/lib/ai/create-ai-filter-handler";
+ * import { tableSchema } from "../table-schema";
+ *
+ * const anthropic = createAnthropic({
+ * baseURL: "https://ai-gateway.vercel.sh/v1",
+ * apiKey: process.env.AI_GATEWAY_API_KEY,
+ * });
+ *
+ * export const POST = createAIFilterHandler({
+ * model: anthropic("anthropic/claude-opus-4.5"),
+ * schema: tableSchema.definition,
+ * });
+ * ```
+ */
+export function createAIFilterHandler({
+ model,
+ schema,
+}: AIFilterHandlerOptions) {
+ // Static prompt (cacheable) — generated once, same for every request
+ const staticPrompt = generateAIPrompt(schema);
+ const outputSchema = generateAIOutputSchema(schema);
+
+ return async function POST(req: Request) {
+ const body = await req.json();
+ const query = typeof body?.query === "string" ? body.query.trim() : "";
+
+ if (!query || query.length > 500) {
+ return Response.json(
+ { error: "Invalid query: must be a non-empty string (max 500 chars)" },
+ { status: 400 },
+ );
+ }
+
+ const now = new Date().toISOString();
+
+ try {
+ const result = streamObject({
+ model,
+ schema: outputSchema,
+ messages: [
+ {
+ role: "system",
+ content: staticPrompt,
+ providerOptions: {
+ anthropic: { cacheControl: { type: "ephemeral" } },
+ },
+ },
+ {
+ role: "user",
+ content: `Current date/time: ${now}\n\nQuery: ${query}`,
+ },
+ ],
+ });
+
+ return result.toTextStreamResponse();
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : "AI filter inference failed";
+ const status =
+ error && typeof error === "object" && "statusCode" in error
+ ? (error.statusCode as number)
+ : 500;
+
+ return Response.json({ error: message }, { status });
+ }
+ };
+}
diff --git a/apps/dashboard/src/lib/react-table.d.ts b/apps/dashboard/src/lib/react-table.d.ts
new file mode 100644
index 000000000..6fd1ac4fb
--- /dev/null
+++ b/apps/dashboard/src/lib/react-table.d.ts
@@ -0,0 +1,25 @@
+import "@tanstack/react-table";
+
+declare module "@tanstack/react-table" {
+ // https://github.com/TanStack/table/issues/44#issuecomment-1377024296
+ interface TableMeta<TData extends unknown> {
+ getRowClassName?: (row: Row<TData>) => string;
+ }
+
+ interface ColumnMeta {
+ headerClassName?: string;
+ cellClassName?: string;
+ label?: string;
+ kind?: string;
+ }
+
+ interface FilterFns {
+ inDateRange?: FilterFn<any>;
+ arrSome?: FilterFn<any>;
+ }
+
+ // https://github.com/TanStack/table/discussions/4554
+ interface ColumnFiltersOptions<TData extends RowData> {
+ filterFns?: Record<string, FilterFn<TData>>;
+ }
+}
diff --git a/oxlint.config.ts b/oxlint.config.ts
index 2f56e4ef6..42c3a87cc 100644
--- a/oxlint.config.ts
+++ b/oxlint.config.ts
@@ -32,6 +32,12 @@ export default defineConfig({
ignorePatterns: [
"packages/ui/src/components/*.ts",
"packages/ui/src/components/*.tsx",
+ // Vendored from the data-table-filters shadcn registry — reformatting or
+ // hand-patching these makes the next `shadcn add` a merge conflict.
+ "packages/ui/src/components/data-table-filters/**",
+ "packages/ui/src/lib/data-table-filters/**",
+ "apps/dashboard/src/lib/react-table.d.ts",
+ "packages/ui/src/react-table.d.ts",
"apps/dashboard/src/scripts/*.ts",
"packages/proto/gen/**",
"**/*_pb.ts",
diff --git a/packages/api/src/router/tinybird/index.test.ts b/packages/api/src/router/tinybird/index.test.ts
index 668055290..bd16f0471 100644
--- a/packages/api/src/router/tinybird/index.test.ts
+++ b/packages/api/src/router/tinybird/index.test.ts
@@ -79,3 +79,66 @@ test("tinybird.metricsTimingPhases succeeds for own workspace monitor", async ()
});
expect(result).toBeDefined();
});
+
+// ─── listInfinite / listFacets ───────────────────────────────────
+
+test("tinybird.listInfinite rejects monitor from another workspace", async () => {
+ const caller = callerForWorkspace(1);
+
+ try {
+ // Monitor 5 belongs to workspace 3
+ await caller.tinybird.listInfinite({ monitorId: 5, limit: 50 });
+ throw new Error("Should have thrown");
+ } catch (e) {
+ expect(e).toBeInstanceOf(TRPCError);
+ expect((e as TRPCError).code).toBe("NOT_FOUND");
+ }
+});
+
+test("tinybird.listInfinite succeeds for own workspace monitor", async () => {
+ const caller = callerForWorkspace(1);
+
+ const result = await caller.tinybird.listInfinite({
+ monitorId: 1,
+ limit: 50,
+ });
+ expect(result).toEqual({ data: [], nextCursor: null, prevCursor: null });
+});
+
+test("tinybird.listFacets rejects monitor from another workspace", async () => {
+ const caller = callerForWorkspace(1);
+
+ try {
+ await caller.tinybird.listFacets({ monitorId: 5 });
+ throw new Error("Should have thrown");
+ } catch (e) {
+ expect(e).toBeInstanceOf(TRPCError);
+ expect((e as TRPCError).code).toBe("NOT_FOUND");
+ }
+});
+
+test("tinybird.listFacets succeeds for own workspace monitor", async () => {
+ const caller = callerForWorkspace(1);
+
+ const result = await caller.tinybird.listFacets({ monitorId: 1 });
+ expect(result).toEqual({
+ totalRowCount: 0,
+ filterRowCount: 0,
+ facets: {},
+ });
+});
+
+test("tinybird.listInfinite accepts React Query's own paging direction", async () => {
+ const caller = callerForWorkspace(1);
+
+ // `@trpc/tanstack-react-query` puts `direction: "forward" | "backward"` on
+ // every infinite-query input; rejecting it breaks the very first page load.
+ for (const direction of ["forward", "backward"] as const) {
+ const result = await caller.tinybird.listInfinite({
+ monitorId: 1,
+ limit: 50,
+ direction,
+ });
+ expect(result).toEqual({ data: [], nextCursor: null, prevCursor: null });
+ }
+});
diff --git a/packages/api/src/router/tinybird/index.ts b/packages/api/src/router/tinybird/index.ts
index b9043e3dd..e9928a4f2 100644
--- a/packages/api/src/router/tinybird/index.ts
+++ b/packages/api/src/router/tinybird/index.ts
@@ -1,12 +1,17 @@
import { type SQL, and, db, eq, inArray } from "@openstatus/db";
import { monitor } from "@openstatus/db/src/schema";
import { monitorRegions } from "@openstatus/db/src/schema/constants";
+import {
+ getResponseLogFacets,
+ listResponseLogsInfinite,
+ ResponseLogFilters,
+} from "@openstatus/services/monitor";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
+import { toServiceCtx, toTRPCError } from "../../service-adapter";
import { tb } from "../../tb";
import { createTRPCRouter, protectedProcedure } from "../../trpc";
-import { calculatePeriod } from "./utils";
const periods = ["1d", "7d", "14d", "30d", "90d"] as const;
const types = ["http", "tcp", "dns", "icmp", "grpc"] as const;
@@ -47,39 +52,6 @@ export function getWorkspace30dProcedure(type: Type) {
if (type === "grpc") return tb.grpcWorkspace30d;
return tb.tcpWorkspace30d;
}
-// Helper functions to get the right procedure based on period and type
-export function getListProcedure(period: Period, type: Type) {
- switch (period) {
- case "1d":
- if (type === "http") return tb.httpListDaily;
- if (type === "tcp") return tb.tcpListDaily;
- if (type === "dns") return tb.dnsListBiweekly;
- if (type === "icmp") return tb.icmpListDaily;
- if (type === "grpc") return tb.grpcListDaily;
- throw new TRPCError({ code: "NOT_FOUND", message: "Invalid type" });
- case "7d":
- if (type === "http") return tb.httpListWeekly;
- if (type === "tcp") return tb.tcpListWeekly;
- if (type === "dns") return tb.dnsListBiweekly;
- if (type === "icmp") return tb.icmpListWeekly;
- if (type === "grpc") return tb.grpcListWeekly;
- throw new TRPCError({ code: "NOT_FOUND", message: "Invalid type" });
- case "14d":
- if (type === "http") return tb.httpListBiweekly;
- if (type === "tcp") return tb.tcpListBiweekly;
- if (type === "dns") return tb.dnsListBiweekly;
- if (type === "icmp") return tb.icmpListBiweekly;
- if (type === "grpc") return tb.grpcListBiweekly;
- throw new TRPCError({ code: "NOT_FOUND", message: "Invalid type" });
- default:
- if (type === "http") return tb.httpListDaily;
- if (type === "tcp") return tb.tcpListDaily;
- if (type === "dns") return tb.dnsListBiweekly;
- if (type === "icmp") return tb.icmpListDaily;
- if (type === "grpc") return tb.grpcListDaily;
- throw new TRPCError({ code: "NOT_FOUND", message: "Invalid type" });
- }
-}
export function getMetricsProcedure(period: Period, type: Type) {
switch (period) {
@@ -311,45 +283,60 @@ export function getTimingPhasesProcedure(period: Period, type: Type) {
}
}
-export const tinybirdRouter = createTRPCRouter({
- list: protectedProcedure
- .input(
- z.object({
- monitorId: z.string(),
- region: z.enum(monitorRegions).or(z.string()).optional(),
- cronTimestamp: z.int().optional(),
- from: z.coerce.date().optional(),
- to: z.coerce.date().optional(),
- }),
- )
- .query(async (opts) => {
- const whereConditions: SQL[] = [
- eq(monitor.id, Number.parseInt(opts.input.monitorId)),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ];
+const listInfiniteInput = ResponseLogFilters.extend({
+ monitorId: z.coerce.number().int(),
+ from: z.coerce.date().optional(),
+ to: z.coerce.date().optional(),
+ cursor: z.int().optional(),
+ // `@trpc/tanstack-react-query` puts React Query's own paging direction on
+ // every infinite-query input, so this field is theirs — the service's
+ // `next`/`prev` vocabulary is mapped below.
+ direction: z.enum(["forward", "backward"]).optional(),
+ limit: z.int().min(1).max(100).prefault(50),
+});
- const _monitor = await db.query.monitor.findFirst({
- where: and(...whereConditions),
- });
+const listFacetsInput = ResponseLogFilters.extend({
+ monitorId: z.coerce.number().int(),
+ from: z.coerce.date().optional(),
+ to: z.coerce.date().optional(),
+});
- if (!_monitor) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Monitor not found",
+export const tinybirdRouter = createTRPCRouter({
+ listInfinite: protectedProcedure
+ .input(listInfiniteInput)
+ .query(async ({ ctx, input }) => {
+ try {
+ const { from, to, direction, ...rest } = input;
+ return await listResponseLogsInfinite({
+ ctx: toServiceCtx(ctx),
+ input: {
+ ...rest,
+ fromTimestamp: from?.getTime(),
+ toTimestamp: to?.getTime(),
+ direction: direction === "backward" ? "prev" : "next",
+ },
});
+ } catch (err) {
+ toTRPCError(err);
}
+ }),
- const period = calculatePeriod(opts.input.from, opts.input.to);
-
- const procedure = getListProcedure(
- period,
- _monitor.jobType as "http" | "tcp" | "dns" | "icmp" | "grpc",
- );
- return await procedure({
- ...opts.input,
- fromDate: opts.input.from?.getTime() ?? undefined,
- toDate: opts.input.to?.getTime(),
- });
+ listFacets: protectedProcedure
+ .input(listFacetsInput)
+ .query(async ({ ctx, input }) => {
+ try {
+ const { from, to, ...rest } = input;
+ return await getResponseLogFacets({
+ ctx: toServiceCtx(ctx),
+ input: {
+ ...rest,
+ fromTimestamp: from?.getTime(),
+ toTimestamp: to?.getTime(),
+ },
+ });
+ } catch (err) {
+ toTRPCError(err);
+ }
}),
uptime: protectedProcedure
diff --git a/packages/api/src/router/tinybird/utils.ts b/packages/api/src/router/tinybird/utils.ts
deleted file mode 100644
index b73bc2992..000000000
--- a/packages/api/src/router/tinybird/utils.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export function calculatePeriod(from: Date | undefined, _to: Date | undefined) {
- const today = new Date();
- const diffTime = Math.abs(today.getTime() - (from?.getTime() ?? 0));
- const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
- if (diffDays <= 1) return "1d";
- if (diffDays <= 7) return "7d";
- if (diffDays <= 14) return "14d";
- return "14d";
-}
diff --git a/packages/services/src/monitor/__tests__/reads.test.ts b/packages/services/src/monitor/__tests__/reads.test.ts
index bc4d24d85..61416d7dd 100644
--- a/packages/services/src/monitor/__tests__/reads.test.ts
+++ b/packages/services/src/monitor/__tests__/reads.test.ts
@@ -21,6 +21,7 @@ import { getMonitorStatus } from "../get-monitor-status";
import { getMonitorSummary } from "../get-monitor-summary";
import { getResponseLog } from "../get-response-log";
import { listResponseLogs } from "../list-response-logs";
+import { listResponseLogsInfinite } from "../list-response-logs-infinite";
import { getPrivateLocationIdsByMonitor } from "../private-locations";
const TEST_PREFIX = "svc-monitor-reads-test";
@@ -667,3 +668,330 @@ describe("getPrivateLocationIdsByMonitor", () => {
});
});
});
+
+describe("listResponseLogsInfinite", () => {
+ const REGIONS = ["iad", "ams", "gru", "syd", "sin"];
+
+ /** One `tb` stand-in per pipe getter, recording the params it was called with. */
+ function makeFakeTb(rows: Record<string, unknown>[]) {
+ const calls: Record<string, Record<string, unknown>> = {};
+ const record = (name: string) => (params: Record<string, unknown>) => {
+ calls[name] = params;
+ return Promise.resolve({ data: rows });
+ };
+ const tb = {
+ httpListV2Daily: record("httpListV2Daily"),
+ httpListV2Weekly: record("httpListV2Weekly"),
+ httpListV2Biweekly: record("httpListV2Biweekly"),
+ tcpListV2Daily: record("tcpListV2Daily"),
+ tcpListV2Weekly: record("tcpListV2Weekly"),
+ tcpListV2Biweekly: record("tcpListV2Biweekly"),
+ icmpListV2Daily: record("icmpListV2Daily"),
+ icmpListV2Weekly: record("icmpListV2Weekly"),
+ icmpListV2Biweekly: record("icmpListV2Biweekly"),
+ dnsListV2Biweekly: record("dnsListV2Biweekly"),
+ grpcListV2Biweekly: record("grpcListV2Biweekly"),
+ } as unknown as NonNullable<ServiceContext["tb"]>;
+ return { tb, calls };
+ }
+
+ function httpRows(ticks: number, perTick: number) {
+ const rows: Record<string, unknown>[] = [];
+ for (let tick = 0; tick < ticks; tick++) {
+ const cronTimestamp = 1_700_000_000_000 - tick * 30_000;
+ for (let i = 0; i < perTick; i++) {
+ rows.push({
+ id: `log-${tick}-${i}`,
+ monitorId: "1",
+ region: REGIONS[i % REGIONS.length],
+ requestStatus: "success",
+ trigger: "cron",
+ statusCode: 200,
+ latency: 100,
+ cronTimestamp,
+ timestamp: cronTimestamp,
+ timing: null,
+ });
+ }
+ }
+ return rows;
+ }
+
+ /** Like `makeFakeTb`, but honours the `limit` the pipe was asked for. */
+ function makeLimitedFakeTb(rows: Record<string, unknown>[]) {
+ const limits: number[] = [];
+ const tb = {
+ httpListV2Biweekly: (params: Record<string, unknown>) => {
+ const limit = Number(params.limit);
+ limits.push(limit);
+ return Promise.resolve({ data: rows.slice(0, limit) });
+ },
+ } as unknown as NonNullable<ServiceContext["tb"]>;
+ return { tb, limits };
+ }
+
+ test("throws ForbiddenError when plan disables response-logs", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ listResponseLogsInfinite({
+ ctx: { ...freeCtx, db: tx },
+ input: { monitorId: 999_999, limit: 50, direction: "next" },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+ });
+
+ test("throws ValidationError for an unsupported job type", async () => {
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-udp-infinite`,
+ jobType: "udp",
+ url: "1.1.1.1",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ regions: ["ams"],
+ },
+ });
+ await expect(
+ listResponseLogsInfinite({
+ ctx: { ...teamCtx, db: tx, tb: makeFakeTb([]).tb },
+ input: { monitorId: row.id, limit: 50, direction: "next" },
+ }),
+ ).rejects.toBeInstanceOf(ValidationError);
+ });
+ });
+
+ test("overfetches by the location count and trims to a whole tick", async () => {
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-http-infinite`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ regions: REGIONS,
+ },
+ });
+ // 53 rows = ten full five-region ticks plus a partial eleventh.
+ const rows = httpRows(11, 5).slice(0, 53);
+ const { tb, calls } = makeFakeTb(rows);
+
+ const result = await listResponseLogsInfinite({
+ ctx: { ...teamCtx, db: tx, tb },
+ input: { monitorId: row.id, limit: 50, direction: "next" },
+ });
+
+ expect(calls.httpListV2Biweekly?.limit).toBe(55);
+ expect(calls.httpListV2Biweekly?.monitorId).toBe(String(row.id));
+ expect(result.data.length).toBe(50);
+ expect(result.nextCursor).toBe(
+ Math.min(...result.data.map((log) => log.cronTimestamp)),
+ );
+ });
+ });
+
+ test("widens the fetch when one tick fills the ceiling", async () => {
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-http-wide-tick`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ regions: REGIONS,
+ },
+ });
+ // Ten rows on the newest tick: the MV is a plain MergeTree, so a retry
+ // can land more rows on a tick than the monitor has locations, and the
+ // location-based overfetch then no longer spans it.
+ const rows = [...httpRows(1, 10), ...httpRows(2, 5).slice(5)];
+ const { tb, limits } = makeLimitedFakeTb(rows);
+
+ const result = await listResponseLogsInfinite({
+ ctx: { ...teamCtx, db: tx, tb },
+ input: { monitorId: row.id, limit: 2, direction: "next" },
+ });
+
+ // 2 + 5 locations only reaches into the tick; the retry doubles it.
+ expect(limits).toEqual([7, 14]);
+ // The tick comes back whole, so the exclusive cursor skips nothing.
+ expect(result.data.length).toBe(10);
+ expect(new Set(result.data.map((log) => log.cronTimestamp)).size).toBe(1);
+ expect(result.nextCursor).toBe(result.data[0].cronTimestamp);
+ });
+ });
+
+ test("routes tcp monitors to the tcp pipe with null http columns", async () => {
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-tcp-infinite`,
+ jobType: "tcp",
+ url: "example.com:443",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ regions: ["ams"],
+ },
+ });
+ const { tb, calls } = makeFakeTb([
+ {
+ id: "tcp-1",
+ monitorId: String(row.id),
+ region: "ams",
+ requestStatus: "success",
+ trigger: "cron",
+ latency: 12,
+ cronTimestamp: 1_700_000_000_000,
+ timestamp: 1_700_000_000_000,
+ },
+ ]);
+
+ const result = await listResponseLogsInfinite({
+ ctx: { ...teamCtx, db: tx, tb },
+ input: { monitorId: row.id, limit: 50, direction: "next" },
+ });
+
+ expect(calls.tcpListV2Biweekly).toBeDefined();
+ expect(calls.httpListV2Biweekly).toBeUndefined();
+ expect(result.data[0].statusCode).toBe(null);
+ expect(result.data[0].timing).toBe(null);
+ expect(result.nextCursor).toBe(null);
+ });
+ });
+
+ test("routes icmp monitors to the icmp pipe", async () => {
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-icmp-infinite`,
+ jobType: "icmp",
+ url: "1.1.1.1",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ regions: ["ams"],
+ },
+ });
+ const { tb, calls } = makeFakeTb([
+ {
+ id: "icmp-1",
+ monitorId: String(row.id),
+ region: "ams",
+ requestStatus: "success",
+ trigger: "cron",
+ latency: 12,
+ cronTimestamp: 1_700_000_000_000,
+ timestamp: 1_700_000_000_000,
+ },
+ ]);
+
+ const result = await listResponseLogsInfinite({
+ ctx: { ...teamCtx, db: tx, tb },
+ input: { monitorId: row.id, limit: 50, direction: "next" },
+ });
+
+ expect(calls.icmpListV2Biweekly).toBeDefined();
+ expect(calls.tcpListV2Biweekly).toBeUndefined();
+ expect(result.data[0].statusCode).toBe(null);
+ expect(result.data[0].timing).toBe(null);
+ expect(result.nextCursor).toBe(null);
+ });
+ });
+
+ test("routes grpc monitors to the grpc pipe, keeping its phase timings", async () => {
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-grpc-infinite`,
+ jobType: "grpc",
+ url: "example.com:443",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ regions: ["ams"],
+ },
+ });
+ const timing = { dns: 1, connect: 2, tls: 3, ttfb: 4, transfer: 5 };
+ const { tb, calls } = makeFakeTb([
+ {
+ id: "grpc-1",
+ monitorId: String(row.id),
+ region: "ams",
+ requestStatus: "success",
+ trigger: "cron",
+ latency: 12,
+ cronTimestamp: 1_700_000_000_000,
+ timestamp: 1_700_000_000_000,
+ timing,
+ },
+ ]);
+
+ const result = await listResponseLogsInfinite({
+ ctx: { ...teamCtx, db: tx, tb },
+ input: { monitorId: row.id, limit: 50, direction: "next" },
+ });
+
+ expect(calls.grpcListV2Biweekly).toBeDefined();
+ expect(calls.httpListV2Biweekly).toBeUndefined();
+ // gRPC has no HTTP status code, but it does carry HTTP's phase shape.
+ expect(result.data[0].statusCode).toBe(null);
+ expect(result.data[0].timing).toEqual(timing);
+ expect(result.nextCursor).toBe(null);
+ });
+ });
+
+ test("routes dns monitors to the dns pipe", async () => {
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-dns-infinite`,
+ jobType: "dns",
+ url: "example.com",
+ method: "GET",
+ headers: [],
+ assertions: [
+ {
+ version: "v1",
+ type: "dnsRecord",
+ key: "A",
+ compare: "eq",
+ target: "1.1.1.1",
+ },
+ ],
+ active: false,
+ regions: ["ams"],
+ },
+ });
+ const { tb, calls } = makeFakeTb([]);
+
+ const result = await listResponseLogsInfinite({
+ ctx: { ...teamCtx, db: tx, tb },
+ input: { monitorId: row.id, limit: 50, direction: "next" },
+ });
+
+ expect(calls.dnsListV2Biweekly).toBeDefined();
+ expect(result.data).toEqual([]);
+ expect(result.nextCursor).toBe(null);
+ });
+ });
+});
diff --git a/packages/services/src/monitor/__tests__/response-logs-cursor.test.ts b/packages/services/src/monitor/__tests__/response-logs-cursor.test.ts
new file mode 100644
index 000000000..3432605b0
--- /dev/null
+++ b/packages/services/src/monitor/__tests__/response-logs-cursor.test.ts
@@ -0,0 +1,196 @@
+import { expect } from "@std/expect";
+import { describe, test } from "@std/testing/bdd";
+
+import {
+ selectWindow,
+ toPipeParams,
+ trimToTick,
+} from "../response-logs-cursor";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** Expand `[tick, rowsInTick]` pairs into rows, in the order given. */
+function rowsOf(ticks: [number, number][]) {
+ return ticks.flatMap(([cronTimestamp, count]) =>
+ Array.from({ length: count }, () => ({ cronTimestamp })),
+ );
+}
+
+describe("selectWindow", () => {
+ const now = 1_700_000_000_000;
+
+ test("falls back to the widest view when the range is open-ended", () => {
+ expect(selectWindow(undefined, undefined, now)).toBe("14d");
+ });
+
+ test("picks the view by how old the oldest requested row is", () => {
+ expect(selectWindow(now - DAY_MS, now, now)).toBe("1d");
+ expect(selectWindow(now - DAY_MS - 1, now, now)).toBe("7d");
+ expect(selectWindow(now - 7 * DAY_MS, now, now)).toBe("7d");
+ expect(selectWindow(now - 7 * DAY_MS - 1, now, now)).toBe("14d");
+ expect(selectWindow(now - 14 * DAY_MS, now, now)).toBe("14d");
+ });
+
+ test("keeps an expired short range on a view that still holds it", () => {
+ // A one-day span that ended a week ago has aged out of the 1 d view.
+ expect(selectWindow(now - 9 * DAY_MS, now - 8 * DAY_MS, now)).toBe("14d");
+ });
+});
+
+describe("toPipeParams", () => {
+ test("drops absent and empty filters", () => {
+ expect(
+ toPipeParams({
+ regions: [],
+ status: undefined,
+ trigger: undefined,
+ statusCodes: undefined,
+ latencyMin: undefined,
+ latencyMax: undefined,
+ }),
+ ).toEqual({});
+ });
+
+ test("keeps every filter that carries a value", () => {
+ expect(
+ toPipeParams({
+ regions: ["ams"],
+ status: ["error"],
+ trigger: ["cron"],
+ statusCodes: [500],
+ latencyMin: 0,
+ latencyMax: 100,
+ }),
+ ).toEqual({
+ regions: ["ams"],
+ status: ["error"],
+ trigger: ["cron"],
+ statusCodes: [500],
+ latencyMin: 0,
+ latencyMax: 100,
+ });
+ });
+});
+
+describe("trimToTick", () => {
+ test("returns null cursors for an empty page", () => {
+ expect(
+ trimToTick({
+ rows: [],
+ limit: 50,
+ fetchLimit: 55,
+ direction: "next",
+ hasCursor: false,
+ }),
+ ).toEqual({
+ rows: [],
+ nextCursor: null,
+ prevCursor: null,
+ truncatedTick: false,
+ });
+ });
+
+ test("stops on a clean tick boundary", () => {
+ const result = trimToTick({
+ rows: rowsOf([
+ [300, 2],
+ [200, 2],
+ [100, 2],
+ ]),
+ limit: 4,
+ fetchLimit: 6,
+ direction: "next",
+ hasCursor: false,
+ });
+ expect(result.rows.length).toBe(4);
+ expect(result.nextCursor).toBe(200);
+ expect(result.prevCursor).toBe(null);
+ });
+
+ test("drops a trailing tick the pipe's own LIMIT may have cut", () => {
+ const result = trimToTick({
+ rows: rowsOf([
+ [300, 2],
+ [200, 2],
+ ]),
+ limit: 4,
+ fetchLimit: 4,
+ direction: "next",
+ hasCursor: false,
+ });
+ expect(result.rows.length).toBe(2);
+ expect(result.nextCursor).toBe(300);
+ expect(result.truncatedTick).toBe(false);
+ });
+
+ test("returns a tick wider than the page size whole", () => {
+ const result = trimToTick({
+ rows: rowsOf([[300, 4]]),
+ limit: 2,
+ fetchLimit: 6,
+ direction: "next",
+ hasCursor: false,
+ });
+ expect(result.rows.length).toBe(4);
+ expect(result.truncatedTick).toBe(false);
+ // Short of the ceiling, so the tick is whole and the source is drained.
+ expect(result.nextCursor).toBe(null);
+ });
+
+ test("flags a lone tick that filled the fetch ceiling as truncated", () => {
+ // The pipe may have cut this tick, and there is no earlier tick to drop
+ // back to; paging past its (exclusive) cursor would lose the remainder.
+ const result = trimToTick({
+ rows: rowsOf([[300, 4]]),
+ limit: 2,
+ fetchLimit: 4,
+ direction: "next",
+ hasCursor: false,
+ });
+ expect(result.truncatedTick).toBe(true);
+ });
+
+ test("reports no next page when the source ran dry", () => {
+ const result = trimToTick({
+ rows: rowsOf([[300, 2]]),
+ limit: 4,
+ fetchLimit: 6,
+ direction: "next",
+ hasCursor: false,
+ });
+ expect(result.rows.length).toBe(2);
+ expect(result.nextCursor).toBe(null);
+ expect(result.prevCursor).toBe(null);
+ });
+
+ test("only offers a page back once the request came from a cursor", () => {
+ const args = {
+ rows: rowsOf([
+ [300, 2],
+ [200, 2],
+ ]),
+ limit: 4,
+ fetchLimit: 6,
+ direction: "next" as const,
+ };
+ expect(trimToTick({ ...args, hasCursor: false }).prevCursor).toBe(null);
+ expect(trimToTick({ ...args, hasCursor: true }).prevCursor).toBe(300);
+ });
+
+ test("walks the other way for the prev direction", () => {
+ const result = trimToTick({
+ rows: rowsOf([
+ [100, 2],
+ [200, 2],
+ [300, 2],
+ ]),
+ limit: 4,
+ fetchLimit: 6,
+ direction: "prev",
+ hasCursor: true,
+ });
+ expect(result.rows.length).toBe(4);
+ expect(result.prevCursor).toBe(200);
+ expect(result.nextCursor).toBe(100);
+ });
+});
diff --git a/packages/services/src/monitor/get-response-log-facets.ts b/packages/services/src/monitor/get-response-log-facets.ts
new file mode 100644
index 000000000..73050f240
--- /dev/null
+++ b/packages/services/src/monitor/get-response-log-facets.ts
@@ -0,0 +1,114 @@
+import { db as defaultDb } from "@openstatus/db";
+
+import { type ServiceContext, defaultTb } from "../context";
+import { ForbiddenError, ValidationError } from "../errors";
+import { getMonitorInWorkspace } from "./internal";
+import { toPipeParams } from "./response-logs-cursor";
+import { GetResponseLogFacetsInput } from "./schemas";
+
+/** Marker the facet pipes use for the rows that carry the window summary. */
+const SUMMARY_FIELD = "__summary";
+
+export type ResponseLogFacet = {
+ rows: { value: string; total: number }[];
+ total: number;
+ min?: number;
+ max?: number;
+};
+
+export type GetResponseLogFacetsResult = {
+ totalRowCount: number;
+ filterRowCount: number;
+ facets: Record<string, ResponseLogFacet>;
+};
+
+export async function getResponseLogFacets(args: {
+ ctx: ServiceContext;
+ input: GetResponseLogFacetsInput;
+}): Promise<GetResponseLogFacetsResult> {
+ const { ctx } = args;
+ const input = GetResponseLogFacetsInput.parse(args.input);
+ if (!ctx.workspace.limits["response-logs"]) {
+ throw new ForbiddenError("Response logs are not enabled on this plan.");
+ }
+ const db = ctx.db ?? defaultDb;
+
+ const record = await getMonitorInWorkspace({
+ tx: db,
+ id: input.monitorId,
+ workspaceId: ctx.workspace.id,
+ });
+ const jobType = record.jobType;
+ if (
+ jobType !== "http" &&
+ jobType !== "tcp" &&
+ jobType !== "dns" &&
+ jobType !== "icmp" &&
+ jobType !== "grpc"
+ ) {
+ throw new ValidationError(
+ `getResponseLogFacets only supports HTTP, TCP, DNS, ICMP and gRPC monitors (got '${jobType}').`,
+ );
+ }
+
+ const tb = ctx.tb ?? defaultTb;
+ const getter =
+ jobType === "http"
+ ? tb.httpListFacets
+ : jobType === "tcp"
+ ? tb.tcpListFacets
+ : jobType === "icmp"
+ ? tb.icmpListFacets
+ : jobType === "grpc"
+ ? tb.grpcListFacets
+ : tb.dnsListFacets;
+
+ const result = await getter({
+ monitorId: String(record.id),
+ fromDate: input.fromTimestamp,
+ toDate: input.toTimestamp,
+ ...toPipeParams(input),
+ });
+
+ const facets: Record<string, ResponseLogFacet> = {};
+ const summary = new Map<string, number>();
+
+ for (const row of result.data) {
+ if (row.field === SUMMARY_FIELD) {
+ summary.set(row.value, row.count);
+ continue;
+ }
+ const facet = (facets[row.field] ??= { rows: [], total: 0 });
+ facet.rows.push({ value: row.value, total: row.count });
+ facet.total += row.count;
+ }
+
+ for (const facet of Object.values(facets)) {
+ facet.rows.sort((a, b) => b.total - a.total);
+ }
+
+ const totalRowCount = summary.get("total") ?? 0;
+ const latencyMin = summary.get("latencyMin");
+ const latencyMax = summary.get("latencyMax");
+ // `min()`/`max()` have no GROUP BY, so an empty window still returns a row —
+ // holding 0. Reporting that as the bounds collapses the slider to [0, 0] and
+ // every range the user then types is clamped to it, so leave the facet out
+ // and let the column's declared bounds stand.
+ if (
+ totalRowCount > 0 &&
+ (latencyMin !== undefined || latencyMax !== undefined)
+ ) {
+ facets.latency = {
+ rows: [],
+ total: 0,
+ min: latencyMin ?? 0,
+ max: latencyMax ?? 0,
+ };
+ }
+
+ return {
+ totalRowCount,
+ filterRowCount: summary.get("filtered") ?? 0,
+ facets,
+ };
+}
diff --git a/packages/services/src/monitor/index.ts b/packages/services/src/monitor/index.ts
index 17f2ecd53..64b350de3 100644
--- a/packages/services/src/monitor/index.ts
+++ b/packages/services/src/monitor/index.ts
@@ -12,12 +12,27 @@ export {
type GetMonitorSummaryResult,
} from "./get-monitor-summary";
export { getResponseLog, type ResponseLogDetail } from "./get-response-log";
+export {
+ getResponseLogFacets,
+ type GetResponseLogFacetsResult,
+ type ResponseLogFacet,
+} from "./get-response-log-facets";
export { getPrivateLocationIdsByMonitor } from "./private-locations";
export {
listResponseLogs,
type ListResponseLogsResult,
type ResponseLogListItem,
} from "./list-response-logs";
+export {
+ listResponseLogsInfinite,
+ type ListResponseLogsInfiniteResult,
+} from "./list-response-logs-infinite";
+export {
+ type ResponseLogWindow,
+ selectWindow,
+ toPipeParams,
+ trimToTick,
+} from "./response-logs-cursor";
export {
getMonitor,
type ListMonitorsResult,
@@ -61,13 +76,16 @@ export {
GetMonitorStatusInput,
GetMonitorSummaryInput,
GetPrivateLocationIdsByMonitorInput,
+ GetResponseLogFacetsInput,
GetResponseLogInput,
grpcTlsModes,
ListMonitorsInput,
+ ListResponseLogsInfiniteInput,
ListResponseLogsInput,
monitorJobTypes,
monitorMethods,
monitorPeriodicity,
+ ResponseLogFilters,
type MonitorTimeRange,
monitorTimeRange,
TriggerMonitorInput,
diff --git a/packages/services/src/monitor/list-response-logs-infinite.ts b/packages/services/src/monitor/list-response-logs-infinite.ts
new file mode 100644
index 000000000..2c57fddb9
--- /dev/null
+++ b/packages/services/src/monitor/list-response-logs-infinite.ts
@@ -0,0 +1,209 @@
+import { db as defaultDb } from "@openstatus/db";
+import { selectMonitorSchema } from "@openstatus/db/src/schema";
+
+import { type ServiceContext, defaultTb } from "../context";
+import { ForbiddenError, ValidationError } from "../errors";
+import { getMonitorInWorkspace } from "./internal";
+import type { ResponseLogListItem } from "./list-response-logs";
+import { getPrivateLocationIdsByMonitor } from "./private-locations";
+import { selectWindow, toPipeParams, trimToTick } from "./response-logs-cursor";
+import { ListResponseLogsInfiniteInput } from "./schemas";
+
+/** The v2 list pipes cap their own `limit` parameter here. */
+const MAX_FETCH_LIMIT = 1000;
+
+export type ListResponseLogsInfiniteResult = {
+ data: ResponseLogListItem[];
+ nextCursor: number | null;
+ prevCursor: number | null;
+};
+
+type BaseRow = {
+ id: string | null;
+ monitorId: string;
+ region: string;
+ requestStatus: "success" | "error" | "degraded" | null;
+ trigger: "cron" | "api" | null;
+ latency: number;
+ cronTimestamp: number;
+ timestamp: number;
+};
+
+function toListItem(
+ log: BaseRow,
+ extra: Pick<ResponseLogListItem, "statusCode" | "timing">,
+): ResponseLogListItem {
+ return {
+ id: log.id ?? null,
+ monitorId: log.monitorId,
+ region: log.region,
+ requestStatus: log.requestStatus ?? null,
+ trigger: log.trigger ?? null,
+ latency: log.latency,
+ cronTimestamp: log.cronTimestamp,
+ timestamp: log.timestamp,
+ ...extra,
+ };
+}
+
+export async function listResponseLogsInfinite(args: {
+ ctx: ServiceContext;
+ input: ListResponseLogsInfiniteInput;
+}): Promise<ListResponseLogsInfiniteResult> {
+ const { ctx } = args;
+ const input = ListResponseLogsInfiniteInput.parse(args.input);
+ if (!ctx.workspace.limits["response-logs"]) {
+ throw new ForbiddenError("Response logs are not enabled on this plan.");
+ }
+ const db = ctx.db ?? defaultDb;
+
+ const record = await getMonitorInWorkspace({
+ tx: db,
+ id: input.monitorId,
+ workspaceId: ctx.workspace.id,
+ });
+ const jobType = record.jobType;
+ if (
+ jobType !== "http" &&
+ jobType !== "tcp" &&
+ jobType !== "dns" &&
+ jobType !== "icmp" &&
+ jobType !== "grpc"
+ ) {
+ throw new ValidationError(
+ `listResponseLogsInfinite only supports HTTP, TCP, DNS, ICMP and gRPC monitors (got '${jobType}').`,
+ );
+ }
+
+ const privateLocations = await getPrivateLocationIdsByMonitor({
+ ctx,
+ input: { monitorIds: [record.id] },
+ });
+ // One cron tick emits one row per location, so overfetching by the location
+ // count is what lets `trimToTick` see where the trailing tick ends.
+ const overfetch =
+ selectMonitorSchema.parse(record).regions.length +
+ (privateLocations.get(record.id)?.length ?? 0);
+
+ const tb = ctx.tb ?? defaultTb;
+ const window = selectWindow(
+ input.fromTimestamp,
+ input.toTimestamp,
+ Date.now(),
+ );
+ const baseParams = {
+ monitorId: String(record.id),
+ fromDate: input.fromTimestamp,
+ toDate: input.toTimestamp,
+ cursor: input.cursor,
+ direction: input.direction,
+ ...toPipeParams(input),
+ };
+
+ async function fetchRows(limit: number): Promise<ResponseLogListItem[]> {
+ const params = { ...baseParams, limit };
+ let rows: ResponseLogListItem[];
+ if (jobType === "http") {
+ const getter =
+ window === "1d"
+ ? tb.httpListV2Daily
+ : window === "7d"
+ ? tb.httpListV2Weekly
+ : tb.httpListV2Biweekly;
+ const result = await getter(params);
+ rows = result.data.map((log) =>
+ toListItem(log, {
+ statusCode: log.statusCode ?? null,
+ timing: log.timing
+ ? {
+ dns: log.timing.dns,
+ connect: log.timing.connect,
+ tls: log.timing.tls,
+ ttfb: log.timing.ttfb,
+ transfer: log.timing.transfer,
+ }
+ : null,
+ }),
+ );
+ } else if (jobType === "tcp") {
+ const getter =
+ window === "1d"
+ ? tb.tcpListV2Daily
+ : window === "7d"
+ ? tb.tcpListV2Weekly
+ : tb.tcpListV2Biweekly;
+ const result = await getter(params);
+ rows = result.data.map((log) =>
+ toListItem(log, { statusCode: null, timing: null }),
+ );
+ } else if (jobType === "icmp") {
+ const getter =
+ window === "1d"
+ ? tb.icmpListV2Daily
+ : window === "7d"
+ ? tb.icmpListV2Weekly
+ : tb.icmpListV2Biweekly;
+ const result = await getter(params);
+ rows = result.data.map((log) =>
+ toListItem(log, { statusCode: null, timing: null }),
+ );
+ } else if (jobType === "grpc") {
+ // gRPC reads the full 14 d materialization: it is the only one carrying
+ // `timing`, and the checker writes HTTP's phase shape there verbatim.
+ const result = await tb.grpcListV2Biweekly(params);
+ rows = result.data.map((log) =>
+ toListItem(log, {
+ statusCode: null,
+ timing: log.timing
+ ? {
+ dns: log.timing.dns,
+ connect: log.timing.connect,
+ tls: log.timing.tls,
+ ttfb: log.timing.ttfb,
+ transfer: log.timing.transfer,
+ }
+ : null,
+ }),
+ );
+ } else {
+ // DNS has a single 14 d materialization, so the window never narrows it.
+ const result = await tb.dnsListV2Biweekly(params);
+ rows = result.data.map((log) =>
+ toListItem(log, { statusCode: null, timing: null }),
+ );
+ }
+ return rows;
+ }
+
+ const hasCursor = input.cursor !== undefined;
+ let fetchLimit = Math.min(input.limit + overfetch, MAX_FETCH_LIMIT);
+ let rows = await fetchRows(fetchLimit);
+ let trimmed = trimToTick({
+ rows,
+ limit: input.limit,
+ fetchLimit,
+ direction: input.direction,
+ hasCursor,
+ });
+
+ // A page that is one tick filling the fetch ceiling may have been cut
+ // mid-tick, and the cursor we would hand back is exclusive: widen until the
+ // tick fits whole, so the remainder is never skipped.
+ while (trimmed.truncatedTick && fetchLimit < MAX_FETCH_LIMIT) {
+ fetchLimit = Math.min(fetchLimit * 2, MAX_FETCH_LIMIT);
+ rows = await fetchRows(fetchLimit);
+ trimmed = trimToTick({
+ rows,
+ limit: input.limit,
+ fetchLimit,
+ direction: input.direction,
+ hasCursor,
+ });
+ }
+
+ return {
+ data: trimmed.rows,
+ nextCursor: trimmed.nextCursor,
+ prevCursor: trimmed.prevCursor,
+ };
+}
diff --git a/packages/services/src/monitor/response-logs-cursor.ts b/packages/services/src/monitor/response-logs-cursor.ts
new file mode 100644
index 000000000..4e63b9cf4
--- /dev/null
+++ b/packages/services/src/monitor/response-logs-cursor.ts
@@ -0,0 +1,146 @@
+import type { ResponseLogFilters } from "./schemas";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+export type ResponseLogWindow = "1d" | "7d" | "14d";
+
+/**
+ * Pick the materialized view to read from. The MVs are rolling TTL windows, so
+ * it is the age of the *oldest* row requested — not the span of the range —
+ * that decides which one still holds the data: a one-day range that ended a
+ * week ago has already expired out of `mv__*_1d__*`.
+ */
+export function selectWindow(
+ fromTimestamp: number | undefined,
+ _toTimestamp: number | undefined,
+ now: number,
+): ResponseLogWindow {
+ if (fromTimestamp === undefined) return "14d";
+ const age = now - fromTimestamp;
+ if (age <= DAY_MS) return "1d";
+ if (age <= 7 * DAY_MS) return "7d";
+ return "14d";
+}
+
+export type ResponseLogPipeFilters = {
+ regions?: string[];
+ status?: string[];
+ trigger?: string[];
+ statusCodes?: number[];
+ latencyMin?: number;
+ latencyMax?: number;
+};
+
+/**
+ * Drop absent and empty filters so zod-bird never serialises a parameter the
+ * pipe would then read as an empty `IN ()`.
+ */
+export function toPipeParams(
+ filters: ResponseLogFilters,
+): ResponseLogPipeFilters {
+ const params: ResponseLogPipeFilters = {};
+ if (filters.regions?.length) params.regions = filters.regions;
+ if (filters.status?.length) params.status = filters.status;
+ if (filters.trigger?.length) params.trigger = filters.trigger;
+ if (filters.statusCodes?.length) params.statusCodes = filters.statusCodes;
+ if (filters.latencyMin !== undefined) params.latencyMin = filters.latencyMin;
+ if (filters.latencyMax !== undefined) params.latencyMax = filters.latencyMax;
+ return params;
+}
+
+export type TrimToTickResult<T> = {
+ rows: T[];
+ nextCursor: number | null;
+ prevCursor: number | null;
+ /**
+ * The page is one tick that filled `fetchLimit`, so the pipe's own LIMIT may
+ * have cut it in half. Cursors are exclusive, so paging past it would skip the
+ * rest of that tick for good — refetch wider before trusting the cursor.
+ */
+ truncatedTick: boolean;
+};
+
+/**
+ * Cut an overfetched page at a cron-tick boundary so a tick is never split
+ * across two pages. `fetchLimit` is what the pipe was asked for; returning
+ * fewer rows than that means the source is drained and there is no next page.
+ */
+export function trimToTick<T extends { cronTimestamp: number }>(args: {
+ rows: T[];
+ limit: number;
+ fetchLimit: number;
+ direction: "next" | "prev";
+ /**
+ * The request carried a cursor, so a page exists on the other side of this
+ * one. Without it the cursor pointing back the way we came is a dead end —
+ * the first page has nothing before it, and handing one back makes
+ * `hasPreviousPage` permanently true.
+ */
+ hasCursor: boolean;
+}): TrimToTickResult<T> {
+ const { rows, limit, fetchLimit, direction, hasCursor } = args;
+ if (rows.length === 0) {
+ return {
+ rows: [],
+ nextCursor: null,
+ prevCursor: null,
+ truncatedTick: false,
+ };
+ }
+
+ const kept: T[] = [];
+ let index = 0;
+ while (index < rows.length && kept.length < limit) {
+ const tick = rows[index].cronTimestamp;
+ // A tick wider than the page size is returned whole rather than split.
+ while (index < rows.length && rows[index].cronTimestamp === tick) {
+ kept.push(rows[index]);
+ index += 1;
+ }
+ }
+
+ const hitCeiling = rows.length >= fetchLimit;
+ const trailingTick = kept[kept.length - 1].cronTimestamp;
+ const trailingIsLast = index === rows.length;
+ const distinctTicks = new Set(kept.map((row) => row.cronTimestamp)).size;
+ // Same cut, but there is no earlier tick to fall back on, so it cannot be
+ // dropped here — flag it and let the caller widen the fetch.
+ const truncatedTick = trailingIsLast && hitCeiling && distinctTicks === 1;
+
+ // The pipe's own LIMIT may have cut the final tick in half; drop it unless
+ // that would leave the caller with nothing.
+ if (trailingIsLast && hitCeiling && distinctTicks > 1) {
+ while (
+ kept.length > 0 &&
+ kept[kept.length - 1].cronTimestamp === trailingTick
+ ) {
+ kept.pop();
+ }
+ }
+
+ const timestamps = kept.map((row) => row.cronTimestamp);
+ const oldest = Math.min(...timestamps);
+ const newest = Math.max(...timestamps);
+ const hasMore = kept.length < rows.length || hitCeiling;
+
+ return {
+ rows: kept,
+ nextCursor:
+ direction === "next"
+ ? hasMore
+ ? oldest
+ : null
+ : hasCursor
+ ? oldest
+ : null,
+ prevCursor:
+ direction === "prev"
+ ? hasMore
+ ? newest
+ : null
+ : hasCursor
+ ? newest
+ : null,
+ truncatedTick,
+ };
+}
diff --git a/packages/services/src/monitor/schemas.ts b/packages/services/src/monitor/schemas.ts
index f6f653d58..245361914 100644
--- a/packages/services/src/monitor/schemas.ts
+++ b/packages/services/src/monitor/schemas.ts
@@ -239,6 +239,51 @@ export const GetResponseLogInput = z.object({
});
export type GetResponseLogInput = z.infer<typeof GetResponseLogInput>;
+/**
+ * Filters the v2 response-log pipes evaluate server-side. Every array is bounded:
+ * they are templated straight into the pipes' `IN (...)` lists and serialised
+ * into the request URL, so an unbounded one is caller-controlled work.
+ */
+export const ResponseLogFilters = z.object({
+ regions: z.array(z.string().max(64)).max(128).optional(),
+ status: z
+ .array(z.enum(["success", "error", "degraded"]))
+ .max(3)
+ .optional(),
+ trigger: z
+ .array(z.enum(["cron", "api"]))
+ .max(2)
+ .optional(),
+ // The pipes cast this list to `Int16`, matching the column: a value outside
+ // that range makes Tinybird fail the query rather than match nothing.
+ statusCodes: z.array(z.number().int().min(0).max(32_767)).max(100).optional(),
+ latencyMin: z.number().int().min(0).optional(),
+ latencyMax: z.number().int().min(0).optional(),
+});
+export type ResponseLogFilters = z.infer<typeof ResponseLogFilters>;
+
+export const ListResponseLogsInfiniteInput = ResponseLogFilters.extend({
+ monitorId: z.number().int(),
+ fromTimestamp: z.number().int().optional(),
+ toTimestamp: z.number().int().optional(),
+ /** `cronTimestamp` boundary of the previous page, exclusive. */
+ cursor: z.number().int().optional(),
+ direction: z.enum(["next", "prev"]).default("next"),
+ limit: z.number().int().min(1).max(100).default(50),
+});
+export type ListResponseLogsInfiniteInput = z.infer<
+ typeof ListResponseLogsInfiniteInput
+>;
+
+export const GetResponseLogFacetsInput = ResponseLogFilters.extend({
+ monitorId: z.number().int(),
+ fromTimestamp: z.number().int().optional(),
+ toTimestamp: z.number().int().optional(),
+});
+export type GetResponseLogFacetsInput = z.infer<
+ typeof GetResponseLogFacetsInput
+>;
+
export const GetPrivateLocationIdsByMonitorInput = z.object({
monitorIds: z.array(z.number().int()),
});
diff --git a/packages/tinybird/datasources/mv__dns_14d__v0.datasource b/packages/tinybird/datasources/mv__dns_14d__v0.datasource
new file mode 100644
index 000000000..d6530f018
--- /dev/null
+++ b/packages/tinybird/datasources/mv__dns_14d__v0.datasource
@@ -0,0 +1,19 @@
+# Data Source created from Pipe 'aggregate__dns_14d__v0'
+
+SCHEMA >
+ `time` DateTime,
+ `id` String,
+ `uri` String,
+ `latency` Int16,
+ `region` String,
+ `trigger` String,
+ `timestamp` Int64,
+ `cronTimestamp` Int64,
+ `monitorId` Int16,
+ `requestStatus` String,
+ `records` String
+
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(time)"
+ENGINE_SORTING_KEY "monitorId, time"
+ENGINE_TTL "time + toIntervalDay(14)"
diff --git a/packages/tinybird/endpoints/endpoint__dns_list_14d__v1.pipe b/packages/tinybird/endpoints/endpoint__dns_list_14d__v1.pipe
new file mode 100644
index 000000000..a0cf37c3f
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__dns_list_14d__v1.pipe
@@ -0,0 +1,49 @@
+TOKEN "endpoint__dns_list_14d__v1_endpoint_read_7107" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ uri,
+ latency,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus,
+ records
+FROM mv__dns_14d__v0
+WHERE
+ monitorId = {{ String(monitorId, '7417', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__dns_list_facets_14d__v0.pipe b/packages/tinybird/endpoints/endpoint__dns_list_facets_14d__v0.pipe
new file mode 100644
index 000000000..128377590
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__dns_list_facets_14d__v0.pipe
@@ -0,0 +1,61 @@
+TOKEN "endpoint__dns_list_facets_14d__v0_endpoint_read_7203" READ
+
+NODE base
+SQL >
+
+%
+SELECT
+ region,
+ requestStatus,
+ trigger,
+ latency,
+ {% if regions %} region IN {{ Array(regions, 'String') }} {% else %} 1 {% end %} AS m_region,
+ {% if status %} requestStatus IN {{ Array(status, 'String') }} {% else %} 1 {% end %} AS m_request_status,
+ {% if trigger %} trigger IN {{ Array(trigger, 'String') }} {% else %} 1 {% end %} AS m_trigger,
+ (
+ {% if defined(latencyMin) %} latency >= toInt64({{ String(latencyMin) }}) {% else %} 1 {% end %}
+ AND
+ {% if defined(latencyMax) %} latency <= toInt64({{ String(latencyMax) }}) {% else %} 1 {% end %}
+ ) AS m_latency
+FROM mv__dns_14d__v0
+WHERE
+ monitorId = {{ String(monitorId, '7417', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+
+NODE endpoint
+SQL >
+
+ SELECT 'region' AS field, toString(region) AS value, toUInt64(countIf(m_request_status AND m_trigger AND m_latency)) AS count
+ FROM base
+ GROUP BY region
+ UNION ALL
+ SELECT 'requestStatus', toString(requestStatus), toUInt64(countIf(m_region AND m_trigger AND m_latency))
+ FROM base
+ WHERE requestStatus IS NOT NULL
+ GROUP BY requestStatus
+ UNION ALL
+ SELECT 'trigger', toString(trigger), toUInt64(countIf(m_region AND m_request_status AND m_latency))
+ FROM base
+ WHERE trigger IS NOT NULL
+ GROUP BY trigger
+ UNION ALL
+ SELECT '__summary', 'filtered', toUInt64(countIf(m_region AND m_request_status AND m_trigger AND m_latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'total', toUInt64(count())
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMin', toUInt64(min(latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMax', toUInt64(max(latency))
+ FROM base
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__grpc_list_14d__v1.pipe b/packages/tinybird/endpoints/endpoint__grpc_list_14d__v1.pipe
new file mode 100644
index 000000000..f8ae5178d
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__grpc_list_14d__v1.pipe
@@ -0,0 +1,51 @@
+TAGS "grpc"
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ region,
+ trigger,
+ servingStatus,
+ grpcCode,
+ service,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus,
+ timing
+FROM mv__grpc_full_14d__v0
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__grpc_list_facets_14d__v0.pipe b/packages/tinybird/endpoints/endpoint__grpc_list_facets_14d__v0.pipe
new file mode 100644
index 000000000..e10fa0bf5
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__grpc_list_facets_14d__v0.pipe
@@ -0,0 +1,61 @@
+TAGS "grpc"
+
+NODE base
+SQL >
+
+%
+SELECT
+ region,
+ requestStatus,
+ trigger,
+ latency,
+ {% if regions %} region IN {{ Array(regions, 'String') }} {% else %} 1 {% end %} AS m_region,
+ {% if status %} requestStatus IN {{ Array(status, 'String') }} {% else %} 1 {% end %} AS m_request_status,
+ {% if trigger %} trigger IN {{ Array(trigger, 'String') }} {% else %} 1 {% end %} AS m_trigger,
+ (
+ {% if defined(latencyMin) %} latency >= toInt64({{ String(latencyMin) }}) {% else %} 1 {% end %}
+ AND
+ {% if defined(latencyMax) %} latency <= toInt64({{ String(latencyMax) }}) {% else %} 1 {% end %}
+ ) AS m_latency
+FROM mv__grpc_full_14d__v0
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+
+NODE endpoint
+SQL >
+
+ SELECT 'region' AS field, toString(region) AS value, toUInt64(countIf(m_request_status AND m_trigger AND m_latency)) AS count
+ FROM base
+ GROUP BY region
+ UNION ALL
+ SELECT 'requestStatus', toString(requestStatus), toUInt64(countIf(m_region AND m_trigger AND m_latency))
+ FROM base
+ WHERE requestStatus IS NOT NULL
+ GROUP BY requestStatus
+ UNION ALL
+ SELECT 'trigger', toString(trigger), toUInt64(countIf(m_region AND m_request_status AND m_latency))
+ FROM base
+ WHERE trigger IS NOT NULL
+ GROUP BY trigger
+ UNION ALL
+ SELECT '__summary', 'filtered', toUInt64(countIf(m_region AND m_request_status AND m_trigger AND m_latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'total', toUInt64(count())
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMin', toUInt64(min(latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMax', toUInt64(max(latency))
+ FROM base
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__http_list_14d__v2.pipe b/packages/tinybird/endpoints/endpoint__http_list_14d__v2.pipe
new file mode 100644
index 000000000..006bf3ca0
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__http_list_14d__v2.pipe
@@ -0,0 +1,50 @@
+TOKEN "endpoint__http_list_14d__v2_endpoint_read_7103" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ region,
+ trigger,
+ statusCode,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus,
+ timing
+FROM mv__http_14d__v1
+WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if statusCodes %} AND statusCode IN {{ Array(statusCodes, 'Int16') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__http_list_1d__v2.pipe b/packages/tinybird/endpoints/endpoint__http_list_1d__v2.pipe
new file mode 100644
index 000000000..488de4b26
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__http_list_1d__v2.pipe
@@ -0,0 +1,50 @@
+TOKEN "endpoint__http_list_1d__v2_endpoint_read_7101" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ region,
+ trigger,
+ statusCode,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus,
+ timing
+FROM mv__http_1d__v1
+WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if statusCodes %} AND statusCode IN {{ Array(statusCodes, 'Int16') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__http_list_7d__v2.pipe b/packages/tinybird/endpoints/endpoint__http_list_7d__v2.pipe
new file mode 100644
index 000000000..f9819b047
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__http_list_7d__v2.pipe
@@ -0,0 +1,50 @@
+TOKEN "endpoint__http_list_7d__v2_endpoint_read_7102" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ region,
+ trigger,
+ statusCode,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus,
+ timing
+FROM mv__http_7d__v1
+WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if statusCodes %} AND statusCode IN {{ Array(statusCodes, 'Int16') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__http_list_facets_14d__v0.pipe b/packages/tinybird/endpoints/endpoint__http_list_facets_14d__v0.pipe
new file mode 100644
index 000000000..d2b4a2021
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__http_list_facets_14d__v0.pipe
@@ -0,0 +1,68 @@
+TOKEN "endpoint__http_list_facets_14d__v0_endpoint_read_7201" READ
+
+NODE base
+SQL >
+
+%
+SELECT
+ region,
+ requestStatus,
+ trigger,
+ statusCode,
+ latency,
+ {% if regions %} region IN {{ Array(regions, 'String') }} {% else %} 1 {% end %} AS m_region,
+ {% if status %} requestStatus IN {{ Array(status, 'String') }} {% else %} 1 {% end %} AS m_request_status,
+ {% if trigger %} trigger IN {{ Array(trigger, 'String') }} {% else %} 1 {% end %} AS m_trigger,
+ {% if statusCodes %} statusCode IN {{ Array(statusCodes, 'Int16') }} {% else %} 1 {% end %} AS m_status_code,
+ (
+ {% if defined(latencyMin) %} latency >= toInt64({{ String(latencyMin) }}) {% else %} 1 {% end %}
+ AND
+ {% if defined(latencyMax) %} latency <= toInt64({{ String(latencyMax) }}) {% else %} 1 {% end %}
+ ) AS m_latency
+FROM mv__http_14d__v1
+WHERE
+ monitorId = {{ String(monitorId, '1', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+
+NODE endpoint
+SQL >
+
+ SELECT 'region' AS field, toString(region) AS value, toUInt64(countIf(m_request_status AND m_trigger AND m_status_code AND m_latency)) AS count
+ FROM base
+ GROUP BY region
+ UNION ALL
+ SELECT 'requestStatus', toString(requestStatus), toUInt64(countIf(m_region AND m_trigger AND m_status_code AND m_latency))
+ FROM base
+ WHERE requestStatus IS NOT NULL
+ GROUP BY requestStatus
+ UNION ALL
+ SELECT 'trigger', toString(trigger), toUInt64(countIf(m_region AND m_request_status AND m_status_code AND m_latency))
+ FROM base
+ WHERE trigger IS NOT NULL
+ GROUP BY trigger
+ UNION ALL
+ SELECT 'statusCode', toString(statusCode), toUInt64(countIf(m_region AND m_request_status AND m_trigger AND m_latency))
+ FROM base
+ WHERE statusCode IS NOT NULL
+ GROUP BY statusCode
+ UNION ALL
+ SELECT '__summary', 'filtered', toUInt64(countIf(m_region AND m_request_status AND m_trigger AND m_status_code AND m_latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'total', toUInt64(count())
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMin', toUInt64(min(latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMax', toUInt64(max(latency))
+ FROM base
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__icmp_list_14d__v1.pipe b/packages/tinybird/endpoints/endpoint__icmp_list_14d__v1.pipe
new file mode 100644
index 000000000..31e3cb35f
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__icmp_list_14d__v1.pipe
@@ -0,0 +1,52 @@
+TOKEN "endpoint__icmp_list_14d__v1_endpoint_read_7110" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ latencyMin,
+ latencyMax,
+ packetsSent,
+ packetsReceived,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus
+FROM mv__icmp_14d__v0
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__icmp_list_1d__v1.pipe b/packages/tinybird/endpoints/endpoint__icmp_list_1d__v1.pipe
new file mode 100644
index 000000000..7c680d37f
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__icmp_list_1d__v1.pipe
@@ -0,0 +1,52 @@
+TOKEN "endpoint__icmp_list_1d__v1_endpoint_read_7108" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ latencyMin,
+ latencyMax,
+ packetsSent,
+ packetsReceived,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus
+FROM mv__icmp_1d__v0
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__icmp_list_7d__v1.pipe b/packages/tinybird/endpoints/endpoint__icmp_list_7d__v1.pipe
new file mode 100644
index 000000000..e38e38c6d
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__icmp_list_7d__v1.pipe
@@ -0,0 +1,52 @@
+TOKEN "endpoint__icmp_list_7d__v1_endpoint_read_7109" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ latencyMin,
+ latencyMax,
+ packetsSent,
+ packetsReceived,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus
+FROM mv__icmp_7d__v0
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__icmp_list_facets_14d__v0.pipe b/packages/tinybird/endpoints/endpoint__icmp_list_facets_14d__v0.pipe
new file mode 100644
index 000000000..0adb4262a
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__icmp_list_facets_14d__v0.pipe
@@ -0,0 +1,61 @@
+TOKEN "endpoint__icmp_list_facets_14d__v0_endpoint_read_7204" READ
+
+NODE base
+SQL >
+
+%
+SELECT
+ region,
+ requestStatus,
+ trigger,
+ latency,
+ {% if regions %} region IN {{ Array(regions, 'String') }} {% else %} 1 {% end %} AS m_region,
+ {% if status %} requestStatus IN {{ Array(status, 'String') }} {% else %} 1 {% end %} AS m_request_status,
+ {% if trigger %} trigger IN {{ Array(trigger, 'String') }} {% else %} 1 {% end %} AS m_trigger,
+ (
+ {% if defined(latencyMin) %} latency >= toInt64({{ String(latencyMin) }}) {% else %} 1 {% end %}
+ AND
+ {% if defined(latencyMax) %} latency <= toInt64({{ String(latencyMax) }}) {% else %} 1 {% end %}
+ ) AS m_latency
+FROM mv__icmp_14d__v0
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+
+NODE endpoint
+SQL >
+
+ SELECT 'region' AS field, toString(region) AS value, toUInt64(countIf(m_request_status AND m_trigger AND m_latency)) AS count
+ FROM base
+ GROUP BY region
+ UNION ALL
+ SELECT 'requestStatus', toString(requestStatus), toUInt64(countIf(m_region AND m_trigger AND m_latency))
+ FROM base
+ WHERE requestStatus IS NOT NULL
+ GROUP BY requestStatus
+ UNION ALL
+ SELECT 'trigger', toString(trigger), toUInt64(countIf(m_region AND m_request_status AND m_latency))
+ FROM base
+ WHERE trigger IS NOT NULL
+ GROUP BY trigger
+ UNION ALL
+ SELECT '__summary', 'filtered', toUInt64(countIf(m_region AND m_request_status AND m_trigger AND m_latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'total', toUInt64(count())
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMin', toUInt64(min(latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMax', toUInt64(max(latency))
+ FROM base
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__tcp_list_14d__v2.pipe b/packages/tinybird/endpoints/endpoint__tcp_list_14d__v2.pipe
new file mode 100644
index 000000000..ff3b65327
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__tcp_list_14d__v2.pipe
@@ -0,0 +1,48 @@
+TOKEN "endpoint__tcp_list_14d__v2_endpoint_read_7106" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus
+FROM mv__tcp_14d__v1
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__tcp_list_1d__v2.pipe b/packages/tinybird/endpoints/endpoint__tcp_list_1d__v2.pipe
new file mode 100644
index 000000000..fdeb704ca
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__tcp_list_1d__v2.pipe
@@ -0,0 +1,48 @@
+TOKEN "endpoint__tcp_list_1d__v2_endpoint_read_7104" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus
+FROM mv__tcp_1d__v1
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__tcp_list_7d__v2.pipe b/packages/tinybird/endpoints/endpoint__tcp_list_7d__v2.pipe
new file mode 100644
index 000000000..5572fec01
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__tcp_list_7d__v2.pipe
@@ -0,0 +1,48 @@
+TOKEN "endpoint__tcp_list_7d__v2_endpoint_read_7105" READ
+
+NODE endpoint
+SQL >
+
+%
+SELECT
+ time,
+ id,
+ latency,
+ error,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus
+FROM mv__tcp_7d__v1
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+ {% if defined(cursor) %}
+ {% if String(direction, 'next') == 'prev' %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp > toInt64({{ String(cursor) }})
+ {% else %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(cursor) }})))
+ AND cronTimestamp < toInt64({{ String(cursor) }})
+ {% end %}
+ {% end %}
+ {% if regions %} AND region IN {{ Array(regions, 'String') }} {% end %}
+ {% if status %} AND requestStatus IN {{ Array(status, 'String') }} {% end %}
+ {% if trigger %} AND trigger IN {{ Array(trigger, 'String') }} {% end %}
+ {% if defined(latencyMin) %} AND latency >= toInt64({{ String(latencyMin) }}) {% end %}
+ {% if defined(latencyMax) %} AND latency <= toInt64({{ String(latencyMax) }}) {% end %}
+ORDER BY
+ time {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %},
+ cronTimestamp {% if String(direction, 'next') == 'prev' %} ASC {% else %} DESC {% end %}
+LIMIT {{ Int32(limit, 50, required=True) }}
+
+TYPE endpoint
diff --git a/packages/tinybird/endpoints/endpoint__tcp_list_facets_14d__v0.pipe b/packages/tinybird/endpoints/endpoint__tcp_list_facets_14d__v0.pipe
new file mode 100644
index 000000000..8ba54b84e
--- /dev/null
+++ b/packages/tinybird/endpoints/endpoint__tcp_list_facets_14d__v0.pipe
@@ -0,0 +1,61 @@
+TOKEN "endpoint__tcp_list_facets_14d__v0_endpoint_read_7202" READ
+
+NODE base
+SQL >
+
+%
+SELECT
+ region,
+ requestStatus,
+ trigger,
+ latency,
+ {% if regions %} region IN {{ Array(regions, 'String') }} {% else %} 1 {% end %} AS m_region,
+ {% if status %} requestStatus IN {{ Array(status, 'String') }} {% else %} 1 {% end %} AS m_request_status,
+ {% if trigger %} trigger IN {{ Array(trigger, 'String') }} {% else %} 1 {% end %} AS m_trigger,
+ (
+ {% if defined(latencyMin) %} latency >= toInt64({{ String(latencyMin) }}) {% else %} 1 {% end %}
+ AND
+ {% if defined(latencyMax) %} latency <= toInt64({{ String(latencyMax) }}) {% else %} 1 {% end %}
+ ) AS m_latency
+FROM mv__tcp_14d__v1
+WHERE
+ monitorId = {{ String(monitorId, '4433', required=True) }}
+ {% if defined(fromDate) %}
+ AND time >= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(fromDate) }})))
+ AND cronTimestamp >= toInt64({{ String(fromDate) }})
+ {% end %}
+ {% if defined(toDate) %}
+ AND time <= toDateTime(fromUnixTimestamp64Milli(toInt64({{ String(toDate) }})))
+ AND cronTimestamp <= toInt64({{ String(toDate) }})
+ {% end %}
+
+NODE endpoint
+SQL >
+
+ SELECT 'region' AS field, toString(region) AS value, toUInt64(countIf(m_request_status AND m_trigger AND m_latency)) AS count
+ FROM base
+ GROUP BY region
+ UNION ALL
+ SELECT 'requestStatus', toString(requestStatus), toUInt64(countIf(m_region AND m_trigger AND m_latency))
+ FROM base
+ WHERE requestStatus IS NOT NULL
+ GROUP BY requestStatus
+ UNION ALL
+ SELECT 'trigger', toString(trigger), toUInt64(countIf(m_region AND m_request_status AND m_latency))
+ FROM base
+ WHERE trigger IS NOT NULL
+ GROUP BY trigger
+ UNION ALL
+ SELECT '__summary', 'filtered', toUInt64(countIf(m_region AND m_request_status AND m_trigger AND m_latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'total', toUInt64(count())
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMin', toUInt64(min(latency))
+ FROM base
+ UNION ALL
+ SELECT '__summary', 'latencyMax', toUInt64(max(latency))
+ FROM base
+
+TYPE endpoint
diff --git a/packages/tinybird/materializations/aggregate__dns_14d__v0.pipe b/packages/tinybird/materializations/aggregate__dns_14d__v0.pipe
new file mode 100644
index 000000000..342654e2a
--- /dev/null
+++ b/packages/tinybird/materializations/aggregate__dns_14d__v0.pipe
@@ -0,0 +1,19 @@
+NODE aggregate
+SQL >
+
+ SELECT
+ toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,
+ id,
+ uri,
+ latency,
+ region,
+ trigger,
+ timestamp,
+ cronTimestamp,
+ monitorId,
+ requestStatus,
+ records
+ FROM dns_response__v0
+
+TYPE materialized
+DATASOURCE mv__dns_14d__v0
diff --git a/packages/tinybird/src/client.test.ts b/packages/tinybird/src/client.test.ts
index 26b4d2e7d..17b015f40 100644
--- a/packages/tinybird/src/client.test.ts
+++ b/packages/tinybird/src/client.test.ts
@@ -38,3 +38,121 @@ describe("OSTinybird", () => {
expect(await tb.homeStats({})).toEqual({ meta: [], data: [] });
});
});
+
+const listV2Getters = [
+ "httpListV2Daily",
+ "httpListV2Weekly",
+ "httpListV2Biweekly",
+ "tcpListV2Daily",
+ "tcpListV2Weekly",
+ "tcpListV2Biweekly",
+ "icmpListV2Daily",
+ "icmpListV2Weekly",
+ "icmpListV2Biweekly",
+ "dnsListV2Biweekly",
+ "grpcListV2Biweekly",
+] as const;
+
+const facetGetters = [
+ "httpListFacets",
+ "tcpListFacets",
+ "icmpListFacets",
+ "dnsListFacets",
+ "grpcListFacets",
+] as const;
+
+describe("v2 response-log list pipes", () => {
+ const tb = new OSTinybird({ token: "a-token" });
+
+ for (const name of listV2Getters) {
+ test(`${name} rejects a limit outside the pipe ceiling`, async () => {
+ await expect(tb[name]({ monitorId: "1", limit: 1001 })).rejects.toThrow();
+ await expect(tb[name]({ monitorId: "1", limit: 0 })).rejects.toThrow();
+ });
+
+ test(`${name} rejects an unknown direction`, async () => {
+ await expect(
+ tb[name]({
+ monitorId: "1",
+ limit: 50,
+ direction: "sideways" as unknown as "next",
+ }),
+ ).rejects.toThrow();
+ });
+
+ test(`${name} accepts a filtered cursor page`, async () => {
+ expect(
+ await tb[name]({
+ monitorId: "1",
+ limit: 50,
+ cursor: 1_700_000_000_000,
+ direction: "prev",
+ fromDate: 1_699_000_000_000,
+ toDate: 1_700_000_000_000,
+ regions: ["ams"],
+ status: ["error"],
+ trigger: ["cron"],
+ latencyMin: 0,
+ latencyMax: 1000,
+ }),
+ ).toEqual({ meta: [], data: [] });
+ });
+ }
+
+ test("httpListV2Biweekly accepts a status-code filter", async () => {
+ expect(
+ await tb.httpListV2Biweekly({
+ monitorId: "1",
+ limit: 50,
+ statusCodes: [200, 500],
+ }),
+ ).toEqual({ meta: [], data: [] });
+ });
+
+ test("httpListV2Biweekly rejects oversized filter arrays", async () => {
+ await expect(
+ tb.httpListV2Biweekly({
+ monitorId: "1",
+ limit: 50,
+ regions: Array.from({ length: 129 }, (_, i) => `r${i}`),
+ }),
+ ).rejects.toThrow();
+ await expect(
+ tb.httpListV2Biweekly({
+ monitorId: "1",
+ limit: 50,
+ statusCodes: Array.from({ length: 101 }, (_, i) => i),
+ }),
+ ).rejects.toThrow();
+ });
+});
+
+describe("response-log facet pipes", () => {
+ const tb = new OSTinybird({ token: "a-token" });
+
+ for (const name of facetGetters) {
+ test(`${name} rejects a non-array region filter`, async () => {
+ await expect(
+ tb[name]({
+ monitorId: "1",
+ regions: "ams" as unknown as string[],
+ }),
+ ).rejects.toThrow();
+ });
+
+ test(`${name} accepts the filter set without a cursor`, async () => {
+ expect(
+ await tb[name]({
+ monitorId: "1",
+ fromDate: 1_699_000_000_000,
+ toDate: 1_700_000_000_000,
+ regions: ["ams"],
+ status: ["error"],
+ trigger: ["cron"],
+ latencyMin: 0,
+ latencyMax: 1000,
+ }),
+ ).toEqual({ meta: [], data: [] });
+ });
+ }
+});
diff --git a/packages/tinybird/src/client.ts b/packages/tinybird/src/client.ts
index d14879692..690fb2468 100644
--- a/packages/tinybird/src/client.ts
+++ b/packages/tinybird/src/client.ts
@@ -91,6 +91,133 @@ const icmpUptimeShape = z.object({
error: z.int(),
});
+// Row shapes shared by the v1 (offset) and v2 (cursor) list pipes of each job
+// type — one object per type so the two generations cannot drift apart.
+const httpListRowShape = {
+ type: z.literal("http").prefault("http"),
+ id: z.string().nullable(),
+ latency: z.int(),
+ statusCode: z.int().nullable(),
+ monitorId: z.string(),
+ requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
+ region: z.enum(monitorRegions).or(z.string()),
+ cronTimestamp: z.int(),
+ trigger: z.enum(triggers).nullable().prefault("cron"),
+ timestamp: z.number(),
+ timing: timingPhasesSchema,
+};
+
+const tcpListRowShape = {
+ type: z.literal("tcp").prefault("tcp"),
+ id: z.string().nullable(),
+ latency: z.int(),
+ monitorId: z.coerce.string(),
+ requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
+ region: z.enum(monitorRegions).or(z.string()),
+ cronTimestamp: z.int(),
+ trigger: z.enum(triggers).nullable().prefault("cron"),
+ timestamp: z.number(),
+};
+
+const icmpListRowShape = {
+ type: z.literal("icmp").prefault("icmp"),
+ id: z.string().nullable(),
+ latency: z.int(),
+ latencyMin: z.int().prefault(0),
+ latencyMax: z.int().prefault(0),
+ packetsSent: z.int().prefault(0),
+ packetsReceived: z.int().prefault(0),
+ monitorId: z.coerce.string(),
+ requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
+ region: z.enum(monitorRegions).or(z.string()),
+ cronTimestamp: z.int(),
+ trigger: z.enum(triggers).nullable().prefault("cron"),
+ timestamp: z.number(),
+};
+
+const dnsListRowShape = {
+ type: z.literal("dns").prefault("dns"),
+ id: z.coerce.string().nullable(),
+ uri: z.string(),
+ latency: z.int(),
+ monitorId: z.coerce.string(),
+ requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
+ region: z.enum(monitorRegions).or(z.string()),
+ cronTimestamp: z.int(),
+ trigger: z.enum(triggers).nullable().prefault("cron"),
+ timestamp: z.number(),
+ records: z
+ .string()
+ .transform((str) => {
+ try {
+ return JSON.parse(str) as Record<string, unknown>;
+ } catch (error) {
+ console.error(error);
+ return {};
+ }
+ })
+ .pipe(z.record(z.string(), z.array(z.string()))),
+};
+
+const grpcListRowShape = {
+ type: z.literal("grpc").prefault("grpc"),
+ id: z.string().nullable(),
+ latency: z.int(),
+ servingStatus: z.string().nullable(),
+ grpcCode: z.int().nullable(),
+ service: z.string().nullable(),
+ monitorId: z.coerce.string(),
+ requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
+ region: z.enum(monitorRegions).or(z.string()),
+ cronTimestamp: z.int(),
+ trigger: z.enum(triggers).nullable().prefault("cron"),
+ timestamp: z.number(),
+ // gRPC is HTTP/2, so the checker writes HTTP's phase shape verbatim.
+ timing: timingPhasesSchema,
+};
+
+// Filters every v2 list and facet pipe accepts; each maps to one `IN` or range
+// predicate evaluated by Tinybird instead of the browser.
+// Bounded here too: these are comma-joined into the pipe request's query string,
+// so the ceiling has to hold at the boundary that builds the URL.
+const responseLogFilterShape = {
+ regions: z.array(z.string().max(64)).max(128).optional(),
+ status: z.array(z.string().max(16)).max(3).optional(),
+ trigger: z.array(z.string().max(16)).max(2).optional(),
+ latencyMin: z.int().optional(),
+ latencyMax: z.int().optional(),
+};
+
+const httpResponseLogFilterShape = {
+ ...responseLogFilterShape,
+ // `Array(statusCodes, 'Int16')` in the pipes: out of that range the query
+ // errors instead of matching nothing.
+ statusCodes: z.array(z.int().min(0).max(32_767)).max(100).optional(),
+};
+
+// The service overfetches by the monitor's location count on top of the caller's
+// page size, so this ceiling sits well above the 100-row service maximum.
+const listV2WindowShape = {
+ monitorId: z.string(),
+ fromDate: z.int().optional(),
+ toDate: z.int().optional(),
+ cursor: z.int().optional(),
+ direction: z.enum(["next", "prev"]).prefault("next"),
+ limit: z.int().min(1).max(1000),
+};
+
+const facetWindowShape = {
+ monitorId: z.string(),
+ fromDate: z.int().optional(),
+ toDate: z.int().optional(),
+};
+
+const facetRowShape = {
+ field: z.string(),
+ value: z.string(),
+ count: z.int(),
+};
+
const grpcMetricsShape = z.object({
p50Latency: z.number().nullable().prefault(0),
p75Latency: z.number().nullable().prefault(0),
@@ -248,19 +375,7 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("http").prefault("http"),
- id: z.string().nullable(),
- latency: z.int(),
- statusCode: z.int().nullable(),
- monitorId: z.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
- timing: timingPhasesSchema,
- }),
+ data: z.object(httpListRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -295,19 +410,7 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("http").prefault("http"),
- id: z.string().nullable(),
- latency: z.int(),
- statusCode: z.int().nullable(),
- monitorId: z.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
- timing: timingPhasesSchema,
- }),
+ data: z.object(httpListRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -344,19 +447,55 @@ export class OSTinybird {
limit: z.int().optional(),
offset: z.int().optional(),
}),
- data: z.object({
- type: z.literal("http").prefault("http"),
- id: z.string().nullable(),
- latency: z.int(),
- statusCode: z.int().nullable(),
- monitorId: z.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
- timing: timingPhasesSchema,
+ data: z.object(httpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get httpListV2Daily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_list_1d__v2",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...httpResponseLogFilterShape,
+ }),
+ data: z.object(httpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get httpListV2Weekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_list_7d__v2",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...httpResponseLogFilterShape,
+ }),
+ data: z.object(httpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get httpListV2Biweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_list_14d__v2",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...httpResponseLogFilterShape,
+ }),
+ data: z.object(httpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get httpListFacets() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__http_list_facets_14d__v0",
+ parameters: z.object({
+ ...facetWindowShape,
+ ...httpResponseLogFilterShape,
}),
+ data: z.object(facetRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -804,17 +943,7 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("tcp").prefault("tcp"),
- id: z.string().nullable(),
- latency: z.int(),
- monitorId: z.coerce.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
- }),
+ data: z.object(tcpListRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -848,17 +977,7 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("tcp").prefault("tcp"),
- id: z.string().nullable(),
- latency: z.int(),
- monitorId: z.coerce.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
- }),
+ data: z.object(tcpListRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -892,17 +1011,55 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("tcp").prefault("tcp"),
- id: z.string().nullable(),
- latency: z.int(),
- monitorId: z.coerce.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
+ data: z.object(tcpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get tcpListV2Daily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_list_1d__v2",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(tcpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get tcpListV2Weekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_list_7d__v2",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(tcpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get tcpListV2Biweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_list_14d__v2",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...responseLogFilterShape,
}),
+ data: z.object(tcpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get tcpListFacets() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__tcp_list_facets_14d__v0",
+ parameters: z.object({
+ ...facetWindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(facetRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -1324,21 +1481,7 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("icmp").prefault("icmp"),
- id: z.string().nullable(),
- latency: z.int(),
- latencyMin: z.int().prefault(0),
- latencyMax: z.int().prefault(0),
- packetsSent: z.int().prefault(0),
- packetsReceived: z.int().prefault(0),
- monitorId: z.coerce.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
- }),
+ data: z.object(icmpListRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -1351,21 +1494,7 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("icmp").prefault("icmp"),
- id: z.string().nullable(),
- latency: z.int(),
- latencyMin: z.int().prefault(0),
- latencyMax: z.int().prefault(0),
- packetsSent: z.int().prefault(0),
- packetsReceived: z.int().prefault(0),
- monitorId: z.coerce.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
- }),
+ data: z.object(icmpListRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -1378,21 +1507,55 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("icmp").prefault("icmp"),
- id: z.string().nullable(),
- latency: z.int(),
- latencyMin: z.int().prefault(0),
- latencyMax: z.int().prefault(0),
- packetsSent: z.int().prefault(0),
- packetsReceived: z.int().prefault(0),
- monitorId: z.coerce.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
+ data: z.object(icmpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get icmpListV2Daily() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__icmp_list_1d__v1",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...responseLogFilterShape,
}),
+ data: z.object(icmpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get icmpListV2Weekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__icmp_list_7d__v1",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(icmpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get icmpListV2Biweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__icmp_list_14d__v1",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(icmpListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get icmpListFacets() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__icmp_list_facets_14d__v0",
+ parameters: z.object({
+ ...facetWindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(facetRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
@@ -1873,6 +2036,30 @@ export class OSTinybird {
});
}
+ public get grpcListV2Biweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__grpc_list_14d__v1",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(grpcListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get grpcListFacets() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__grpc_list_facets_14d__v0",
+ parameters: z.object({
+ ...facetWindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(facetRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
public get grpcMetricsDaily() {
return this.tb.buildPipe({
pipe: "endpoint__grpc_metrics_1d__v0",
@@ -2651,29 +2838,31 @@ export class OSTinybird {
fromDate: z.int().optional(),
toDate: z.int().optional(),
}),
- data: z.object({
- type: z.literal("dns").prefault("dns"),
- id: z.coerce.string().nullable(),
- uri: z.string(),
- latency: z.int(),
- monitorId: z.coerce.string(),
- requestStatus: z.enum(["error", "success", "degraded"]).nullable(),
- region: z.enum(monitorRegions).or(z.string()),
- cronTimestamp: z.int(),
- trigger: z.enum(triggers).nullable().prefault("cron"),
- timestamp: z.number(),
- records: z
- .string()
- .transform((str) => {
- try {
- return JSON.parse(str) as Record<string, unknown>;
- } catch (error) {
- console.error(error);
- return {};
- }
- })
- .pipe(z.record(z.string(), z.array(z.string()))),
+ data: z.object(dnsListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get dnsListV2Biweekly() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__dns_list_14d__v1",
+ parameters: z.object({
+ ...listV2WindowShape,
+ ...responseLogFilterShape,
+ }),
+ data: z.object(dnsListRowShape),
+ opts: { next: { revalidate: REVALIDATE } },
+ });
+ }
+
+ public get dnsListFacets() {
+ return this.tb.buildPipe({
+ pipe: "endpoint__dns_list_facets_14d__v0",
+ parameters: z.object({
+ ...facetWindowShape,
+ ...responseLogFilterShape,
}),
+ data: z.object(facetRowShape),
opts: { next: { revalidate: REVALIDATE } },
});
}
diff --git a/packages/ui/package.json b/packages/ui/package.json
index bbeac19a4..29846760e 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -3,10 +3,6 @@
"version": "0.0.0",
"license": "MIT",
"exports": {
- "./components/ui/*": {
- "types": "./src/components/ui/*.tsx",
- "default": "./src/components/ui/*.tsx"
- },
"./components/blocks/status.types": {
"types": "./src/components/blocks/status.types.ts",
"default": "./src/components/blocks/status.types.ts"
@@ -15,6 +11,27 @@
"types": "./src/components/blocks/status.utils.ts",
"default": "./src/components/blocks/status.utils.ts"
},
+ "./components/data-table-filters/data-table-filter-command/utils": {
+ "types": "./src/components/data-table-filters/data-table-filter-command/utils.ts",
+ "default": "./src/components/data-table-filters/data-table-filter-command/utils.ts"
+ },
+ "./components/data-table-filters/types": {
+ "types": "./src/components/data-table-filters/types.ts",
+ "default": "./src/components/data-table-filters/types.ts"
+ },
+ "./components/data-table-filters/utils": {
+ "types": "./src/components/data-table-filters/utils.ts",
+ "default": "./src/components/data-table-filters/utils.ts"
+ },
+ "./globals": "./src/globals.css",
+ "./lib/data-table-filters/store/provider/DataTableStoreProvider": {
+ "types": "./src/lib/data-table-filters/store/provider/DataTableStoreProvider.tsx",
+ "default": "./src/lib/data-table-filters/store/provider/DataTableStoreProvider.tsx"
+ },
+ "./lib/data-table-filters/table-schema/generators/columns": {
+ "types": "./src/lib/data-table-filters/table-schema/generators/columns.tsx",
+ "default": "./src/lib/data-table-filters/table-schema/generators/columns.tsx"
+ },
"./components/blocks/*": {
"types": "./src/components/blocks/*.tsx",
"default": "./src/components/blocks/*.tsx"
@@ -23,15 +40,22 @@
"types": "./src/components/custom/*.tsx",
"default": "./src/components/custom/*.tsx"
},
- "./lib/*": {
- "types": "./src/lib/*.ts",
- "default": "./src/lib/*.ts"
+ "./components/data-table-filters/*": {
+ "types": "./src/components/data-table-filters/*.tsx",
+ "default": "./src/components/data-table-filters/*.tsx"
+ },
+ "./components/ui/*": {
+ "types": "./src/components/ui/*.tsx",
+ "default": "./src/components/ui/*.tsx"
},
"./hooks/*": {
"types": "./src/hooks/*.ts",
"default": "./src/hooks/*.ts"
},
- "./globals": "./src/globals.css"
+ "./lib/*": {
+ "types": "./src/lib/*.ts",
+ "default": "./src/lib/*.ts"
+ }
},
"scripts": {
"build": "echo '@openstatus/ui has no build step (registry builds separately)'",
@@ -40,6 +64,7 @@
"tsc": "tsc --noEmit"
},
"dependencies": {
+ "@ai-sdk/react": "catalog:",
"@date-fns/utc": "catalog:",
"@dnd-kit/core": "catalog:",
"@dnd-kit/modifiers": "catalog:",
@@ -69,12 +94,18 @@
"@radix-ui/react-tabs": "catalog:",
"@radix-ui/react-toggle": "catalog:",
"@radix-ui/react-tooltip": "catalog:",
+ "@radix-ui/react-visually-hidden": "catalog:",
+ "@tanstack/react-query": "catalog:",
+ "@tanstack/react-table": "catalog:",
+ "@tanstack/react-virtual": "catalog:",
+ "ai": "catalog:",
"class-variance-authority": "catalog:",
"clsx": "catalog:",
"cmdk": "catalog:",
"date-fns": "catalog:",
"lucide-react": "catalog:",
"next": "catalog:",
+ "nuqs": "catalog:",
"qr-code-styling": "catalog:",
"radix-ui": "catalog:",
"react": "catalog:",
diff --git a/packages/ui/src/components/custom/date-picker-with-range.tsx b/packages/ui/src/components/custom/date-picker-with-range.tsx
new file mode 100644
index 000000000..d10ce233e
--- /dev/null
+++ b/packages/ui/src/components/custom/date-picker-with-range.tsx
@@ -0,0 +1,350 @@
+"use client";
+
+import type { DatePreset } from "@openstatus/ui/components/data-table-filters/types";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { Calendar } from "@openstatus/ui/components/ui/calendar";
+import { Input } from "@openstatus/ui/components/ui/input";
+import { Kbd } from "@openstatus/ui/components/ui/kbd";
+import { Label } from "@openstatus/ui/components/ui/label";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@openstatus/ui/components/ui/popover";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@openstatus/ui/components/ui/select";
+import { Separator } from "@openstatus/ui/components/ui/separator";
+import { useDebounce } from "@openstatus/ui/hooks/use-debounce";
+import { presets as defaultPresets } from "@openstatus/ui/lib/date-preset";
+import { cn } from "@openstatus/ui/lib/utils";
+import { endOfDay, format } from "date-fns";
+import { Calendar as CalendarIcon } from "lucide-react";
+import * as React from "react";
+import type { DateRange } from "react-day-picker";
+
+interface DatePickerWithRangeProps extends React.HTMLAttributes<HTMLDivElement> {
+ date: DateRange | undefined;
+ setDate: (date: DateRange | undefined) => void;
+ presets?: DatePreset[];
+}
+
+/** The presets span the selectable window - nothing outside them is queryable. */
+function getBounds(presets: DatePreset[]) {
+ const from = presets.map((preset) => preset.from.getTime());
+ const to = presets.map((preset) => preset.to.getTime());
+ return {
+ min: from.length ? new Date(Math.min(...from)) : undefined,
+ max: to.length ? new Date(Math.max(...to)) : undefined,
+ };
+}
+
+function clampToBounds(date: Date | undefined, min?: Date, max?: Date) {
+ if (!date) return undefined;
+ if (min && date < min) return min;
+ if (max && date > max) return max;
+ return date;
+}
+
+export function DatePickerWithRange({
+ className,
+ date,
+ setDate,
+ presets = defaultPresets,
+}: DatePickerWithRangeProps) {
+ const [open, setOpen] = React.useState(false);
+ const { min, max } = React.useMemo(() => getBounds(presets), [presets]);
+
+ const onCalendarSelect = React.useCallback(
+ (range: DateRange | undefined) => {
+ if (!range) {
+ setDate(undefined);
+ return;
+ }
+ // A day in the calendar means that whole day, but react-day-picker
+ // returns its midnight - without this the last day gets excluded.
+ setDate({
+ from: clampToBounds(range.from, min, max),
+ to: clampToBounds(range.to ? endOfDay(range.to) : undefined, min, max),
+ });
+ },
+ [setDate, min, max],
+ );
+
+ React.useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ if (!open) return;
+
+ presets.map((preset) => {
+ if (preset.shortcut === e.key) {
+ setDate({ from: preset.from, to: preset.to });
+ }
+ });
+ };
+ document.addEventListener("keydown", down);
+ return () => document.removeEventListener("keydown", down);
+ }, [setDate, presets, open]);
+
+ return (
+ <div className={cn("grid gap-2", className)}>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ id="date"
+ variant="outline"
+ className={cn(
+ "hover:bg-muted/50 max-w-full justify-start truncate text-left font-normal shadow-none",
+ !date && "text-muted-foreground",
+ )}
+ >
+ <CalendarIcon className="h-4 w-4" />
+ {date?.from ? (
+ date.to ? (
+ <span className="truncate">
+ {format(date.from, "LLL dd, y")} -{" "}
+ {format(date.to, "LLL dd, y")}
+ </span>
+ ) : (
+ format(date.from, "LLL dd, y")
+ )
+ ) : (
+ <span>Pick a date</span>
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0" align="start">
+ <div className="flex flex-col justify-between sm:flex-row">
+ <div className="hidden sm:block">
+ <DatePresets
+ onSelect={setDate}
+ selected={date}
+ presets={presets}
+ />
+ </div>
+ <div className="block p-3 sm:hidden">
+ <DatePresetsSelect
+ onSelect={setDate}
+ selected={date}
+ presets={presets}
+ />
+ </div>
+ <Separator orientation="vertical" className="h-auto w-px" />
+ <Calendar
+ // This repo pins react-day-picker 8, where the prop is still
+ // `initialFocus` — `autoFocus` only lands in 10.
+ initialFocus
+ mode="range"
+ defaultMonth={date?.from}
+ selected={date}
+ onSelect={onCalendarSelect}
+ numberOfMonths={1}
+ fromDate={min}
+ toDate={max}
+ disabled={[
+ ...(min ? [{ before: min }] : []),
+ ...(max ? [{ after: max }] : []),
+ ]}
+ />
+ </div>
+ <Separator />
+ <CustomDateRange
+ onSelect={setDate}
+ selected={date}
+ min={min}
+ max={max}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ );
+}
+
+function DatePresets({
+ selected,
+ onSelect,
+ presets,
+}: {
+ selected: DateRange | undefined;
+ onSelect: (date: DateRange | undefined) => void;
+ presets: DatePreset[];
+}) {
+ return (
+ <div className="flex flex-col gap-2 p-3">
+ <p className="text-muted-foreground mx-3 text-xs uppercase">Date Range</p>
+ <div className="grid gap-1">
+ {presets.map(({ label, shortcut, from, to }) => {
+ const isActive = selected?.from === from && selected?.to === to;
+ return (
+ <Button
+ key={label}
+ variant={isActive ? "outline" : "ghost"}
+ onClick={() => onSelect({ from, to })}
+ className={cn(
+ "flex items-center justify-between gap-6",
+ !isActive && "border border-transparent!",
+ )}
+ >
+ <span className="mr-auto">{label}</span>
+ <Kbd className="uppercase">{shortcut}</Kbd>
+ </Button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+function DatePresetsSelect({
+ selected,
+ onSelect,
+ presets,
+}: {
+ selected: DateRange | undefined;
+ onSelect: (date: DateRange | undefined) => void;
+ presets: DatePreset[];
+}) {
+ function findPreset(from?: Date, to?: Date) {
+ return presets.find((p) => p.from === from && p.to === to)?.shortcut;
+ }
+ const [value, setValue] = React.useState<string | undefined>(
+ findPreset(selected?.from, selected?.to),
+ );
+
+ React.useEffect(() => {
+ const preset = findPreset(selected?.from, selected?.to);
+ if (preset === value) return;
+ setValue(preset);
+ }, [selected, presets]);
+
+ return (
+ <Select
+ value={value}
+ onValueChange={(v) => {
+ const preset = presets.find((p) => p.shortcut === v);
+ if (preset) {
+ onSelect({ from: preset.from, to: preset.to });
+ }
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Date Presets" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectLabel>Date Presets</SelectLabel>
+ {presets.map(({ label, shortcut }) => {
+ return (
+ <SelectItem
+ key={label}
+ value={shortcut}
+ className="flex items-center justify-between [&>span:last-child]:flex [&>span:last-child]:w-full [&>span:last-child]:justify-between"
+ >
+ <span>{label}</span>
+ <Kbd className="ml-2 uppercase">{shortcut}</Kbd>
+ </SelectItem>
+ );
+ })}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+}
+
+function CustomDateRange({
+ selected,
+ onSelect,
+ min,
+ max,
+}: {
+ selected: DateRange | undefined;
+ onSelect: (date: DateRange | undefined) => void;
+ min?: Date;
+ max?: Date;
+}) {
+ const [range, setRange] = React.useState<DateRange | undefined>(selected);
+ const debouncedRange = useDebounce(range, 1000);
+
+ const selectedFrom = selected?.from?.getTime();
+ const selectedTo = selected?.to?.getTime();
+
+ const formatDateForInput = (date: Date | undefined): string => {
+ if (!date) return "";
+ const utcDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
+ return utcDate.toISOString().slice(0, 16);
+ };
+
+ /** Presets and the calendar write `selected` - adopt it as the new draft,
+ * otherwise editing one endpoint submits the other one from a stale range. */
+ React.useEffect(() => {
+ setRange(selected);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedFrom, selectedTo]);
+
+ React.useEffect(() => {
+ if (
+ debouncedRange?.from?.getTime() === selectedFrom &&
+ debouncedRange?.to?.getTime() === selectedTo
+ ) {
+ return;
+ }
+ onSelect(debouncedRange);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [debouncedRange]);
+
+ /** The calendar disables anything outside the presets - typing must not
+ * slip past the same window. */
+ const isWithinBounds = (date: Date) =>
+ !(min && date < min) && !(max && date > max);
+
+ return (
+ <div className="flex flex-col gap-2 p-3">
+ <p className="text-muted-foreground text-xs uppercase">Custom Range</p>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <div className="grid w-full gap-1.5">
+ <Label htmlFor="from">Start</Label>
+ <Input
+ key={formatDateForInput(selected?.from)}
+ type="datetime-local"
+ id="from"
+ name="from"
+ min={min ? formatDateForInput(min) : undefined}
+ max={max ? formatDateForInput(max) : undefined}
+ defaultValue={formatDateForInput(selected?.from)}
+ onChange={(e) => {
+ const newDate = new Date(e.target.value);
+ if (Number.isNaN(newDate.getTime())) return;
+ if (!isWithinBounds(newDate)) return;
+ setRange((prev) => ({ from: newDate, to: prev?.to }));
+ }}
+ disabled={!selected?.from}
+ />
+ </div>
+ <div className="grid w-full gap-1.5">
+ <Label htmlFor="to">End</Label>
+ <Input
+ key={formatDateForInput(selected?.to)}
+ type="datetime-local"
+ id="to"
+ name="to"
+ min={min ? formatDateForInput(min) : undefined}
+ max={max ? formatDateForInput(max) : undefined}
+ defaultValue={formatDateForInput(selected?.to)}
+ onChange={(e) => {
+ const newDate = new Date(e.target.value);
+ if (Number.isNaN(newDate.getTime())) return;
+ if (!isWithinBounds(newDate)) return;
+ setRange((prev) => ({ from: prev?.from, to: newDate }));
+ }}
+ disabled={!selected?.to}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/custom/slider.tsx b/packages/ui/src/components/custom/slider.tsx
new file mode 100644
index 000000000..724b93f2a
--- /dev/null
+++ b/packages/ui/src/components/custom/slider.tsx
@@ -0,0 +1,36 @@
+"use client";
+
+import { cn } from "@openstatus/ui/lib/utils";
+import * as SliderPrimitive from "@radix-ui/react-slider";
+import * as React from "react";
+
+function Slider({
+ className,
+ ...props
+}: React.ComponentProps<typeof SliderPrimitive.Root>) {
+ const initialValue = Array.isArray(props.value)
+ ? props.value
+ : [props.min, props.max];
+
+ return (
+ <SliderPrimitive.Root
+ data-slot="slider"
+ className={cn(
+ "relative flex w-full touch-none items-center select-none",
+ className,
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track className="bg-secondary relative h-2 w-full grow overflow-hidden rounded-full">
+ <SliderPrimitive.Range className="bg-primary absolute h-full" />
+ </SliderPrimitive.Track>
+ {initialValue.map((_, index) => (
+ <React.Fragment key={index}>
+ <SliderPrimitive.Thumb className="border-primary bg-background focus-visible:border-ring focus-visible:ring-ring/50 block h-4 w-4 rounded-full border-2 transition-all outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50" />
+ </React.Fragment>
+ ))}
+ </SliderPrimitive.Root>
+ );
+}
+
+export { Slider };
diff --git a/packages/ui/src/components/custom/sortable.tsx b/packages/ui/src/components/custom/sortable.tsx
new file mode 100644
index 000000000..a88eaf293
--- /dev/null
+++ b/packages/ui/src/components/custom/sortable.tsx
@@ -0,0 +1,351 @@
+"use client";
+
+import type {
+ DndContextProps,
+ DraggableSyntheticListeners,
+ DropAnimation,
+ UniqueIdentifier,
+} from "@dnd-kit/core";
+import {
+ closestCenter,
+ defaultDropAnimationSideEffects,
+ DndContext,
+ DragOverlay,
+ KeyboardSensor,
+ MouseSensor,
+ TouchSensor,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import {
+ restrictToHorizontalAxis,
+ restrictToParentElement,
+ restrictToVerticalAxis,
+} from "@dnd-kit/modifiers";
+import {
+ arrayMove,
+ horizontalListSortingStrategy,
+ SortableContext,
+ useSortable,
+ verticalListSortingStrategy,
+ type SortableContextProps,
+} from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { composeRefs } from "@openstatus/ui/lib/compose-refs";
+import { cn } from "@openstatus/ui/lib/utils";
+import { Slot, type SlotProps } from "@radix-ui/react-slot";
+import * as React from "react";
+import { createPortal } from "react-dom";
+
+const orientationConfig = {
+ vertical: {
+ modifiers: [restrictToVerticalAxis, restrictToParentElement],
+ strategy: verticalListSortingStrategy,
+ },
+ horizontal: {
+ modifiers: [restrictToHorizontalAxis, restrictToParentElement],
+ strategy: horizontalListSortingStrategy,
+ },
+ mixed: {
+ modifiers: [restrictToParentElement],
+ strategy: undefined,
+ },
+};
+
+interface SortableProps<
+ TData extends { id: UniqueIdentifier },
+> extends DndContextProps {
+ /**
+ * An array of data items that the sortable component will render.
+ * @example
+ * value={[
+ * { id: 1, name: 'Item 1' },
+ * { id: 2, name: 'Item 2' },
+ * ]}
+ */
+ value: TData[];
+
+ /**
+ * An optional callback function that is called when the order of the data items changes.
+ * It receives the new array of items as its argument.
+ * @example
+ * onValueChange={(items) => console.log(items)}
+ */
+ onValueChange?: (items: TData[]) => void;
+
+ /**
+ * An optional callback function that is called when an item is moved.
+ * It receives an event object with `activeIndex` and `overIndex` properties, representing the original and new positions of the moved item.
+ * This will override the default behavior of updating the order of the data items.
+ * @type (event: { activeIndex: number; overIndex: number }) => void
+ * @example
+ * onMove={(event) => console.log(`Item moved from index ${event.activeIndex} to index ${event.overIndex}`)}
+ */
+ onMove?: (event: { activeIndex: number; overIndex: number }) => void;
+
+ /**
+ * A collision detection strategy that will be used to determine the closest sortable item.
+ * @default closestCenter
+ * @type DndContextProps["collisionDetection"]
+ */
+ collisionDetection?: DndContextProps["collisionDetection"];
+
+ /**
+ * An array of modifiers that will be used to modify the behavior of the sortable component.
+ * @default
+ * [restrictToVerticalAxis, restrictToParentElement]
+ * @type Modifier[]
+ */
+ modifiers?: DndContextProps["modifiers"];
+
+ /**
+ * A sorting strategy that will be used to determine the new order of the data items.
+ * @default verticalListSortingStrategy
+ * @type SortableContextProps["strategy"]
+ */
+ strategy?: SortableContextProps["strategy"];
+
+ /**
+ * Specifies the axis for the drag-and-drop operation. It can be "vertical", "horizontal", or "both".
+ * @default "vertical"
+ * @type "vertical" | "horizontal" | "mixed"
+ */
+ orientation?: "vertical" | "horizontal" | "mixed";
+
+ /**
+ * An optional React node that is rendered on top of the sortable component.
+ * It can be used to display additional information or controls.
+ * @default null
+ * @type React.ReactNode | null
+ * @example
+ * overlay={<Skeleton className="w-full h-8" />}
+ */
+ overlay?: React.ReactNode | null;
+}
+
+function Sortable<TData extends { id: UniqueIdentifier }>({
+ value,
+ onValueChange,
+ onDragStart,
+ onDragEnd,
+ onDragCancel,
+ collisionDetection = closestCenter,
+ modifiers,
+ strategy,
+ onMove,
+ orientation = "vertical",
+ overlay,
+ children,
+ ...props
+}: SortableProps<TData>) {
+ const [activeId, setActiveId] = React.useState<UniqueIdentifier | null>(null);
+ const sensors = useSensors(
+ useSensor(MouseSensor),
+ useSensor(TouchSensor),
+ useSensor(KeyboardSensor),
+ );
+
+ const config = orientationConfig[orientation];
+
+ return (
+ <DndContext
+ modifiers={modifiers ?? config.modifiers}
+ sensors={sensors}
+ onDragStart={(event) => {
+ setActiveId(event.active.id);
+ onDragStart?.(event);
+ }}
+ onDragEnd={(event) => {
+ const { active, over } = event;
+ if (over && active.id !== over?.id) {
+ const activeIndex = value.findIndex((item) => item.id === active.id);
+ const overIndex = value.findIndex((item) => item.id === over.id);
+
+ if (onMove) {
+ onMove({ activeIndex, overIndex });
+ } else {
+ onValueChange?.(arrayMove(value, activeIndex, overIndex));
+ }
+ }
+ setActiveId(null);
+ onDragEnd?.(event);
+ }}
+ onDragCancel={(event) => {
+ setActiveId?.(null);
+ onDragCancel?.(event);
+ }}
+ collisionDetection={collisionDetection}
+ {...props}
+ >
+ <SortableContext items={value} strategy={strategy ?? config.strategy}>
+ {children}
+ </SortableContext>
+ {overlay
+ ? // https://docs.dndkit.com/api-documentation/draggable/drag-overlay#portals
+ createPortal(
+ <SortableOverlay activeId={activeId}>{overlay}</SortableOverlay>,
+ document.body,
+ )
+ : null}
+ </DndContext>
+ );
+}
+
+const dropAnimationOpts: DropAnimation = {
+ sideEffects: defaultDropAnimationSideEffects({
+ styles: {
+ active: {
+ opacity: "0.4",
+ },
+ },
+ }),
+};
+
+interface SortableOverlayProps extends React.ComponentPropsWithRef<
+ typeof DragOverlay
+> {
+ activeId?: UniqueIdentifier | null;
+}
+
+function SortableOverlay({
+ activeId,
+ dropAnimation = dropAnimationOpts,
+ children,
+ ...props
+}: SortableOverlayProps) {
+ return (
+ <DragOverlay dropAnimation={dropAnimation} {...props}>
+ {activeId ? (
+ <SortableItem value={activeId} className="cursor-grabbing" asChild>
+ {children}
+ </SortableItem>
+ ) : null}
+ </DragOverlay>
+ );
+}
+
+interface SortableItemContextProps {
+ attributes: React.HTMLAttributes<HTMLElement>;
+ listeners: DraggableSyntheticListeners | undefined;
+ isDragging?: boolean;
+}
+
+const SortableItemContext = React.createContext<SortableItemContextProps>({
+ attributes: {},
+ listeners: undefined,
+ isDragging: false,
+});
+
+function useSortableItem() {
+ const context = React.useContext(SortableItemContext);
+
+ if (!context) {
+ throw new Error("useSortableItem must be used within a SortableItem");
+ }
+
+ return context;
+}
+
+interface SortableItemProps extends SlotProps {
+ /**
+ * The unique identifier of the item.
+ * @example "item-1"
+ * @type UniqueIdentifier
+ */
+ value: UniqueIdentifier;
+
+ /**
+ * Specifies whether the item should act as a trigger for the drag-and-drop action.
+ * @default false
+ * @type boolean | undefined
+ */
+ asTrigger?: boolean;
+
+ /**
+ * Merges the item's props into its immediate child.
+ * @default false
+ * @type boolean | undefined
+ */
+ asChild?: boolean;
+}
+
+function SortableItem({
+ value,
+ asTrigger,
+ asChild,
+ className,
+ ref,
+ ...props
+}: SortableItemProps & { ref?: React.Ref<HTMLDivElement> }) {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id: value });
+
+ const context = React.useMemo<SortableItemContextProps>(
+ () => ({
+ attributes,
+ listeners,
+ isDragging,
+ }),
+ [attributes, listeners, isDragging],
+ );
+ const style: React.CSSProperties = {
+ opacity: isDragging ? 0.5 : 1,
+ transform: CSS.Translate.toString(transform),
+ transition,
+ };
+
+ const Comp = asChild ? Slot : "div";
+
+ return (
+ <SortableItemContext.Provider value={context}>
+ <Comp
+ data-state={isDragging ? "dragging" : undefined}
+ className={cn(
+ "data-[state=dragging]:cursor-grabbing",
+ { "cursor-grab": !isDragging && asTrigger },
+ className,
+ )}
+ ref={composeRefs(ref, setNodeRef as React.Ref<HTMLDivElement>)}
+ style={style}
+ {...(asTrigger ? attributes : {})}
+ {...(asTrigger ? listeners : {})}
+ {...props}
+ />
+ </SortableItemContext.Provider>
+ );
+}
+
+interface SortableDragHandleProps extends React.ComponentProps<typeof Button> {
+ withHandle?: boolean;
+}
+
+function SortableDragHandle({
+ className,
+ ref,
+ ...props
+}: SortableDragHandleProps) {
+ const { attributes, listeners, isDragging } = useSortableItem();
+
+ return (
+ <Button
+ ref={composeRefs(ref)}
+ data-state={isDragging ? "dragging" : undefined}
+ className={cn(
+ "cursor-grab data-[state=dragging]:cursor-grabbing",
+ className,
+ )}
+ {...attributes}
+ {...listeners}
+ {...props}
+ />
+ );
+}
+
+export { Sortable, SortableDragHandle, SortableItem, SortableOverlay };
diff --git a/packages/ui/src/components/custom/table.tsx b/packages/ui/src/components/custom/table.tsx
new file mode 100644
index 000000000..d64abf7dd
--- /dev/null
+++ b/packages/ui/src/components/custom/table.tsx
@@ -0,0 +1,99 @@
+import { cn } from "@openstatus/ui/lib/utils";
+import * as React from "react";
+
+interface TableProps extends React.ComponentProps<"table"> {
+ containerClassName?: string;
+}
+
+function Table({
+ className,
+ containerClassName,
+ onScroll,
+ ...props
+}: TableProps) {
+ return (
+ <div
+ className={cn("w-full overflow-auto", containerClassName)}
+ // REMINDER: we are not scrolling the table, but the container
+ {...{ onScroll }}
+ >
+ <table
+ className={cn("w-full caption-bottom text-sm", className)}
+ {...props}
+ />
+ </div>
+ );
+}
+
+function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
+ return <thead className={cn("[&_tr]:border-b", className)} {...props} />;
+}
+
+function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
+ return (
+ <tbody className={cn("[&_tr:last-child]:border-0", className)} {...props} />
+ );
+}
+
+function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
+ return (
+ <tfoot
+ className={cn(
+ "bg-primary text-primary-foreground font-medium",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
+ return (
+ <tr
+ className={cn(
+ "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TableHead({ className, ...props }: React.ComponentProps<"th">) {
+ return (
+ <th
+ className={cn(
+ "text-muted-foreground h-10 px-2 text-left align-middle font-medium",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TableCell({ className, ...props }: React.ComponentProps<"td">) {
+ return <td className={cn("p-2 align-middle", className)} {...props} />;
+}
+
+function TableCaption({
+ className,
+ ...props
+}: React.ComponentProps<"caption">) {
+ return (
+ <caption
+ className={cn("text-muted-foreground mt-4 text-sm", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Table,
+ TableHeader,
+ TableBody,
+ TableFooter,
+ TableHead,
+ TableRow,
+ TableCell,
+ TableCaption,
+};
diff --git a/packages/ui/src/components/custom/text-with-tooltip.tsx b/packages/ui/src/components/custom/text-with-tooltip.tsx
new file mode 100644
index 000000000..f5744b031
--- /dev/null
+++ b/packages/ui/src/components/custom/text-with-tooltip.tsx
@@ -0,0 +1,67 @@
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui/components/ui/tooltip";
+import { cn } from "@openstatus/ui/lib/utils";
+import React, { useEffect, useRef, useState } from "react";
+
+interface TextWithTooltipProps {
+ text: string | number;
+ className?: string;
+ style?: React.CSSProperties;
+}
+
+export function TextWithTooltip({
+ text,
+ className,
+ style,
+}: TextWithTooltipProps) {
+ const [isTruncated, setIsTruncated] = useState<boolean>(false);
+ const textRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const checkTruncation = () => {
+ if (textRef.current) {
+ const { scrollWidth, clientWidth } = textRef.current;
+ setIsTruncated(scrollWidth > clientWidth);
+ }
+ };
+
+ const resizeObserver = new ResizeObserver(() => {
+ checkTruncation();
+ });
+
+ if (textRef.current) {
+ resizeObserver.observe(textRef.current);
+ }
+
+ checkTruncation();
+
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }, []);
+
+ return (
+ <TooltipProvider delayDuration={100} disableHoverableContent>
+ <Tooltip>
+ <TooltipTrigger disabled={!isTruncated} asChild>
+ <div
+ ref={textRef}
+ className={cn(
+ "truncate",
+ !isTruncated && "pointer-events-none",
+ className,
+ )}
+ style={style}
+ >
+ {text}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>{text}</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/controls.tsx b/packages/ui/src/components/data-table-filters/controls.tsx
new file mode 100644
index 000000000..6b754c77e
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/controls.tsx
@@ -0,0 +1,38 @@
+import { useLocalStorage } from "@openstatus/ui/hooks/use-local-storage";
+import { CONTROLS_KEY } from "@openstatus/ui/lib/data-table-filters/local-storage";
+import { createContext, useContext } from "react";
+
+interface ControlsContextType {
+ open: boolean;
+ setOpen: React.Dispatch<React.SetStateAction<boolean>>;
+}
+
+export const ControlsContext = createContext<ControlsContextType | null>(null);
+
+export function ControlsProvider({ children }: { children: React.ReactNode }) {
+ const [open, setOpen] = useLocalStorage(CONTROLS_KEY, true);
+
+ return (
+ <ControlsContext.Provider value={{ open, setOpen }}>
+ <div
+ // REMINDER: access the data-expanded state with tailwind via `group-data-[expanded=true]/controls:block`
+ // In tailwindcss v4, we could even use `group-data-expanded/controls:block`
+ // `contents` so the group never becomes a box in the height chain
+ className="group/controls contents"
+ data-expanded={open}
+ >
+ {children}
+ </div>
+ </ControlsContext.Provider>
+ );
+}
+
+export function useControls() {
+ const context = useContext(ControlsContext);
+
+ if (!context) {
+ throw new Error("useControls must be used within a ControlsProvider");
+ }
+
+ return context as ControlsContextType;
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-badge.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-badge.tsx
new file mode 100644
index 000000000..4d81c8eff
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-badge.tsx
@@ -0,0 +1,24 @@
+export function DataTableCellBadge({
+ value,
+ color,
+}: {
+ value: string | number;
+ color?: string;
+}) {
+ return (
+ <span
+ className="rounded-sm border px-1.5 py-0.5 font-mono text-xs"
+ style={
+ color
+ ? {
+ color,
+ backgroundColor: `${color}1a`,
+ borderColor: `${color}33`,
+ }
+ : undefined
+ }
+ >
+ {value}
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-bar.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-bar.tsx
new file mode 100644
index 000000000..382a3a3b3
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-bar.tsx
@@ -0,0 +1,46 @@
+import { hexToRgb } from "@openstatus/ui/lib/data-table-filters/colors";
+
+const OPACITY = 0.5;
+const BORDER_OPACITY = 1;
+
+export function DataTableCellBar({
+ value,
+ min,
+ max,
+ unit,
+ color,
+}: {
+ value: number;
+ min: number;
+ max: number;
+ unit?: string;
+ color?: string;
+}) {
+ const range = max - min;
+ const ratio =
+ range === 0 ? 0 : Math.max(0, Math.min(1, (value - min) / range));
+
+ const formatted = new Intl.NumberFormat("en-US", {
+ maximumFractionDigits: 3,
+ }).format(value);
+
+ return (
+ <div className="relative -m-2 p-2">
+ <div
+ className="absolute inset-y-0 left-0"
+ style={{
+ width: `${ratio * 100}%`,
+ backgroundColor: color
+ ? `rgba(${hexToRgb(color)}, ${OPACITY})`
+ : `var(--muted)`,
+ opacity: color ? undefined : OPACITY,
+ borderRight: `1px solid ${color ? `rgba(${hexToRgb(color)}, ${BORDER_OPACITY})` : `var(--border)`}`,
+ }}
+ />
+ <span className="relative font-mono">
+ {formatted}
+ {unit && <span className="text-muted-foreground">{unit}</span>}
+ </span>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-boolean.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-boolean.tsx
new file mode 100644
index 000000000..c571f9c35
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-boolean.tsx
@@ -0,0 +1,24 @@
+import { Check, Minus } from "lucide-react";
+
+export function DataTableCellBoolean({
+ value,
+ color,
+}: {
+ value: boolean;
+ color?: string;
+}) {
+ if (value) {
+ return (
+ <Check
+ className={`ml-auto h-4 w-4 ${color ? "" : "text-foreground"}`}
+ style={color ? { color } : undefined}
+ />
+ );
+ }
+ return (
+ <Minus
+ className={`ml-auto h-4 w-4 ${color ? "" : "text-muted-foreground/50"}`}
+ style={color ? { color } : undefined}
+ />
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-code.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-code.tsx
new file mode 100644
index 000000000..4017e205c
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-code.tsx
@@ -0,0 +1,13 @@
+export function DataTableCellCode({
+ value,
+ color,
+}: {
+ value: string | number;
+ color?: string;
+}) {
+ return (
+ <span className="font-mono" style={color ? { color } : undefined}>
+ {value}
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-gauge.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-gauge.tsx
new file mode 100644
index 000000000..8e74c1507
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-gauge.tsx
@@ -0,0 +1,78 @@
+import { hexToRgb } from "@openstatus/ui/lib/data-table-filters/colors";
+
+const BG_OPACITY = 0.2;
+const FOREGROUND_OPACITY = 0.5;
+
+export function DataTableCellGauge({
+ value,
+ min,
+ max,
+ unit,
+ color,
+}: {
+ value: number;
+ min: number;
+ max: number;
+ unit?: string;
+ color?: string;
+}) {
+ const range = max - min;
+ const ratio =
+ range === 0 ? 0 : Math.max(0, Math.min(1, (value - min) / range));
+
+ // SVG circle gauge calculations
+ const size = 20;
+ const strokeWidth = 4;
+ const viewBox = 120;
+ const radius = 50;
+ const circumference = 2 * Math.PI * radius;
+ const strokeDashoffset = circumference - ratio * circumference;
+
+ const bgStroke = color
+ ? `rgba(${hexToRgb(color)}, ${BG_OPACITY})`
+ : `var(--muted)`;
+
+ const fgStroke = color
+ ? `rgba(${hexToRgb(color)}, ${FOREGROUND_OPACITY})`
+ : `var(--muted-foreground)`;
+
+ const formatted = new Intl.NumberFormat("en-US", {
+ maximumFractionDigits: 3,
+ }).format(value);
+
+ return (
+ <div className="flex items-center gap-1.5">
+ <svg
+ fill="none"
+ height={size}
+ width={size}
+ viewBox={`0 0 ${viewBox} ${viewBox}`}
+ className="shrink-0 -rotate-90"
+ >
+ <circle
+ strokeWidth={strokeWidth * 4}
+ stroke={bgStroke}
+ fill="transparent"
+ r={radius}
+ cx={viewBox / 2}
+ cy={viewBox / 2}
+ />
+ <circle
+ strokeWidth={strokeWidth * 4}
+ strokeDasharray={`${circumference} ${circumference}`}
+ strokeDashoffset={strokeDashoffset}
+ strokeLinecap="round"
+ stroke={fgStroke}
+ fill="transparent"
+ r={radius}
+ cx={viewBox / 2}
+ cy={viewBox / 2}
+ />
+ </svg>
+ <span className="font-mono">
+ {formatted}
+ {unit && <span className="text-muted-foreground">{unit}</span>}
+ </span>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-heatmap.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-heatmap.tsx
new file mode 100644
index 000000000..d98a6c539
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-heatmap.tsx
@@ -0,0 +1,44 @@
+import { hexToRgb } from "@openstatus/ui/lib/data-table-filters/colors";
+
+const OPACITY = 0.1;
+
+export function DataTableCellHeatmap({
+ value,
+ min,
+ max,
+ unit,
+ color,
+}: {
+ value: number;
+ min: number;
+ max: number;
+ unit?: string;
+ color?: string;
+}) {
+ const range = max - min;
+ const ratio =
+ range === 0 ? 0 : Math.max(0, Math.min(1, (value - min) / range));
+ const opacity = ratio * OPACITY;
+
+ const formatted = new Intl.NumberFormat("en-US", {
+ maximumFractionDigits: 3,
+ }).format(value);
+
+ return (
+ <div className="relative -m-2 p-2">
+ <div
+ className="absolute inset-0"
+ style={{
+ backgroundColor: color
+ ? `rgba(${hexToRgb(color)}, ${opacity})`
+ : `var(--muted-foreground)`,
+ opacity: color ? undefined : opacity,
+ }}
+ />
+ <span className="relative font-mono">
+ {formatted}
+ {unit && <span className="text-muted-foreground">{unit}</span>}
+ </span>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-level-indicator.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-level-indicator.tsx
new file mode 100644
index 000000000..064dfdb9e
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-level-indicator.tsx
@@ -0,0 +1,30 @@
+const LEVEL_COLORS: Record<string, string> = {
+ error: "bg-red-500",
+ warn: "bg-yellow-500",
+ warning: "bg-yellow-500",
+ info: "bg-blue-500",
+ debug: "bg-gray-400",
+ success: "bg-green-500",
+};
+
+export function DataTableCellLevelIndicator({
+ value,
+ color: colorOverride,
+}: {
+ value: string;
+ color?: string;
+}) {
+ const builtinColor = LEVEL_COLORS[value.toLowerCase()] ?? "bg-gray-300";
+ return (
+ <span
+ className="inline-flex items-center gap-1.5"
+ style={colorOverride ? { color: colorOverride } : undefined}
+ >
+ <span
+ className={`inline-block size-3.5 shrink-0 rounded-sm ${colorOverride ? "" : builtinColor}`}
+ style={colorOverride ? { backgroundColor: colorOverride } : undefined}
+ />
+ <span>{value}</span>
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-number.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-number.tsx
new file mode 100644
index 000000000..28eff64da
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-number.tsx
@@ -0,0 +1,20 @@
+export function DataTableCellNumber({
+ value,
+ unit,
+ color,
+}: {
+ value: number;
+ unit?: string;
+ color?: string;
+}) {
+ const formatted = new Intl.NumberFormat("en-US", {
+ maximumFractionDigits: 3,
+ }).format(value);
+
+ return (
+ <span className="font-mono" style={color ? { color } : undefined}>
+ {formatted}
+ {unit && <span className="text-muted-foreground">{unit}</span>}
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-star.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-star.tsx
new file mode 100644
index 000000000..8828e49c1
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-star.tsx
@@ -0,0 +1,21 @@
+import { Star } from "lucide-react";
+
+export function DataTableCellStar({ value }: { value: boolean }) {
+ if (value) {
+ return (
+ <span className="ml-auto inline-flex items-center">
+ <Star
+ className="h-4 w-4 fill-yellow-400 text-yellow-400"
+ aria-hidden="true"
+ />
+ <span className="sr-only">Favorited</span>
+ </span>
+ );
+ }
+ return (
+ <span className="ml-auto inline-flex items-center">
+ <Star className="text-muted-foreground/40 h-4 w-4" aria-hidden="true" />
+ <span className="sr-only">Not favorited</span>
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-status-code.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-status-code.tsx
new file mode 100644
index 000000000..a344f3eef
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-status-code.tsx
@@ -0,0 +1,19 @@
+import { getStatusColor } from "@openstatus/ui/lib/data-table-filters/status-code";
+
+export function DataTableCellStatusCode({
+ value,
+ color,
+}: {
+ value: number;
+ color?: string;
+}) {
+ const colors = getStatusColor(value);
+ return (
+ <span
+ className={`font-mono ${color ? "" : colors.text}`}
+ style={color ? { color } : undefined}
+ >
+ {value}
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-text.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-text.tsx
new file mode 100644
index 000000000..8ad9593fd
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-text.tsx
@@ -0,0 +1,11 @@
+import { TextWithTooltip } from "@openstatus/ui/components/custom/text-with-tooltip";
+
+export function DataTableCellText({
+ value,
+ color,
+}: {
+ value: string | number;
+ color?: string;
+}) {
+ return <TextWithTooltip text={value} style={color ? { color } : undefined} />;
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-timestamp.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-timestamp.tsx
new file mode 100644
index 000000000..6a73030c6
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/data-table-cell-timestamp.tsx
@@ -0,0 +1,18 @@
+"use client";
+
+import { HoverCardTimestamp } from "@openstatus/ui/components/data-table-filters/data-table-infinite/hover-card-timestamp";
+
+export function DataTableCellTimestamp({
+ date,
+ color,
+}: {
+ date: Date | string | number;
+ color?: string;
+}) {
+ const d = date instanceof Date ? date : new Date(date);
+ return (
+ <span style={color ? { color } : undefined}>
+ <HoverCardTimestamp date={d} />
+ </span>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-cell/index.tsx b/packages/ui/src/components/data-table-filters/data-table-cell/index.tsx
new file mode 100644
index 000000000..a30afb9bd
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-cell/index.tsx
@@ -0,0 +1,12 @@
+export { DataTableCellText } from "./data-table-cell-text";
+export { DataTableCellCode } from "./data-table-cell-code";
+export { DataTableCellNumber } from "./data-table-cell-number";
+export { DataTableCellBar } from "./data-table-cell-bar";
+export { DataTableCellHeatmap } from "./data-table-cell-heatmap";
+export { DataTableCellGauge } from "./data-table-cell-gauge";
+export { DataTableCellTimestamp } from "./data-table-cell-timestamp";
+export { DataTableCellBadge } from "./data-table-cell-badge";
+export { DataTableCellBoolean } from "./data-table-cell-boolean";
+export { DataTableCellStar } from "./data-table-cell-star";
+export { DataTableCellStatusCode } from "./data-table-cell-status-code";
+export { DataTableCellLevelIndicator } from "./data-table-cell-level-indicator";
diff --git a/packages/ui/src/components/data-table-filters/data-table-column-header.tsx b/packages/ui/src/components/data-table-filters/data-table-column-header.tsx
new file mode 100644
index 000000000..66f8a4a8c
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-column-header.tsx
@@ -0,0 +1,58 @@
+import { Button } from "@openstatus/ui/components/ui/button";
+import { cn } from "@openstatus/ui/lib/utils";
+import type { Column } from "@tanstack/react-table";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import type React from "react";
+
+interface DataTableColumnHeaderProps<
+ TData,
+ TValue,
+> extends React.ComponentProps<typeof Button> {
+ column: Column<TData, TValue>;
+ title: string;
+}
+
+export function DataTableColumnHeader<TData, TValue>({
+ column,
+ title,
+ className,
+ ...props
+}: DataTableColumnHeaderProps<TData, TValue>) {
+ if (!column.getCanSort()) {
+ return <div className={cn(className)}>{title}</div>;
+ }
+
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => {
+ column.toggleSorting(undefined);
+ }}
+ className={cn(
+ "flex h-7 w-full items-center justify-between gap-2 px-0 py-0 hover:bg-transparent",
+ className,
+ )}
+ {...props}
+ >
+ <span>{title}</span>
+ <span className="flex flex-col">
+ <ChevronUp
+ className={cn(
+ "-mb-0.5 size-3",
+ column.getIsSorted() === "asc"
+ ? "text-accent-foreground"
+ : "text-muted-foreground",
+ )}
+ />
+ <ChevronDown
+ className={cn(
+ "-mt-0.5 size-3",
+ column.getIsSorted() === "desc"
+ ? "text-accent-foreground"
+ : "text-muted-foreground",
+ )}
+ />
+ </span>
+ </Button>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-checkbox.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-checkbox.tsx
new file mode 100644
index 000000000..a2cfb6ccb
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-checkbox.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@openstatus/ui/components/ui/input-group";
+import { Label } from "@openstatus/ui/components/ui/label";
+import { Skeleton } from "@openstatus/ui/components/ui/skeleton";
+import { formatCompactNumber } from "@openstatus/ui/lib/format";
+import { cn } from "@openstatus/ui/lib/utils";
+import { Search } from "lucide-react";
+import { useMemo, useState } from "react";
+
+import type { DataTableCheckboxFilterField, Option } from "./types";
+
+export function DataTableFilterCheckbox<TData>({
+ value: _value,
+ options,
+ component,
+ keepEmptyOptions,
+}: DataTableCheckboxFilterField<TData>) {
+ const value = _value as string;
+ const [inputValue, setInputValue] = useState("");
+ const {
+ table,
+ columnFilters,
+ isLoading,
+ isFacetsLoading,
+ getFacetedUniqueValues,
+ } = useDataTable();
+ const column = table.getColumn(value);
+ // REMINDER: avoid using column?.getFilterValue()
+ const filterValue = columnFilters.find((i) => i.id === value)?.value;
+ const facetedValue =
+ getFacetedUniqueValues?.(table, value) || column?.getFacetedUniqueValues();
+
+ const Component = component;
+
+ // CHECK: it could be filterValue or searchValue
+ const filters = useMemo(
+ () =>
+ filterValue
+ ? Array.isArray(filterValue)
+ ? filterValue
+ : [filterValue]
+ : [],
+ [filterValue],
+ );
+
+ // `options` is a baseline, not the whole set: a column holds values nobody
+ // declared (an unusual status code) and declares values the data never
+ // contains. The facets know which values exist, so they win when present;
+ // `options` then only supplies labels. Selected values are kept regardless,
+ // so a filter can always be unchecked. `keepEmptyOptions` opts a column out
+ // of the pruning half: every declared option stays, at a count of zero.
+ const resolvedOptions = useMemo(() => {
+ if (!facetedValue?.size) {
+ // A value picked out of an earlier facet list is not in `options`, and a
+ // window with no rows would drop it here — leaving a filter that is
+ // applied but has no box to uncheck.
+ // Through a Set like the faceted branch below: the filter value is
+ // whatever the URL held, so `?region=ams,ams` would otherwise render two
+ // rows keyed on the same value.
+ const declaredValues = new Set(options?.map((option) => option.value));
+ const orphans = Array.from(new Set(filters as Option["value"][]))
+ .filter((value) => !declaredValues.has(value))
+ .map((value) => ({ label: String(value), value }) as Option);
+ return orphans.length > 0 ? [...(options ?? []), ...orphans] : options;
+ }
+ const present = new Set<Option["value"]>([
+ ...facetedValue.keys(),
+ ...filters,
+ ]);
+ // Declared options keep their declared order — regions are grouped, not
+ // alphabetical, and facets arrive count-descending.
+ const declared = keepEmptyOptions
+ ? options
+ : options?.filter((option) => present.has(option.value));
+ const declaredValues = new Set(declared?.map((option) => option.value));
+ const resolved = [
+ ...(declared ?? []),
+ ...Array.from(present)
+ .filter((value) => !declaredValues.has(value))
+ .map((value) => ({ label: String(value), value })),
+ ];
+ return resolved.every((option) => typeof option.value === "number")
+ ? resolved.sort((a, b) => (a.value as number) - (b.value as number))
+ : resolved;
+ }, [facetedValue, options, filters, keepEmptyOptions]);
+
+ // filter out the options based on the input value
+ const filterOptions = resolvedOptions?.filter(
+ (option) =>
+ inputValue === "" ||
+ option.label.toLowerCase().includes(inputValue.toLowerCase()),
+ );
+
+ // REMINDER: if no options are defined, while fetching data, we should show a skeleton
+ if (isLoading && !filterOptions?.length)
+ return (
+ <div className="border-border grid divide-y rounded-lg border">
+ {Array.from({ length: 3 }).map((_, index) => (
+ <div
+ key={index}
+ className="flex items-center justify-between gap-2 px-2 py-2.5"
+ >
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ <Skeleton className="h-4 w-full rounded-sm" />
+ </div>
+ ))}
+ </div>
+ );
+
+ return (
+ <div className="grid gap-2">
+ {resolvedOptions && resolvedOptions.length > 4 ? (
+ <InputGroup className="h-9 rounded-lg shadow-none">
+ <InputGroupAddon>
+ <Search className="mt-0.5 h-4 w-4" />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder="Search"
+ value={inputValue}
+ onChange={(e) => setInputValue(e.target.value)}
+ />
+ </InputGroup>
+ ) : null}
+ {/* FIXME: due to the added max-h and overflow-y-auto, the hover state and border is laying on top of the scroll bar */}
+ <div className="border-border max-h-[200px] overflow-y-auto rounded-lg border empty:border-none">
+ {filterOptions
+ // TODO: we shoudn't sort the options here, instead filterOptions should be sorted by default
+ // .sort((a, b) => a.label.localeCompare(b.label))
+ ?.map((option, index) => {
+ const checked = filters.includes(option.value);
+
+ return (
+ <div
+ key={String(option.value)}
+ className={cn(
+ "group hover:bg-accent/50 relative flex items-center space-x-2 px-2 py-2.5",
+ index !== filterOptions.length - 1 ? "border-b" : undefined,
+ )}
+ >
+ <Checkbox
+ id={`${value}-${option.value}`}
+ checked={checked}
+ onCheckedChange={(checked) => {
+ const newValue = checked
+ ? [...(filters || []), option.value]
+ : filters?.filter((value) => option.value !== value);
+ column?.setFilterValue(
+ newValue?.length ? newValue : undefined,
+ );
+ }}
+ className="border-foreground! shadow-none"
+ />
+ <Label
+ htmlFor={`${value}-${option.value}`}
+ className={cn(
+ "group-hover:text-accent-foreground flex w-full items-center justify-center gap-1 truncate",
+ checked ? "text-foreground" : "text-foreground/70",
+ )}
+ >
+ {Component ? (
+ <Component {...option} />
+ ) : (
+ <span className="truncate font-normal">{option.label}</span>
+ )}
+ <span className="ml-auto flex min-w-8 items-center justify-end font-mono text-xs">
+ {isLoading || isFacetsLoading ? (
+ <Skeleton className="h-4 w-8" />
+ ) : facetedValue?.has(option.value) ? (
+ formatCompactNumber(facetedValue.get(option.value) || 0)
+ ) : keepEmptyOptions && facetedValue?.size ? (
+ formatCompactNumber(0)
+ ) : null}
+ </span>
+ <button
+ type="button"
+ onClick={() => column?.setFilterValue([option.value])}
+ className={cn(
+ "text-muted-foreground hover:text-foreground absolute inset-y-0 right-0 hidden font-normal backdrop-blur-xs group-hover:block",
+ "focus-visible:border-ring focus-visible:ring-ring/50 rounded-md transition-all outline-none focus-visible:ring-[3px]",
+ )}
+ >
+ <span className="px-2">only</span>
+ </button>
+ </Label>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-command-ai/index.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-command-ai/index.tsx
new file mode 100644
index 000000000..cdcd5afbb
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-command-ai/index.tsx
@@ -0,0 +1,601 @@
+"use client";
+
+import { TextShimmer } from "@openstatus/ui/components/data-table-filters/data-table-filter-command-ai/text-shimmer";
+import {
+ columnFiltersParserFromSchema,
+ getFieldOptions,
+ getFilterValue,
+ getWordByCaretPosition,
+ replaceInputByFieldType,
+} from "@openstatus/ui/components/data-table-filters/data-table-filter-command/utils";
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import type { DataTableFilterField } from "@openstatus/ui/components/data-table-filters/types";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@openstatus/ui/components/ui/command";
+import { Kbd } from "@openstatus/ui/components/ui/kbd";
+import { Separator } from "@openstatus/ui/components/ui/separator";
+import { useHotKey } from "@openstatus/ui/hooks/use-hot-key";
+import { useLocalStorage } from "@openstatus/ui/hooks/use-local-storage";
+import { isStructuredQuery } from "@openstatus/ui/lib/data-table-filters/ai/index";
+import { useAIFilters } from "@openstatus/ui/lib/data-table-filters/hooks/use-ai-filters";
+import { getCommandHistoryKey } from "@openstatus/ui/lib/data-table-filters/local-storage";
+import type { SchemaDefinition } from "@openstatus/ui/lib/data-table-filters/store/schema/types";
+import type { TableSchemaDefinition } from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+import { formatCompactNumber } from "@openstatus/ui/lib/format";
+import { cn } from "@openstatus/ui/lib/utils";
+import { Command as CommandPrimitive } from "cmdk";
+import { formatDistanceToNow } from "date-fns";
+import { LoaderCircle, Search, Sparkles, X } from "lucide-react";
+import React, { useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+
+/** Suggestions kept in localStorage; only the newest five are ever rendered. */
+const MAX_COMMAND_HISTORY = 25;
+
+interface DataTableFilterAICommandProps {
+ /** BYOS schema definition for parsing/serializing filter values */
+ schema: SchemaDefinition;
+ /** Table schema definition for AI context generation */
+ tableSchema: TableSchemaDefinition;
+ /** API endpoint that streams AI filter results */
+ api: string;
+ /** Unique ID for this table (used to namespace localStorage) */
+ tableId?: string;
+}
+
+export function DataTableFilterAICommand({
+ schema,
+ tableSchema,
+ api,
+ tableId = "default",
+}: DataTableFilterAICommandProps) {
+ const {
+ table,
+ isLoading,
+ filterFields: _filterFields,
+ getFacetedUniqueValues,
+ } = useDataTable();
+ const columnFilters = table.getState().columnFilters;
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [open, setOpen] = useState<boolean>(false);
+ const [currentWord, setCurrentWord] = useState<string>("");
+ const isSerializingRef = useRef(false);
+ const filterFields = useMemo(
+ () => _filterFields?.filter((i) => !i.commandDisabled),
+ [_filterFields],
+ );
+ const columnParser = useMemo(
+ () => columnFiltersParserFromSchema({ schema, filterFields }),
+ [schema, filterFields],
+ );
+ const [inputValue, setInputValue] = useState<string>(
+ columnParser.serialize(columnFilters),
+ );
+ const [lastSearches, setLastSearches] = useLocalStorage<
+ {
+ search: string;
+ timestamp: number;
+ }[]
+ >(getCommandHistoryKey(tableId), []);
+
+ // Detect if the current input looks like natural language (for UI hints).
+ // Single-word input that partially matches a field name → structured mode.
+ // Multi-word input without key:value syntax → natural language mode.
+ const isNaturalLanguage = useMemo(() => {
+ const trimmed = inputValue.trim();
+ if (!trimmed) return false;
+ if (isStructuredQuery(trimmed, tableSchema)) return false;
+
+ const words = trimmed.split(/\s+/);
+
+ // Single word: only treat as natural language if it doesn't match any field
+ if (words.length === 1) {
+ const word = words[0]!.toLowerCase();
+ const matchesField = filterFields.some((f) => {
+ const key = String(f.value).toLowerCase();
+ return key.startsWith(word) || key.includes(word);
+ });
+ if (matchesField) return false;
+ }
+
+ // Multiple words without key:value → natural language
+ return (
+ words.length > 1 ||
+ !filterFields.some((f) => {
+ const key = String(f.value).toLowerCase();
+ return key === words[0]?.toLowerCase();
+ })
+ );
+ }, [inputValue, tableSchema, filterFields]);
+
+ // Track the last AI query for display while loading
+ const [aiQuery, setAIQuery] = useState<string | null>(null);
+ // Taken before the replace-all reset so a failed request can be undone.
+ const previousFiltersRef = useRef<{ id: string; value: unknown }[] | null>(
+ null,
+ );
+
+ /**
+ * Replace-all: every filterable field missing from `filters` is cleared.
+ * Iterates `_filterFields`, not the command-visible subset, so a
+ * command-disabled field (the timerange) cannot survive as a stale constraint.
+ */
+ function applyFilterSet(filters: { id: string; value: unknown }[]) {
+ const next = new Map(filters.map((filter) => [filter.id, filter.value]));
+ for (const field of _filterFields ?? []) {
+ if (typeof field.value !== "string") continue;
+ table.getColumn(field.value)?.setFilterValue(next.get(field.value));
+ }
+ }
+
+ // AI filters hook
+ const { infer, isLoading: isAILoading } = useAIFilters({
+ api,
+ tableSchema,
+ onField(key, value) {
+ table.getColumn(key)?.setFilterValue(value);
+ },
+ onFinish(state) {
+ // Final reconciliation: the validated state is the whole truth, so fields
+ // that were applied progressively but did not validate get cleared here.
+ const validated = Object.entries(state).map(([id, value]) => ({
+ id,
+ value,
+ }));
+ applyFilterSet(validated);
+ previousFiltersRef.current = null;
+ // Serialize from the validated state directly to avoid stale table state
+ isSerializingRef.current = true;
+ setInputValue(columnParser.serialize(validated));
+ },
+ onComplete() {
+ setAIQuery(null);
+ },
+ onStart() {
+ previousFiltersRef.current = table
+ .getState()
+ .columnFilters.map(({ id, value }) => ({ id, value }));
+ // Clear existing filters before AI applies new ones (replace-all strategy)
+ applyFilterSet([]);
+ },
+ onError(error) {
+ // A failed request must not leave the table on a query the user never
+ // asked for: put the pre-request filters back.
+ applyFilterSet(previousFiltersRef.current ?? []);
+ previousFiltersRef.current = null;
+ setAIQuery(null);
+ toast.error("Failed to infer filters", {
+ description: error.message,
+ });
+ },
+ });
+
+ useEffect(() => {
+ if (isSerializingRef.current) {
+ isSerializingRef.current = false;
+ return;
+ }
+ if (currentWord !== "" && open) return;
+ if (currentWord !== "" && !open) setCurrentWord("");
+ if (inputValue.trim() === "" && !open) return;
+
+ const searchParams = columnParser.parse(inputValue);
+
+ const currentFilters = table.getState().columnFilters;
+ const currentEnabledFilters = currentFilters.filter((filter) => {
+ const field = _filterFields?.find((field) => field.value === filter.id);
+ return !field?.commandDisabled;
+ });
+ for (const key of Object.keys(searchParams)) {
+ const value = searchParams[key as keyof typeof searchParams];
+ table.getColumn(key)?.setFilterValue(value);
+ }
+ const currentFiltersToReset = currentEnabledFilters.filter((filter) => {
+ return !(filter.id in searchParams);
+ });
+ for (const filter of currentFiltersToReset) {
+ table.getColumn(filter.id)?.setFilterValue(undefined);
+ }
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [inputValue, open, currentWord]);
+
+ useEffect(() => {
+ if (!open) {
+ isSerializingRef.current = true;
+ setInputValue(columnParser.serialize(columnFilters));
+ }
+ }, [columnFilters, filterFields, open]);
+
+ useHotKey(() => setOpen((open) => !open), "k");
+
+ useEffect(() => {
+ if (open) {
+ inputRef?.current?.focus();
+ }
+ }, [open]);
+
+ function handleClose() {
+ setOpen(false);
+ const search = inputValue.trim();
+ if (!search) return;
+ const timestamp = Date.now();
+ const searchIndex = lastSearches.findIndex(
+ (item) => item.search === search,
+ );
+ if (searchIndex !== -1) {
+ setLastSearches(
+ lastSearches.map((item, i) =>
+ i === searchIndex ? { ...item, timestamp } : item,
+ ),
+ );
+ return;
+ }
+ // Only the newest few are ever shown, and every entry is re-serialised into
+ // localStorage on each write — so keep the stored history bounded.
+ setLastSearches(
+ [...lastSearches, { search, timestamp }]
+ .sort((a, b) => b.timestamp - a.timestamp)
+ .slice(0, MAX_COMMAND_HISTORY),
+ );
+ }
+
+ function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
+ if (e.key === "Escape") {
+ inputRef?.current?.blur();
+ return;
+ }
+ if (e.key === "Enter" && isNaturalLanguage) {
+ // Let cmdk handle Enter if an item is selected (e.g., a suggestion)
+ const selected = document.querySelector("[cmdk-item][data-selected]");
+ if (selected) return;
+
+ e.preventDefault();
+ const query = inputValue.trim();
+ const handled = infer(inputValue);
+ if (handled) {
+ setAIQuery(query);
+ handleClose();
+ }
+ }
+ }
+
+ return (
+ <div>
+ <button
+ type="button"
+ className={cn(
+ "group border-input bg-background text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground focus-within:border-ring focus-within:ring-ring/50 flex w-full items-center rounded-lg border px-3 transition-all outline-none focus-within:ring-[3px]",
+ open ? "hidden" : "visible",
+ )}
+ onClick={() => setOpen(true)}
+ >
+ {isLoading || isAILoading ? (
+ <LoaderCircle className="text-muted-foreground group-hover:text-popover-foreground mr-2 h-4 w-4 shrink-0 animate-spin opacity-50" />
+ ) : (
+ <Search className="text-muted-foreground group-hover:text-popover-foreground mr-2 h-4 w-4 shrink-0 opacity-50" />
+ )}
+ <span className="h-11 w-full max-w-sm truncate py-3 text-left text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50 md:max-w-xl lg:max-w-4xl xl:max-w-5xl">
+ {aiQuery ? (
+ <TextShimmer duration={2}>{aiQuery}</TextShimmer>
+ ) : inputValue.trim() ? (
+ <span className="text-foreground">{inputValue}</span>
+ ) : (
+ <span>Search data table...</span>
+ )}
+ </span>
+ <Kbd className="text-muted-foreground group-hover:text-accent-foreground ml-auto">
+ <span className="mr-1">⌘</span>
+ <span>K</span>
+ </Kbd>
+ </button>
+ <Command
+ className={cn(
+ "border-border dark:bg-muted/50 overflow-visible rounded-lg border shadow-md [&>div]:border-none",
+ open ? "visible" : "hidden",
+ )}
+ filter={(value, search, keywords) =>
+ getFilterValue({ value, search, keywords, currentWord })
+ }
+ >
+ <div
+ data-slot="command-input-wrapper"
+ className="flex items-center gap-2 border-b px-3"
+ >
+ <Search className="size-4 shrink-0 opacity-50" />
+ <CommandPrimitive.Input
+ ref={inputRef}
+ value={inputValue}
+ onValueChange={setInputValue}
+ onKeyDown={handleKeyDown}
+ onBlur={handleClose}
+ onInput={(e: React.FormEvent<HTMLInputElement>) => {
+ const caretPosition = e.currentTarget?.selectionStart || -1;
+ const value = e.currentTarget?.value || "";
+ const word = getWordByCaretPosition({ value, caretPosition });
+ setCurrentWord(word);
+ }}
+ placeholder="Search data table..."
+ className="text-foreground placeholder:text-muted-foreground flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50"
+ />
+ </div>
+ <div className="relative">
+ <div className="border-border bg-popover text-popover-foreground animate-in absolute top-2 z-10 w-full overflow-hidden rounded-lg border shadow-md outline-hidden">
+ <CommandList className="max-h-[310px]">
+ {!isNaturalLanguage && (
+ <>
+ <CommandGroup heading="Filter">
+ {filterFields.map((field) => {
+ if (typeof field.value !== "string") return null;
+ if (inputValue.includes(`${field.value}:`)) return null;
+ return (
+ <CommandItem
+ key={field.value}
+ value={field.value}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onSelect={(value) => {
+ setInputValue((prev) => {
+ if (currentWord.trim() === "") {
+ const input = `${prev}${value}`;
+ return `${input}:`;
+ }
+ const isStarting = currentWord === prev;
+ const prefix = isStarting ? "" : " ";
+ const input = prev.replace(
+ `${prefix}${currentWord}`,
+ `${prefix}${value}`,
+ );
+ return `${input}:`;
+ });
+ setCurrentWord(`${value}:`);
+ }}
+ className="group"
+ >
+ {field.value}
+ <CommandItemSuggestions field={field} />
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ <CommandSeparator />
+ <CommandGroup heading="Query">
+ {filterFields?.map((field) => {
+ if (typeof field.value !== "string") return null;
+ if (!currentWord.includes(`${field.value}:`)) return null;
+
+ const column = table.getColumn(field.value);
+ const facetedValue =
+ getFacetedUniqueValues?.(table, field.value) ||
+ column?.getFacetedUniqueValues();
+
+ const options = getFieldOptions({ field, facetedValue });
+
+ return options.map((optionValue) => {
+ return (
+ <CommandItem
+ key={`${String(field.value)}:${optionValue}`}
+ value={`${String(field.value)}:${optionValue}`}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onSelect={(value) => {
+ setInputValue((prev) =>
+ replaceInputByFieldType({
+ prev,
+ currentWord,
+ optionValue,
+ value,
+ field,
+ }),
+ );
+ setCurrentWord("");
+ }}
+ >
+ {`${optionValue}`}
+ {facetedValue?.has(optionValue) ? (
+ <span className="text-muted-foreground ml-auto font-mono">
+ {formatCompactNumber(
+ facetedValue.get(optionValue) || 0,
+ )}
+ </span>
+ ) : null}
+ </CommandItem>
+ );
+ });
+ })}
+ </CommandGroup>
+ <CommandEmpty>No results found.</CommandEmpty>
+ </>
+ )}
+ {isNaturalLanguage && inputValue.trim() && (
+ <CommandGroup heading="Infer">
+ <CommandItem
+ value={`ai:${inputValue.trim()}`}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onSelect={() => {
+ const query = inputValue.trim();
+ const handled = infer(inputValue);
+ if (handled) {
+ setAIQuery(query);
+ handleClose();
+ }
+ }}
+ >
+ <Sparkles className="size-4 shrink-0" />
+ {inputValue.trim()}
+ <span className="text-muted-foreground ml-auto text-xs">
+ describe your query to infer filters
+ </span>
+ </CommandItem>
+ </CommandGroup>
+ )}
+ {lastSearches.length > 0 && (
+ <>
+ <CommandSeparator />
+ <CommandGroup heading="Suggestions">
+ {[...lastSearches]
+ .sort((a, b) => b.timestamp - a.timestamp)
+ .slice(0, 5)
+ .map((item) => {
+ return (
+ <CommandItem
+ key={`suggestion:${item.search}`}
+ value={`suggestion:${item.search}`}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onSelect={(value) => {
+ const search = value.replace("suggestion:", "");
+ setInputValue(`${search} `);
+ setCurrentWord("");
+ }}
+ className="group"
+ >
+ {item.search}
+ <span className="text-muted-foreground/80 ml-auto truncate group-aria-selected:block">
+ {formatDistanceToNow(item.timestamp, {
+ addSuffix: true,
+ })}
+ </span>
+ <button
+ type="button"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setLastSearches(
+ lastSearches.filter(
+ (i) => i.search !== item.search,
+ ),
+ );
+ }}
+ className="hover:bg-background ml-1 hidden rounded-md p-0.5 group-aria-selected:block"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </>
+ )}
+ </CommandList>
+ <div
+ className="bg-accent/50 text-accent-foreground flex flex-wrap justify-between gap-2 border-t px-2 py-1.5 text-sm"
+ cmdk-footer=""
+ >
+ <div className="flex flex-wrap gap-2">
+ <span>
+ Use <Kbd>↑</Kbd> <Kbd>↓</Kbd> to navigate
+ </span>
+ <span>
+ <Kbd>Enter</Kbd> to query
+ </span>
+ <span>
+ <Kbd>Esc</Kbd> to close
+ </span>
+ <Separator
+ orientation="vertical"
+ className="my-auto data-[orientation=vertical]:h-3"
+ />
+ <span>
+ Union: <Kbd>regions:a,b</Kbd>
+ </span>
+ <span>
+ Range: <Kbd>p95:59-340</Kbd>
+ </span>
+ <span>
+ Spaces: <Kbd>name:&quot;a b&quot;</Kbd>
+ </span>
+ <Separator
+ orientation="vertical"
+ className="my-auto data-[orientation=vertical]:h-3"
+ />
+ <span>
+ AI:{" "}
+ <Kbd>
+ <Sparkles className="size-2.5 shrink-0" />
+ </Kbd>
+ </span>
+ </div>
+ {lastSearches.length ? (
+ <button
+ type="button"
+ className="text-muted-foreground hover:text-accent-foreground"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={() => setLastSearches([])}
+ >
+ Clear suggestions
+ </button>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ </Command>
+ </div>
+ );
+}
+
+function CommandItemSuggestions<TData>({
+ field,
+}: {
+ field: DataTableFilterField<TData>;
+}) {
+ const { table, getFacetedMinMaxValues, getFacetedUniqueValues } =
+ useDataTable();
+ const value = field.value as string;
+ switch (field.type) {
+ case "checkbox": {
+ return (
+ <span className="text-muted-foreground/80 ml-1 hidden truncate group-aria-selected:block">
+ {getFacetedUniqueValues
+ ? Array.from(getFacetedUniqueValues(table, value)?.keys() || [])
+ .map((value) => `[${value}]`)
+ .join(" ")
+ : field.options?.map(({ value }) => `[${value}]`).join(" ")}
+ </span>
+ );
+ }
+ case "slider": {
+ const [min, max] = getFacetedMinMaxValues?.(table, value) || [
+ field.min,
+ field.max,
+ ];
+ return (
+ <span className="text-muted-foreground/80 ml-1 hidden truncate group-aria-selected:block">
+ [{min} - {max}]
+ </span>
+ );
+ }
+ case "input": {
+ return (
+ <span className="text-muted-foreground/80 ml-1 hidden truncate group-aria-selected:block">
+ [{`${String(field.value)}`} input]
+ </span>
+ );
+ }
+ default: {
+ return null;
+ }
+ }
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-command-ai/text-shimmer.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-command-ai/text-shimmer.tsx
new file mode 100644
index 000000000..ccf316bc0
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-command-ai/text-shimmer.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import { cn } from "@openstatus/ui/lib/utils";
+
+export type TextShimmerProps = {
+ as?: React.ElementType;
+ duration?: number;
+ spread?: number;
+ children: React.ReactNode;
+} & React.HTMLAttributes<HTMLElement>;
+
+export function TextShimmer({
+ as = "span",
+ className,
+ duration = 4,
+ spread = 20,
+ children,
+ ...props
+}: TextShimmerProps) {
+ const dynamicSpread = Math.min(Math.max(spread, 5), 45);
+ const Component = as;
+
+ return (
+ <Component
+ className={cn(
+ "bg-size-[200%_auto] bg-clip-text font-medium text-transparent",
+ "animate-[shimmer_4s_infinite_linear]",
+ className,
+ )}
+ style={{
+ backgroundImage: `linear-gradient(to right, var(--muted-foreground) ${50 - dynamicSpread}%, var(--foreground) 50%, var(--muted-foreground) ${50 + dynamicSpread}%)`,
+ animationDuration: `${duration}s`,
+ }}
+ {...props}
+ >
+ {children}
+ </Component>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-command/utils.ts b/packages/ui/src/components/data-table-filters/data-table-filter-command/utils.ts
new file mode 100644
index 000000000..9e6bff90a
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-command/utils.ts
@@ -0,0 +1,353 @@
+import {
+ ARRAY_DELIMITER,
+ RANGE_DELIMITER,
+ SLIDER_DELIMITER,
+} from "@openstatus/ui/lib/data-table-filters/delimiters";
+import { isArrayOfDates } from "@openstatus/ui/lib/data-table-filters/is-array";
+import type {
+ FieldBuilder,
+ SchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/store/schema/types";
+import {
+ serializeFilterValue,
+ tokenizeFilterInput,
+} from "@openstatus/ui/lib/data-table-filters/tokenize";
+import type { ColumnFiltersState } from "@tanstack/react-table";
+
+import type { DataTableFilterField } from "../types";
+
+export {
+ serializeFilterValue,
+ tokenizeFilterInput,
+} from "@openstatus/ui/lib/data-table-filters/tokenize";
+
+/**
+ * Extracts the word from the given string at the specified caret position.
+ */
+export function getWordByCaretPosition({
+ value,
+ caretPosition,
+}: {
+ value: string;
+ caretPosition: number;
+}) {
+ let start = caretPosition;
+ let end = caretPosition;
+
+ while (start > 0 && value[start - 1] !== " ") start--;
+ while (end < value.length && value[end] !== " ") end++;
+
+ const word = value.substring(start, end);
+ return word;
+}
+
+/**
+ * Quote a value if it contains spaces
+ */
+function quoteIfNeeded(val: string | number | boolean | undefined): string {
+ const str = `${val}`;
+ if (str.includes(" ")) {
+ return `"${str}"`;
+ }
+ return str;
+}
+
+export function replaceInputByFieldType<TData>({
+ prev,
+ currentWord,
+ optionValue,
+ value,
+ field,
+}: {
+ prev: string;
+ currentWord: string;
+ optionValue?: string | number | boolean | undefined; // FIXME: use DataTableFilterField<TData>["options"][number];
+ value: string;
+ field: DataTableFilterField<TData>;
+}) {
+ switch (field.type) {
+ case "checkbox": {
+ if (currentWord.includes(ARRAY_DELIMITER)) {
+ const words = currentWord.split(ARRAY_DELIMITER);
+ words[words.length - 1] = quoteIfNeeded(optionValue);
+ const input = prev.replace(currentWord, words.join(ARRAY_DELIMITER));
+ return `${input.trim()} `;
+ }
+ break;
+ }
+ case "slider": {
+ if (currentWord.includes(SLIDER_DELIMITER)) {
+ const words = currentWord.split(SLIDER_DELIMITER);
+ words[words.length - 1] = `${optionValue}`;
+ const input = prev.replace(currentWord, words.join(SLIDER_DELIMITER));
+ return `${input.trim()} `;
+ }
+ break;
+ }
+ case "timerange": {
+ if (currentWord.includes(RANGE_DELIMITER)) {
+ const words = currentWord.split(RANGE_DELIMITER);
+ words[words.length - 1] = `${optionValue}`;
+ const input = prev.replace(currentWord, words.join(RANGE_DELIMITER));
+ return `${input.trim()} `;
+ }
+ break;
+ }
+ }
+
+ // Default: set a fresh filter value, quoting if it contains spaces
+ const quotedValue = quoteIfNeeded(optionValue) || value;
+ const input = prev.replace(
+ currentWord,
+ `${String(field.value)}:${quotedValue}`,
+ );
+ return `${input.trim()} `;
+}
+
+export function getFieldOptions<TData>({
+ field,
+ facetedValue,
+}: {
+ field: DataTableFilterField<TData>;
+ facetedValue?: Map<unknown, number>;
+}) {
+ switch (field.type) {
+ case "slider": {
+ if (field.options?.length) {
+ return field.options
+ .map(({ value }) => value)
+ .sort((a, b) => Number(a) - Number(b))
+ .filter(notEmpty);
+ }
+ // Use only the values that actually exist in the data to avoid
+ // generating thousands of intermediate integers (e.g. salary 58k-155k).
+ if (facetedValue?.size) {
+ return Array.from(facetedValue.keys())
+ .map(Number)
+ .filter((n) => !isNaN(n))
+ .sort((a, b) => a - b);
+ }
+ return [];
+ }
+ default: {
+ return field.options?.map(({ value }) => value).filter(notEmpty) || [];
+ }
+ }
+}
+
+export function getFilterValue({
+ value,
+ search,
+ currentWord,
+}: {
+ value: string;
+ search: string;
+ keywords?: string[] | undefined;
+ currentWord: string;
+}): number {
+ /**
+ * @example value "suggestion:public:true regions,ams,gru,fra"
+ */
+ if (value.startsWith("suggestion:")) {
+ const rawValue = value.toLowerCase().replace("suggestion:", "");
+ if (rawValue.includes(search)) return 1;
+ return 0;
+ }
+
+ /** */
+ if (value.toLowerCase().includes(currentWord.toLowerCase())) return 1;
+
+ /**
+ * @example checkbox [filter, query] = ["regions", "ams,gru,fra"]
+ * @example slider [filter, query] = ["p95", "0-3000"]
+ * @example input [filter, query] = ["name", "api"]
+ */
+ // Split on the FIRST colon only — values legitimately contain colons (urls,
+ // timestamps), and `split(":")` would truncate the query at the second one.
+ const lowerCurrentWord = currentWord.toLowerCase();
+ const separatorIndex = lowerCurrentWord.indexOf(":");
+ const filter =
+ separatorIndex === -1
+ ? lowerCurrentWord
+ : lowerCurrentWord.slice(0, separatorIndex);
+ const query =
+ separatorIndex === -1
+ ? undefined
+ : lowerCurrentWord.slice(separatorIndex + 1);
+ if (query && value.startsWith(`${filter}:`)) {
+ if (query.includes(ARRAY_DELIMITER)) {
+ /**
+ * array of n elements
+ * @example queries = ["ams", "gru", "fra"]
+ */
+ const queries = query.split(ARRAY_DELIMITER);
+ const rawValue = value.toLowerCase().replace(`${filter}:`, "");
+ if (
+ queries.some((item, i) => item === rawValue && i !== queries.length - 1)
+ )
+ return 0;
+ if (queries.some((item) => rawValue.includes(item))) return 1;
+ }
+ if (query.includes(SLIDER_DELIMITER)) {
+ /**
+ * range between 2 elements
+ * @example queries = ["0", "3000"]
+ */
+ const queries = query.split(SLIDER_DELIMITER);
+ const rawValue = value.toLowerCase().replace(`${filter}:`, "");
+
+ const rawValueAsNumber = Number.parseInt(rawValue);
+ const queryAsNumber = Number.parseInt(queries[0]);
+
+ if (queryAsNumber < rawValueAsNumber) {
+ if (rawValue.includes(queries[1])) return 1;
+ return 0;
+ }
+ return 0;
+ }
+ const rawValue = value.toLowerCase().replace(`${filter}:`, "");
+ if (rawValue.includes(query)) return 1;
+ }
+ return 0;
+}
+
+export function getFieldValueByType<TData>({
+ field,
+ value,
+}: {
+ field?: DataTableFilterField<TData>;
+ value: unknown;
+}) {
+ if (!field) return null;
+
+ switch (field.type) {
+ case "slider": {
+ if (Array.isArray(value)) {
+ return value.join(SLIDER_DELIMITER);
+ }
+ return value;
+ }
+ case "checkbox": {
+ if (Array.isArray(value)) {
+ return value.join(ARRAY_DELIMITER);
+ }
+ // REMINER: inversed logic
+ if (typeof value === "string") {
+ return value.split(ARRAY_DELIMITER);
+ }
+ return value;
+ }
+ case "timerange": {
+ if (Array.isArray(value)) {
+ if (isArrayOfDates(value)) {
+ return value.map((date) => date.getTime()).join(RANGE_DELIMITER);
+ }
+ return value.join(RANGE_DELIMITER);
+ }
+ if (value instanceof Date) {
+ return value.getTime();
+ }
+ return value;
+ }
+ default: {
+ return value;
+ }
+ }
+}
+
+export function notEmpty<TValue>(
+ value: TValue | null | undefined,
+): value is TValue {
+ return value !== null && value !== undefined;
+}
+
+/**
+ * Schema-based column filters parser for BYOS
+ *
+ * This parser works with the new schema system instead of nuqs ParserBuilder.
+ */
+export function columnFiltersParserFromSchema<TData>({
+ schema,
+ filterFields,
+}: {
+ schema: SchemaDefinition;
+ filterFields: DataTableFilterField<TData>[];
+}) {
+ return {
+ parse: (inputValue: string) => {
+ // Use tokenizer that respects quoted values
+ const tokens = tokenizeFilterInput(inputValue);
+ const values = tokens.reduce(
+ (prev, [name, value]) => {
+ prev[name] = value;
+ return prev;
+ },
+ {} as Record<string, string>,
+ );
+
+ const searchParams = Object.entries(values).reduce(
+ (prev, [key, value]) => {
+ // mirror `serialize`: only fields the command exposes can be typed
+ const field = filterFields?.find((f) => f.value === key);
+ if (!field || field.commandDisabled) return prev;
+
+ // own-property only: `toString:x` would otherwise resolve on the prototype
+ if (!Object.prototype.hasOwnProperty.call(schema, key)) return prev;
+ const fieldBuilder = schema[key] as FieldBuilder<unknown> | undefined;
+ if (!fieldBuilder) return prev;
+
+ try {
+ let parsed = fieldBuilder._config.parse(value);
+ if (parsed !== null) {
+ // Slider fields expect [min, max] for inNumberRange — if a single
+ // value is provided (e.g. "amount:1800"), duplicate it so the range
+ // becomes [1800, 1800] (exact match).
+ if (
+ field.type === "slider" &&
+ Array.isArray(parsed) &&
+ parsed.length === 1
+ ) {
+ parsed = [parsed[0], parsed[0]];
+ }
+ prev[key] = parsed;
+ }
+ } catch {
+ // skip fields whose custom parser rejects the input
+ }
+ return prev;
+ },
+ {} as Record<string, unknown>,
+ );
+
+ return searchParams;
+ },
+ serialize: (columnFilters: ColumnFiltersState) => {
+ const values = columnFilters.reduce((prev, curr) => {
+ const { commandDisabled } = filterFields?.find(
+ (field) => curr.id === field.value,
+ ) || { commandDisabled: true };
+ const fieldBuilder = Object.prototype.hasOwnProperty.call(
+ schema,
+ curr.id,
+ )
+ ? (schema[curr.id] as FieldBuilder<unknown> | undefined)
+ : undefined;
+
+ if (commandDisabled || !fieldBuilder) return prev;
+
+ let serialized: string;
+ try {
+ serialized = fieldBuilder._config.serialize(curr.value);
+ } catch {
+ return prev;
+ }
+ if (!serialized) return prev;
+
+ const quotedValue = serializeFilterValue(serialized);
+ return `${prev}${curr.id}:${quotedValue} `;
+ }, "");
+
+ return values;
+ },
+ };
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-controls-drawer.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-controls-drawer.tsx
new file mode 100644
index 000000000..1f9daca48
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-controls-drawer.tsx
@@ -0,0 +1,82 @@
+import { Button } from "@openstatus/ui/components/ui/button";
+import {
+ Drawer,
+ DrawerClose,
+ DrawerContent,
+ DrawerDescription,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ DrawerTrigger,
+} from "@openstatus/ui/components/ui/drawer";
+import { Kbd } from "@openstatus/ui/components/ui/kbd";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui/components/ui/tooltip";
+import { useHotKey } from "@openstatus/ui/hooks/use-hot-key";
+import { useMediaQuery } from "@openstatus/ui/hooks/use-media-query";
+import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
+import { FilterIcon } from "lucide-react";
+import React from "react";
+
+import { DataTableFilterControls } from "./data-table-filter-controls";
+
+export function DataTableFilterControlsDrawer() {
+ const triggerButtonRef = React.useRef<HTMLButtonElement>(null);
+ const isMobile = useMediaQuery("(max-width: 640px)");
+
+ useHotKey(() => {
+ triggerButtonRef.current?.click();
+ }, "b");
+
+ return (
+ <Drawer>
+ <TooltipProvider>
+ <Tooltip delayDuration={100}>
+ <TooltipTrigger asChild>
+ <DrawerTrigger asChild>
+ <Button
+ ref={isMobile ? triggerButtonRef : null}
+ variant="ghost"
+ size="icon"
+ className="h-9 w-9"
+ >
+ <FilterIcon className="h-4 w-4" />
+ </Button>
+ </DrawerTrigger>
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p className="text-nowrap">
+ Toggle controls with{" "}
+ <Kbd className="text-muted-foreground group-hover:text-accent-foreground ml-1">
+ <span className="mr-1">⌘</span>
+ <span>B</span>
+ </Kbd>
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <DrawerContent className="max-h-[calc(100dvh-4rem)]">
+ <VisuallyHidden>
+ <DrawerHeader>
+ <DrawerTitle>Filters</DrawerTitle>
+ <DrawerDescription>Adjust your table filters</DrawerDescription>
+ </DrawerHeader>
+ </VisuallyHidden>
+ <div className="flex-1 overflow-y-auto px-4">
+ <DataTableFilterControls />
+ </div>
+ <DrawerFooter>
+ <DrawerClose asChild>
+ <Button variant="outline" className="w-full">
+ Close
+ </Button>
+ </DrawerClose>
+ </DrawerFooter>
+ </DrawerContent>
+ </Drawer>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-controls.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-controls.tsx
new file mode 100644
index 000000000..e4a19e517
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-controls.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@openstatus/ui/components/ui/accordion";
+import * as React from "react";
+
+import { DataTableFilterCheckbox } from "./data-table-filter-checkbox";
+import { DataTableFilterInput } from "./data-table-filter-input";
+import { DataTableFilterResetButton } from "./data-table-filter-reset-button";
+import { DataTableFilterSlider } from "./data-table-filter-slider";
+import { DataTableFilterTimerange } from "./data-table-filter-timerange";
+
+// FIXME: use @container (especially for the slider element) to restructure elements
+
+// TODO: only pass the columns to generate the filters!
+// https://tanstack.com/table/v8/docs/framework/react/examples/filters
+
+// Pluggable filter registry — extend by adding entries
+export const FILTER_COMPONENTS: Record<string, React.ComponentType<any>> = {
+ checkbox: DataTableFilterCheckbox,
+ input: DataTableFilterInput,
+ slider: DataTableFilterSlider,
+ timerange: DataTableFilterTimerange,
+};
+
+export function DataTableFilterControls() {
+ const { filterFields } = useDataTable();
+ const [isMounted, setIsMounted] = React.useState(false);
+
+ React.useEffect(() => {
+ const timer = setTimeout(() => setIsMounted(true), 0);
+ return () => clearTimeout(timer);
+ }, []);
+
+ return (
+ <Accordion
+ type="multiple"
+ className={
+ isMounted
+ ? undefined
+ : "[&_[data-slot=accordion-content]]:!animate-none"
+ }
+ defaultValue={filterFields
+ ?.filter(({ defaultOpen }) => defaultOpen)
+ ?.map(({ value }) => value as string)}
+ >
+ {filterFields?.map((field) => {
+ const value = field.value as string;
+ const FilterComponent = FILTER_COMPONENTS[field.type];
+ if (!FilterComponent) return null;
+ return (
+ // REMINDER: -mx-2 lets the border-b span the full sidebar width despite the parent p-2; px-2 keeps the content aligned
+ <AccordionItem
+ key={value}
+ value={value}
+ className="-mx-2 px-2 last:border-b"
+ >
+ <AccordionTrigger className="data-[state=closed]:text-muted-foreground data-[state=open]:text-foreground focus-within:data-[state=closed]:text-foreground hover:data-[state=closed]:text-foreground w-full items-center gap-2 px-2 py-0 hover:no-underline">
+ <div className="flex w-full items-center justify-between gap-2 truncate py-3 pr-2">
+ <div className="flex items-center gap-2 truncate">
+ <p className="text-sm font-medium">{field.label}</p>
+ {value !== field.label.toLowerCase() &&
+ !field.commandDisabled ? (
+ <p className="text-muted-foreground mt-px truncate font-mono text-[10px]">
+ {value}
+ </p>
+ ) : null}
+ </div>
+ <DataTableFilterResetButton {...field} />
+ </div>
+ </AccordionTrigger>
+ <AccordionContent>
+ {/* REMINDER: avoid the focus state to be cut due to overflow-hidden */}
+ {/* REMINDER: need to move within here because of accordion height animation */}
+ <div className="p-1">
+ <FilterComponent {...field} />
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ );
+ })}
+ </Accordion>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-input.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-input.tsx
new file mode 100644
index 000000000..c8a063744
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-input.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@openstatus/ui/components/ui/input-group";
+import { Label } from "@openstatus/ui/components/ui/label";
+import { useDebounce } from "@openstatus/ui/hooks/use-debounce";
+import { Search } from "lucide-react";
+import { useEffect, useState } from "react";
+
+import type { DataTableInputFilterField } from "./types";
+
+function getFilter(filterValue: unknown) {
+ return typeof filterValue === "string" ? filterValue : null;
+}
+
+export function DataTableFilterInput<TData>({
+ value: _value,
+}: DataTableInputFilterField<TData>) {
+ const value = _value as string;
+ const { table, columnFilters } = useDataTable();
+ const column = table.getColumn(value);
+ const filterValue = columnFilters.find((i) => i.id === value)?.value;
+ const filters = getFilter(filterValue);
+ const [input, setInput] = useState<string | null>(filters);
+
+ const debouncedInput = useDebounce(input, 500);
+
+ useEffect(() => {
+ const newValue = debouncedInput?.trim() === "" ? null : debouncedInput;
+ if (debouncedInput === null) return;
+ column?.setFilterValue(newValue);
+ }, [debouncedInput]);
+
+ useEffect(() => {
+ if (debouncedInput?.trim() !== filters) {
+ setInput(filters);
+ }
+ }, [filters]);
+
+ return (
+ <div className="grid w-full gap-1.5">
+ <Label htmlFor={value} className="text-muted-foreground sr-only px-2">
+ {value}
+ </Label>
+ <InputGroup className="h-9 rounded-lg shadow-none">
+ <InputGroupAddon>
+ <Search className="mt-0.5 h-4 w-4" />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder="Search"
+ name={value}
+ id={value}
+ value={input || ""}
+ onChange={(e) => setInput(e.target.value)}
+ />
+ </InputGroup>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-rail.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-rail.tsx
new file mode 100644
index 000000000..a1c833ec2
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-rail.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import { useControls } from "@openstatus/ui/components/data-table-filters/controls";
+import { cn } from "@openstatus/ui/lib/utils";
+
+/**
+ * The hit area on the filter sidebar's border, mirroring the app sidebar's
+ * rail. Absolutely positioned so it costs no layout width; the accessible
+ * control is the toolbar's Hide/Show Controls button.
+ */
+export function DataTableFilterRail({
+ className,
+ ...props
+}: React.ComponentProps<"button">) {
+ const { open, setOpen } = useControls();
+
+ return (
+ <button
+ type="button"
+ data-slot="data-table-filter-rail"
+ aria-label="Toggle Filters"
+ aria-expanded={open}
+ title="Toggle Filters"
+ tabIndex={-1}
+ onClick={() => setOpen((prev) => !prev)}
+ className={cn(
+ // z-30: above the table's own sticky header, which is z-20
+ "absolute inset-y-0 left-0 z-30 hidden w-4 -translate-x-1/2 sm:block",
+ "after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] after:transition-colors",
+ "hover:after:bg-border",
+ open ? "cursor-w-resize" : "cursor-e-resize",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-reset-button.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-reset-button.tsx
new file mode 100644
index 000000000..6852c2b67
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-reset-button.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { X } from "lucide-react";
+
+import type { DataTableFilterField } from "./types";
+
+export function DataTableFilterResetButton<TData>({
+ value: _value,
+}: DataTableFilterField<TData>) {
+ const { columnFilters, table } = useDataTable();
+ const value = _value as string;
+ const column = table.getColumn(value);
+ const filterValue = columnFilters.find((f) => f.id === value)?.value;
+
+ // TODO: check if we could useMemo
+ const filters = filterValue
+ ? Array.isArray(filterValue)
+ ? filterValue
+ : [filterValue]
+ : [];
+
+ if (filters.length === 0) return null;
+
+ return (
+ <Button
+ variant="outline"
+ className="h-5 gap-1 rounded-full px-1.5! py-1! font-mono text-[10px] shadow-none"
+ onClick={(e) => {
+ e.stopPropagation();
+ column?.setFilterValue(undefined);
+ }}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.code === "Enter") {
+ column?.setFilterValue(undefined);
+ }
+ }}
+ asChild
+ >
+ {/* REMINDER: `AccordionTrigger` is also a button(!) and we get Hydration error when rendering button within button */}
+ <div role="button" tabIndex={0}>
+ <span>{filters.length}</span>
+ <X className="text-muted-foreground ml-1! size-2.5!" />
+ </div>
+ </Button>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-slider.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-slider.tsx
new file mode 100644
index 000000000..16608f6e1
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-slider.tsx
@@ -0,0 +1,141 @@
+"use client";
+
+import { Slider } from "@openstatus/ui/components/custom/slider";
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@openstatus/ui/components/ui/input-group";
+import { Label } from "@openstatus/ui/components/ui/label";
+import { useDebounce } from "@openstatus/ui/hooks/use-debounce";
+import { isArrayOfNumbers } from "@openstatus/ui/lib/data-table-filters/is-array";
+import { useEffect, useMemo, useState } from "react";
+
+import type { DataTableSliderFilterField } from "./types";
+
+function getFilter(filterValue: unknown) {
+ return typeof filterValue === "number"
+ ? [filterValue, filterValue]
+ : Array.isArray(filterValue) && isArrayOfNumbers(filterValue)
+ ? filterValue.length === 1
+ ? [filterValue[0], filterValue[0]]
+ : filterValue
+ : null;
+}
+
+// TODO: discuss if we even need the `defaultMin` and `defaultMax`
+export function DataTableFilterSlider<TData>({
+ value: _value,
+ min: defaultMin,
+ max: defaultMax,
+ unit,
+}: DataTableSliderFilterField<TData>) {
+ const value = _value as string;
+ const { table, columnFilters, getFacetedMinMaxValues } = useDataTable();
+ const column = table.getColumn(value);
+ const filterValue = columnFilters.find((i) => i.id === value)?.value;
+ // `getFilter` builds a fresh pair out of a scalar or one-element filter, so
+ // without this the `[filters]` effect below fires on every render and reverts
+ // the range while it is being typed.
+ const filters = useMemo(() => getFilter(filterValue), [filterValue]);
+ const [input, setInput] = useState<number[] | null>(filters);
+ const [min, max] = getFacetedMinMaxValues?.(table, value) ||
+ column?.getFacetedMinMaxValues() || [defaultMin, defaultMax];
+
+ const debouncedInput = useDebounce(input, 500);
+
+ useEffect(() => {
+ if (debouncedInput?.length !== 2) return;
+ // Untouched range: clamping it here would narrow a filter that came from
+ // the URL against faceted bounds that have not loaded yet.
+ if (
+ filters &&
+ debouncedInput[0] === filters[0] &&
+ debouncedInput[1] === filters[1]
+ ) {
+ return;
+ }
+ const [first = min, second = max] = debouncedInput;
+ // The endpoints reach the server as `min`/`max` - reversed or out of
+ // bounds they match nothing.
+ const lower = Math.max(Math.min(first, second), min);
+ const upper = Math.min(Math.max(first, second), max);
+ column?.setFilterValue([lower, upper]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [debouncedInput]);
+
+ // Adopt ranges applied elsewhere (URL, command, reset). Only `filters` may
+ // trigger it - on `input` it would overwrite the range while it is typed.
+ useEffect(() => {
+ if (!filters) {
+ setInput(null);
+ } else if (input?.[0] !== filters[0] || input?.[1] !== filters[1]) {
+ setInput(filters);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filters]);
+
+ return (
+ <div className="grid gap-2">
+ <div className="flex items-center gap-4">
+ <div className="grid w-full gap-1.5">
+ <Label
+ htmlFor={`min-${value}`}
+ className="text-muted-foreground px-2"
+ >
+ Min.
+ </Label>
+ <InputGroup className="mb-2 h-9 rounded-lg font-mono shadow-none">
+ <InputGroupInput
+ placeholder="from"
+ type="number"
+ name={`min-${value}`}
+ id={`min-${value}`}
+ value={`${input?.[0] ?? min}`}
+ min={min}
+ max={max}
+ onChange={(e) =>
+ setInput((prev) => [Number(e.target.value), prev?.[1] ?? max])
+ }
+ />
+ {unit ? (
+ <InputGroupAddon align="inline-end">{unit}</InputGroupAddon>
+ ) : null}
+ </InputGroup>
+ </div>
+ <div className="grid w-full gap-1.5">
+ <Label
+ htmlFor={`max-${value}`}
+ className="text-muted-foreground px-2"
+ >
+ Max.
+ </Label>
+ <InputGroup className="mb-2 h-9 rounded-lg font-mono shadow-none">
+ <InputGroupInput
+ placeholder="to"
+ type="number"
+ name={`max-${value}`}
+ id={`max-${value}`}
+ value={`${input?.[1] ?? max}`}
+ min={min}
+ max={max}
+ onChange={(e) =>
+ setInput((prev) => [prev?.[0] ?? min, Number(e.target.value)])
+ }
+ />
+ {unit ? (
+ <InputGroupAddon align="inline-end">{unit}</InputGroupAddon>
+ ) : null}
+ </InputGroup>
+ </div>
+ </div>
+ <Slider
+ min={min}
+ max={max}
+ value={input?.length === 2 ? input : [min, max]}
+ onValueChange={(values) => setInput(values)}
+ />
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-filter-timerange.tsx b/packages/ui/src/components/data-table-filters/data-table-filter-timerange.tsx
new file mode 100644
index 000000000..19a3b46b8
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-filter-timerange.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import { DatePickerWithRange } from "@openstatus/ui/components/custom/date-picker-with-range";
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { isArrayOfDates } from "@openstatus/ui/lib/data-table-filters/is-array";
+import { useMemo } from "react";
+import type { DateRange } from "react-day-picker";
+
+import type { DataTableTimerangeFilterField } from "./types";
+
+export function DataTableFilterTimerange<TData>({
+ value: _value,
+ presets,
+}: DataTableTimerangeFilterField<TData>) {
+ const value = _value as string;
+ const { table, columnFilters } = useDataTable();
+ const column = table.getColumn(value);
+ const filterValue = columnFilters.find((i) => i.id === value)?.value;
+
+ const date: DateRange | undefined = useMemo(
+ () =>
+ filterValue instanceof Date
+ ? { from: filterValue, to: undefined }
+ : Array.isArray(filterValue) && isArrayOfDates(filterValue)
+ ? { from: filterValue?.[0], to: filterValue?.[1] }
+ : undefined,
+ [filterValue],
+ );
+
+ const setDate = (date: DateRange | undefined) => {
+ if (!date) {
+ column?.setFilterValue(undefined);
+ return;
+ }
+ if (date.from && !date.to) {
+ column?.setFilterValue([date.from]);
+ }
+ if (date.to && date.from) {
+ // A reversed range matches nothing - order it like the server does.
+ const reversed = date.from.getTime() > date.to.getTime();
+ column?.setFilterValue(
+ reversed ? [date.to, date.from] : [date.from, date.to],
+ );
+ }
+ };
+
+ return <DatePickerWithRange {...{ date, setDate, presets }} />;
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-infinite.tsx b/packages/ui/src/components/data-table-filters/data-table-infinite.tsx
new file mode 100644
index 000000000..8e415f780
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-infinite.tsx
@@ -0,0 +1,630 @@
+"use client";
+
+// REMINDER: React Compiler is not compatible with Tanstack Table v8 https://github.com/TanStack/table/issues/5567
+"use no memo";
+
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@openstatus/ui/components/custom/table";
+import { DataTableFilterControls } from "@openstatus/ui/components/data-table-filters/data-table-filter-controls";
+import { DataTableFilterRail } from "@openstatus/ui/components/data-table-filters/data-table-filter-rail";
+import { DataTableProvider } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { DataTableResetButton } from "@openstatus/ui/components/data-table-filters/data-table-reset-button";
+import { DataTableToolbar } from "@openstatus/ui/components/data-table-filters/data-table-toolbar"; // TODO: check where to put this
+import type { DataTableFilterField } from "@openstatus/ui/components/data-table-filters/types";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { useHotKey } from "@openstatus/ui/hooks/use-hot-key";
+import { useLocalStorage } from "@openstatus/ui/hooks/use-local-storage";
+import { getFacetedUniqueValuesFlattened } from "@openstatus/ui/lib/data-table-filters/data-table/faceted";
+import {
+ arrSome,
+ inDateRange,
+} from "@openstatus/ui/lib/data-table-filters/filterfns";
+import {
+ getColumnOrderKey,
+ getColumnVisibilityKey,
+} from "@openstatus/ui/lib/data-table-filters/local-storage";
+import { useFilterActions } from "@openstatus/ui/lib/data-table-filters/store/hooks/useFilterActions";
+import { useFilterState } from "@openstatus/ui/lib/data-table-filters/store/hooks/useFilterState";
+import { formatCompactNumber } from "@openstatus/ui/lib/format";
+import { cn } from "@openstatus/ui/lib/utils";
+import {
+ type FetchNextPageOptions,
+ type RefetchOptions,
+} from "@tanstack/react-query";
+import type {
+ ColumnDef,
+ ColumnFiltersState,
+ Row,
+ RowSelectionState,
+ SortingState,
+ TableOptions,
+ Table as TTable,
+ VisibilityState,
+} from "@tanstack/react-table";
+import {
+ flexRender,
+ getCoreRowModel,
+ getFacetedRowModel,
+ getFilteredRowModel,
+ getSortedRowModel,
+ getFacetedMinMaxValues as getTTableFacetedMinMaxValues,
+ useReactTable,
+} from "@tanstack/react-table";
+import { LoaderCircle } from "lucide-react";
+import * as React from "react";
+
+// TODO: add a possible chartGroupBy
+export interface DataTableInfiniteProps<TData, TValue> {
+ columns: ColumnDef<TData, TValue>[];
+ getRowClassName?: (row: Row<TData>) => string;
+ // REMINDER: make sure to pass the correct id to access the rows
+ getRowId?: TableOptions<TData>["getRowId"];
+ data: TData[];
+ defaultColumnFilters?: ColumnFiltersState;
+ defaultColumnSorting?: SortingState;
+ defaultRowSelection?: RowSelectionState;
+ defaultColumnVisibility?: VisibilityState;
+ filterFields?: DataTableFilterField<TData>[];
+ // REMINDER: close to the same signature as the `getFacetedUniqueValues` of the `useReactTable`
+ getFacetedUniqueValues?: (
+ table: TTable<TData>,
+ columnId: string,
+ ) => Map<string, number>;
+ getFacetedMinMaxValues?: (
+ table: TTable<TData>,
+ columnId: string,
+ ) => undefined | [number, number];
+ totalRows?: number;
+ filterRows?: number;
+ totalRowsFetched?: number;
+ isFetching?: boolean;
+ isLoading?: boolean;
+ isFacetsLoading?: boolean;
+ hasNextPage?: boolean;
+ fetchNextPage: (
+ options?: FetchNextPageOptions | undefined,
+ ) => Promise<unknown>;
+ refetch: (options?: RefetchOptions | undefined) => void;
+ renderLiveRow?: (props?: { row: Row<TData> }) => React.ReactNode;
+ // Used to store column order and visibility in local storage for specific data-table namespace
+ tableId?: string;
+ // Optional slots for extensibility
+ commandSlot?: React.ReactNode;
+ sheetSlot?: React.ReactNode;
+ toolbarActions?: React.ReactNode;
+ chartSlot?: React.ReactNode;
+ footerSlot?: React.ReactNode;
+ floatingBarSlot?: React.ReactNode;
+ className?: string;
+}
+
+export function DataTableInfinite<TData, TValue>({
+ columns,
+ getRowClassName,
+ getRowId,
+ data,
+ defaultColumnFilters = [],
+ defaultColumnSorting = [],
+ defaultRowSelection = {},
+ defaultColumnVisibility = {},
+ filterFields = [],
+ isFetching,
+ isLoading,
+ isFacetsLoading,
+ fetchNextPage,
+ hasNextPage,
+ refetch,
+ totalRows,
+ filterRows,
+ totalRowsFetched = 0,
+ getFacetedUniqueValues,
+ getFacetedMinMaxValues,
+ renderLiveRow,
+ tableId = "infinite",
+ commandSlot,
+ sheetSlot,
+ toolbarActions,
+ chartSlot,
+ footerSlot,
+ floatingBarSlot,
+ className,
+}: DataTableInfiniteProps<TData, TValue>) {
+ const [columnFilters, setColumnFilters] =
+ React.useState<ColumnFiltersState>(defaultColumnFilters);
+ const [sorting, setSorting] =
+ React.useState<SortingState>(defaultColumnSorting);
+ const [rowSelection, setRowSelection] =
+ React.useState<RowSelectionState>(defaultRowSelection);
+ const [columnOrder, setColumnOrder] = useLocalStorage<string[]>(
+ getColumnOrderKey(tableId),
+ [],
+ );
+ const [columnVisibility, setColumnVisibility] =
+ useLocalStorage<VisibilityState>(
+ getColumnVisibilityKey(tableId),
+ defaultColumnVisibility,
+ );
+ const topBarRef = React.useRef<HTMLDivElement>(null);
+ const tableRef = React.useRef<HTMLTableElement>(null);
+ const [topBarHeight, setTopBarHeight] = React.useState(0);
+
+ // Detect if a select column exists to enable multi-row selection
+ const hasSelectColumn = React.useMemo(
+ () => columns.some((col) => col.meta?.kind === "select"),
+ [columns],
+ );
+
+ const onScroll = React.useCallback(
+ (e: React.UIEvent<HTMLElement>) => {
+ const onPageBottom =
+ Math.ceil(e.currentTarget.scrollTop + e.currentTarget.clientHeight) >=
+ e.currentTarget.scrollHeight;
+
+ // The cursor decides whether a page is left, not the facet counts:
+ // `filterRows` comes from a separate query, and while it is pending or
+ // failed it reads as 0 and scrolling would silently stop loading.
+ const canFetchMore = hasNextPage ?? totalRowsFetched < (filterRows ?? 0);
+
+ if (onPageBottom && !isFetching && canFetchMore) {
+ fetchNextPage();
+ }
+ },
+ [fetchNextPage, isFetching, hasNextPage, filterRows, totalRowsFetched],
+ );
+
+ React.useEffect(() => {
+ const observer = new ResizeObserver(() => {
+ const rect = topBarRef.current?.getBoundingClientRect();
+ if (rect) {
+ setTopBarHeight(rect.height);
+ }
+ });
+
+ const topBar = topBarRef.current;
+ if (!topBar) return;
+
+ observer.observe(topBar);
+ return () => observer.unobserve(topBar);
+ }, [topBarRef]);
+
+ const table = useReactTable({
+ data,
+ columns,
+ state: {
+ columnFilters,
+ sorting,
+ columnVisibility,
+ rowSelection,
+ columnOrder,
+ },
+ enableMultiRowSelection: hasSelectColumn,
+ columnResizeMode: "onChange",
+ getRowId,
+ onColumnVisibilityChange: setColumnVisibility,
+ onColumnFiltersChange: setColumnFilters,
+ onRowSelectionChange: setRowSelection,
+ onSortingChange: setSorting,
+ onColumnOrderChange: setColumnOrder,
+ getSortedRowModel: getSortedRowModel(),
+ getCoreRowModel: getCoreRowModel(),
+ getFilteredRowModel: getFilteredRowModel(),
+ getFacetedRowModel: getFacetedRowModel(),
+ getFacetedUniqueValues: getFacetedUniqueValuesFlattened(),
+ getFacetedMinMaxValues: getTTableFacetedMinMaxValues(),
+ filterFns: { inDateRange, arrSome },
+ debugAll: process.env.NEXT_PUBLIC_TABLE_DEBUG === "true",
+ meta: { getRowClassName },
+ });
+
+ // Clear multi-select when filters or sorting change
+ React.useEffect(() => {
+ if (hasSelectColumn) {
+ setRowSelection({});
+ }
+ }, [columnFilters, sorting, hasSelectColumn, setRowSelection]);
+
+ // NOTE: Filter, sort, and selection syncing is now handled by DataTableStoreSync
+
+ /**
+ * https://tanstack.com/table/v8/docs/guide/column-sizing#advanced-column-resizing-performance
+ * Instead of calling `column.getSize()` on every render for every header
+ * and especially every data cell (very expensive),
+ * we will calculate all column sizes at once at the root table level in a useMemo
+ * and pass the column sizes down as CSS variables to the <table> element.
+ */
+ const columnSizeVars = React.useMemo(() => {
+ const headers = table.getFlatHeaders();
+ const colSizes: { [key: string]: string } = {};
+ for (let i = 0; i < headers.length; i++) {
+ const header = headers[i]!;
+ // REMINDER: replace "." with "-" to avoid invalid CSS variable name (e.g. "timing.dns" -> "timing-dns")
+ colSizes[`--header-${header.id.replaceAll(".", "-")}-size`] =
+ `${header.getSize()}px`;
+ colSizes[`--col-${header.column.id.replaceAll(".", "-")}-size`] =
+ `${header.column.getSize()}px`;
+ }
+ return colSizes;
+ }, [
+ table.getState().columnSizingInfo,
+ table.getState().columnSizing,
+ table.getState().columnVisibility,
+ ]);
+
+ useHotKey(() => {
+ setColumnOrder([]);
+ setColumnVisibility(defaultColumnVisibility);
+ }, "u");
+
+ // Memoize column state as strings for efficient row memoization comparison
+ const visibleColumnIds = React.useMemo(
+ () =>
+ table
+ .getVisibleLeafColumns()
+ .map((c) => c.id)
+ .join(","),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [table.getState().columnVisibility],
+ );
+ const columnOrderString = React.useMemo(
+ () => columnOrder.join(","),
+ [columnOrder],
+ );
+
+ // Read BYOS uuid for detail row visual state (only used in multi-select mode)
+ const detailRowId = useFilterState((s) => s.uuid) as
+ | string
+ | null
+ | undefined;
+ const { setFilters } = useFilterActions();
+
+ // Stable callback for row clicks — lifted here so Row doesn't need useFilterActions
+ const onRowClick = React.useCallback(
+ (row: Row<TData>) => {
+ if (hasSelectColumn) {
+ setFilters({ uuid: detailRowId === row.id ? null : row.id });
+ } else {
+ row.toggleSelected();
+ }
+ },
+ [hasSelectColumn, detailRowId, setFilters],
+ );
+
+ return (
+ <DataTableProvider
+ table={table}
+ columns={columns}
+ filterFields={filterFields}
+ columnFilters={columnFilters}
+ sorting={sorting}
+ rowSelection={rowSelection}
+ columnOrder={columnOrder}
+ columnVisibility={columnVisibility}
+ enableColumnOrdering={true}
+ isLoading={isFetching || isLoading}
+ isFacetsLoading={isFacetsLoading}
+ refresh={refetch}
+ totalRows={totalRows}
+ filterRows={filterRows ?? table.getFilteredRowModel().rows.length}
+ getFacetedUniqueValues={getFacetedUniqueValues}
+ getFacetedMinMaxValues={getFacetedMinMaxValues}
+ >
+ <div
+ className={cn(
+ "flex h-full w-full flex-col overflow-hidden sm:flex-row",
+ "sm:[--controls-width:12rem] md:[--controls-width:15rem]",
+ className,
+ )}
+ style={
+ {
+ "--top-bar-height": `${topBarHeight}px`,
+ ...columnSizeVars,
+ } as React.CSSProperties
+ }
+ >
+ <div
+ className={cn(
+ "h-full w-full flex-col sm:w-[var(--controls-width)] sm:shrink-0",
+ "group-data-[expanded=false]/controls:hidden",
+ "hidden sm:flex",
+ )}
+ >
+ <div className="border-border bg-background shrink-0 border-b p-2">
+ <div className="flex h-[46px] items-center justify-between gap-3">
+ <p className="text-foreground px-2 font-medium">Filters</p>
+ <div>
+ {table.getState().columnFilters.length ? (
+ <DataTableResetButton />
+ ) : null}
+ </div>
+ </div>
+ </div>
+ {/* REMINDER: no top padding - it would offset the first filter row */}
+ <div className="min-h-0 flex-1 overflow-y-auto px-2 pb-2">
+ <DataTableFilterControls />
+ </div>
+ {footerSlot ? (
+ <div className="border-border bg-background shrink-0 border-t p-4">
+ {footerSlot}
+ </div>
+ ) : null}
+ </div>
+ <div
+ className={cn(
+ "border-border relative flex min-h-0 max-w-full flex-1 flex-col sm:border-l",
+ // Chrome issue
+ "sm:group-data-[expanded=true]/controls:max-w-[calc(100%-var(--controls-width))]",
+ )}
+ >
+ <DataTableFilterRail />
+ <div
+ ref={topBarRef}
+ className={cn(
+ "bg-background flex flex-col gap-4 p-2",
+ "z-10 shrink-0 pb-4",
+ )}
+ >
+ {commandSlot}
+ {/* TBD: better flexibility with compound components? */}
+ <DataTableToolbar
+ renderActions={toolbarActions ? () => toolbarActions : undefined}
+ />
+ {chartSlot}
+ </div>
+ <div className="z-0 min-h-0 flex-1">
+ <Table
+ ref={tableRef}
+ onScroll={onScroll}
+ // REMINDER: https://stackoverflow.com/questions/50361698/border-style-do-not-work-with-sticky-position-element
+ className="border-separate border-spacing-0"
+ containerClassName="h-full"
+ >
+ <TableHeader className={cn("bg-background sticky top-0 z-20")}>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow
+ key={headerGroup.id}
+ className={cn(
+ "bg-muted/50 hover:bg-muted/50",
+ "*:border-t [&>:not(:last-child)]:border-r",
+ )}
+ >
+ {headerGroup.headers.map((header) => {
+ return (
+ <TableHead
+ key={header.id}
+ style={
+ header.column.getCanResize()
+ ? {
+ width: `var(--header-${header.id.replaceAll(".", "-")}-size)`,
+ minWidth: `var(--header-${header.id.replaceAll(".", "-")}-size)`,
+ }
+ : header.column.columnDef.maxSize
+ ? {
+ width: `var(--header-${header.id.replaceAll(".", "-")}-size)`,
+ minWidth: `var(--header-${header.id.replaceAll(".", "-")}-size)`,
+ maxWidth: `var(--header-${header.id.replaceAll(".", "-")}-size)`,
+ }
+ : undefined
+ }
+ className={cn(
+ "border-border relative truncate border-b select-none last:[&>.cursor-col-resize]:opacity-0",
+ header.column.columnDef.meta?.headerClassName,
+ )}
+ aria-sort={
+ header.column.getIsSorted() === "asc"
+ ? "ascending"
+ : header.column.getIsSorted() === "desc"
+ ? "descending"
+ : "none"
+ }
+ >
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+ {header.column.getCanResize() && (
+ <div
+ onDoubleClick={() => header.column.resetSize()}
+ onMouseDown={header.getResizeHandler()}
+ onTouchStart={header.getResizeHandler()}
+ className={cn(
+ "user-select-none absolute top-0 -right-2 z-10 flex h-full w-4 cursor-col-resize touch-none justify-center",
+ "before:bg-border before:absolute before:inset-y-0 before:w-px before:translate-x-px",
+ )}
+ />
+ )}
+ </TableHead>
+ );
+ })}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody
+ id="content"
+ tabIndex={-1}
+ className="outline-primary outline-1 -outline-offset-1 transition-colors outline-none focus-visible:outline-solid"
+ // REMINDER: avoids scroll (skipping the table header) when using skip to content
+ style={{
+ scrollMarginTop: "calc(var(--top-bar-height) + 40px)",
+ }}
+ >
+ {table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ // REMINDER: if we want to add arrow navigation https://github.com/TanStack/table/discussions/2752#discussioncomment-192558
+ <React.Fragment key={row.id}>
+ {renderLiveRow?.({ row })}
+ <MemoizedRow
+ row={row}
+ table={table}
+ selected={row.getIsSelected()}
+ detailRowId={hasSelectColumn ? detailRowId : undefined}
+ onRowClick={onRowClick}
+ visibleColumnIds={visibleColumnIds}
+ columnOrder={columnOrderString}
+ />
+ </React.Fragment>
+ ))
+ ) : (
+ <React.Fragment>
+ {renderLiveRow?.()}
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="h-24 text-center"
+ >
+ No results.
+ </TableCell>
+ </TableRow>
+ </React.Fragment>
+ )}
+ <TableRow className="hover:bg-transparent data-[state=selected]:bg-transparent">
+ <TableCell colSpan={columns.length} className="text-center">
+ {hasNextPage || isFetching || isLoading ? (
+ <Button
+ disabled={isFetching || isLoading}
+ onClick={() => fetchNextPage()}
+ variant="outline"
+ >
+ {isFetching ? (
+ <LoaderCircle className="mr-2 h-4 w-4 animate-spin" />
+ ) : null}
+ Load More
+ </Button>
+ ) : (
+ <p className="text-muted-foreground text-sm">
+ No more data to load (
+ <span className="font-mono font-medium">
+ {formatCompactNumber(filterRows ?? 0)}
+ </span>{" "}
+ of{" "}
+ <span className="font-mono font-medium">
+ {formatCompactNumber(totalRows ?? 0)}
+ </span>{" "}
+ rows)
+ </p>
+ )}
+ </TableCell>
+ </TableRow>
+ </TableBody>
+ </Table>
+ </div>
+ </div>
+ </div>
+ {sheetSlot}
+ {floatingBarSlot}
+ </DataTableProvider>
+ );
+}
+
+/**
+ * REMINDER: this is the heaviest component in the table if lots of rows
+ * Some other components are rendered more often necessary, but are fixed size (not like rows that can grow in height)
+ * e.g. DataTableFilterControls, DataTableFilterCommand, DataTableToolbar, DataTableHeader
+ */
+
+function Row<TData>({
+ row,
+ table,
+ selected,
+ detailRowId,
+ onRowClick,
+ visibleColumnIds,
+ columnOrder,
+}: {
+ row: Row<TData>;
+ table: TTable<TData>;
+ // REMINDER: row.getIsSelected(); - just for memoization
+ selected?: boolean;
+ // When multi-select is enabled, the BYOS uuid for detail sheet (undefined = single-select mode)
+ detailRowId?: string | null;
+ onRowClick: (row: Row<TData>) => void;
+ // REMINDER: for memoization - triggers re-render when columns change
+ visibleColumnIds: string;
+ columnOrder: string;
+}) {
+ // REMINDER: rerender the row when live mode is toggled - used to opacity the row
+ // via the `getRowClassName` prop - but for some reasons it wil render the row on data fetch
+ useFilterState((s) => s.live);
+
+ const isMultiSelect = detailRowId !== undefined;
+ const isDetail = isMultiSelect && detailRowId === row.id;
+
+ const handleClick = React.useCallback(() => {
+ onRowClick(row);
+ }, [onRowClick, row]);
+
+ return (
+ <TableRow
+ id={row.id}
+ tabIndex={0}
+ // Single-select: data-state="selected" for the selected row
+ // Multi-select: data-detail + data-checked are independent (a row can be both)
+ data-state={!isMultiSelect && selected ? "selected" : undefined}
+ data-detail={isDetail ? "" : undefined}
+ data-checked={isMultiSelect && selected ? "" : undefined}
+ onClick={handleClick}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ handleClick();
+ }
+ }}
+ className={cn(
+ "[&>:not(:last-child)]:border-r",
+ "outline-primary focus-visible:bg-muted/50 outline-1 -outline-offset-1 transition-colors outline-none focus-visible:outline-solid",
+ "data-[state=selected]:outline-solid",
+ "data-detail:outline-solid",
+ "data-checked:bg-muted/50",
+ table.options.meta?.getRowClassName?.(row),
+ )}
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell
+ key={cell.id}
+ style={
+ cell.column.getCanResize()
+ ? {
+ width: `var(--col-${cell.column.id.replaceAll(".", "-")}-size)`,
+ maxWidth: `var(--col-${cell.column.id.replaceAll(".", "-")}-size)`,
+ }
+ : cell.column.columnDef.maxSize
+ ? {
+ width: `var(--col-${cell.column.id.replaceAll(".", "-")}-size)`,
+ minWidth: `var(--col-${cell.column.id.replaceAll(".", "-")}-size)`,
+ maxWidth: `var(--col-${cell.column.id.replaceAll(".", "-")}-size)`,
+ }
+ : undefined
+ }
+ className={cn(
+ "border-border truncate border-b",
+ cell.column.columnDef.meta?.cellClassName,
+ )}
+ >
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ ))}
+ </TableRow>
+ );
+}
+
+const MemoizedRow = React.memo(
+ Row,
+ (prev, next) =>
+ prev.row.id === next.row.id &&
+ // react-table rebuilds every `Row` on a data change, so the id alone would
+ // freeze the cells of a row whose content changed. `original` keeps its
+ // identity through react-query's structural sharing when nothing changed.
+ prev.row.original === next.row.original &&
+ prev.selected === next.selected &&
+ prev.detailRowId === next.detailRowId &&
+ prev.onRowClick === next.onRowClick &&
+ prev.visibleColumnIds === next.visibleColumnIds &&
+ prev.columnOrder === next.columnOrder,
+) as typeof Row;
diff --git a/packages/ui/src/components/data-table-filters/data-table-infinite/hover-card-timestamp.tsx b/packages/ui/src/components/data-table-filters/data-table-infinite/hover-card-timestamp.tsx
new file mode 100644
index 000000000..8a3416283
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-infinite/hover-card-timestamp.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import { UTCDate } from "@date-fns/utc";
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from "@openstatus/ui/components/ui/hover-card";
+import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";
+import { cn } from "@openstatus/ui/lib/utils";
+import { format, formatDistanceToNowStrict } from "date-fns";
+import { Check, Copy } from "lucide-react";
+import type { ComponentPropsWithoutRef } from "react";
+
+type HoverCardContentProps = ComponentPropsWithoutRef<typeof HoverCardContent>;
+
+interface HoverCardTimestampProps {
+ date: Date;
+ side?: HoverCardContentProps["side"];
+ sideOffset?: HoverCardContentProps["sideOffset"];
+ align?: HoverCardContentProps["align"];
+ alignOffset?: HoverCardContentProps["alignOffset"];
+ className?: string;
+}
+
+export function HoverCardTimestamp({
+ date,
+ side = "right",
+ align = "start",
+ alignOffset = -4,
+ sideOffset,
+ className,
+}: HoverCardTimestampProps) {
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+
+ return (
+ <HoverCard openDelay={0} closeDelay={0}>
+ <HoverCardTrigger asChild>
+ {/* Phrasing content: the callers render it inside a `<span>` - and it
+ has to be focusable for the hover card to open without a pointer. */}
+ <button
+ type="button"
+ className={cn(
+ "font-mono whitespace-nowrap focus-visible:underline",
+ className,
+ )}
+ >
+ {format(date, "LLL dd, y HH:mm:ss")}
+ </button>
+ </HoverCardTrigger>
+ {/* Portal is built into HoverCardContent in shadcn v4 */}
+ <HoverCardContent
+ className="z-10 w-auto p-2"
+ {...{ side, align, alignOffset, sideOffset }}
+ >
+ <dl className="flex flex-col gap-1">
+ <Row value={String(date.getTime())} label="Timestamp" />
+ <Row
+ value={format(new UTCDate(date), "LLL dd, y HH:mm:ss")}
+ label="UTC"
+ />
+ <Row value={format(date, "LLL dd, y HH:mm:ss")} label={timezone} />
+ <Row
+ value={formatDistanceToNowStrict(date, { addSuffix: true })}
+ label="Relative"
+ />
+ </dl>
+ </HoverCardContent>
+ </HoverCard>
+ );
+}
+
+function Row({ value, label }: { value: string; label: string }) {
+ const { copy, isCopied } = useCopyToClipboard();
+
+ return (
+ <div
+ className="group flex items-center justify-between gap-4 text-sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ copy(value, {});
+ }}
+ >
+ <dt className="text-muted-foreground">{label}</dt>
+ <dd className="flex items-center gap-1 truncate font-mono">
+ <span className="invisible group-hover:visible">
+ {!isCopied ? (
+ <Copy className="h-3 w-3" />
+ ) : (
+ <Check className="h-3 w-3" />
+ )}
+ </span>
+ {value}
+ </dd>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-provider.tsx b/packages/ui/src/components/data-table-filters/data-table-provider.tsx
new file mode 100644
index 000000000..a541e1e38
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-provider.tsx
@@ -0,0 +1,121 @@
+import { ControlsProvider } from "@openstatus/ui/components/data-table-filters/controls";
+import { DataTableFilterField } from "@openstatus/ui/components/data-table-filters/types";
+import type {
+ ColumnDef,
+ ColumnFiltersState,
+ PaginationState,
+ RowSelectionState,
+ SortingState,
+ Table,
+ VisibilityState,
+} from "@tanstack/react-table";
+import { createContext, useContext, useMemo } from "react";
+
+import { DataTableStoreSync } from "./data-table-store-sync";
+
+// REMINDER: read about how to move controlled state out of the useReactTable hook
+// https://github.com/TanStack/table/discussions/4005#discussioncomment-7303569
+
+interface DataTableStateContextType {
+ columnFilters: ColumnFiltersState;
+ sorting: SortingState;
+ rowSelection: RowSelectionState;
+ columnOrder: string[];
+ columnVisibility: VisibilityState;
+ pagination: PaginationState;
+ enableColumnOrdering: boolean;
+}
+
+interface DataTableBaseContextType<TData = unknown, TValue = unknown> {
+ table: Table<TData>;
+ filterFields: DataTableFilterField<TData>[];
+ columns: ColumnDef<TData, TValue>[];
+ isLoading?: boolean;
+ /**
+ * Whether the facet counts are still in flight. Separate from `isLoading`,
+ * which tracks the rows: a table that fetches facets in their own request
+ * has rows on screen while the counts are still pending, and the filter
+ * would otherwise blank its counts in between.
+ */
+ isFacetsLoading?: boolean;
+ /** Refetch the query behind the table; the toolbar hides its button without it. */
+ refresh?: () => void;
+ totalRows?: number;
+ filterRows?: number;
+ getFacetedUniqueValues?: (
+ table: Table<TData>,
+ columnId: string,
+ ) => Map<string, number>;
+ getFacetedMinMaxValues?: (
+ table: Table<TData>,
+ columnId: string,
+ ) => undefined | [number, number];
+}
+
+interface DataTableContextType<TData = unknown, TValue = unknown>
+ extends DataTableStateContextType, DataTableBaseContextType<TData, TValue> {}
+
+export const DataTableContext = createContext<DataTableContextType<
+ any,
+ any
+> | null>(null);
+
+export function DataTableProvider<TData, TValue>({
+ children,
+ ...props
+}: Partial<DataTableStateContextType> &
+ DataTableBaseContextType<TData, TValue> & {
+ children: React.ReactNode;
+ }) {
+ const value = useMemo(
+ // eslint-disable-next-line react-hooks/preserve-manual-memoization
+ () => ({
+ ...props,
+ columnFilters: props.columnFilters ?? [],
+ sorting: props.sorting ?? [],
+ rowSelection: props.rowSelection ?? {},
+ columnOrder: props.columnOrder ?? [],
+ columnVisibility: props.columnVisibility ?? {},
+ pagination: props.pagination ?? { pageIndex: 0, pageSize: 10 },
+ enableColumnOrdering: props.enableColumnOrdering ?? false,
+ }),
+ [
+ props.columnFilters,
+ props.sorting,
+ props.rowSelection,
+ props.columnOrder,
+ props.columnVisibility,
+ props.pagination,
+ props.table,
+ props.filterFields,
+ props.columns,
+ props.enableColumnOrdering,
+ props.isLoading,
+ props.isFacetsLoading,
+ props.refresh,
+ props.totalRows,
+ props.filterRows,
+ props.getFacetedUniqueValues,
+ props.getFacetedMinMaxValues,
+ ],
+ );
+
+ return (
+ <DataTableContext.Provider value={value}>
+ <ControlsProvider>
+ <DataTableStoreSync />
+ {children}
+ </ControlsProvider>
+ </DataTableContext.Provider>
+ );
+}
+
+export function useDataTable<TData, TValue>() {
+ const context = useContext(DataTableContext);
+
+ if (!context) {
+ throw new Error("useDataTable must be used within a DataTableProvider");
+ }
+
+ return context as DataTableContextType<TData, TValue>;
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-refresh-button.tsx b/packages/ui/src/components/data-table-filters/data-table-refresh-button.tsx
new file mode 100644
index 000000000..954a1f4f8
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-refresh-button.tsx
@@ -0,0 +1,41 @@
+"use client";
+
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { Button } from "@openstatus/ui/components/ui/button";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui/components/ui/tooltip";
+import { cn } from "@openstatus/ui/lib/utils";
+import { RefreshCcw } from "lucide-react";
+
+export function DataTableRefreshButton() {
+ const { refresh, isLoading } = useDataTable();
+ if (!refresh) return null;
+
+ return (
+ <TooltipProvider>
+ <Tooltip delayDuration={100}>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ className="shadow-none"
+ disabled={isLoading}
+ onClick={() => refresh()}
+ >
+ <RefreshCcw
+ className={cn("h-4 w-4", isLoading && "animate-spin")}
+ />
+ <span className="sr-only">Refresh</span>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <p className="text-nowrap">Refresh data</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-reset-button.tsx b/packages/ui/src/components/data-table-filters/data-table-reset-button.tsx
new file mode 100644
index 000000000..1f44d8d37
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-reset-button.tsx
@@ -0,0 +1,40 @@
+"use client";
+
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { Kbd } from "@openstatus/ui/components/ui/kbd";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui/components/ui/tooltip";
+import { useHotKey } from "@openstatus/ui/hooks/use-hot-key";
+import { X } from "lucide-react";
+
+export function DataTableResetButton() {
+ const { table } = useDataTable();
+ useHotKey(table.resetColumnFilters, "Escape");
+
+ return (
+ <TooltipProvider>
+ <Tooltip delayDuration={100}>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" onClick={() => table.resetColumnFilters()}>
+ <X className="mr-2 h-4 w-4" />
+ Reset
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="left">
+ <p className="text-nowrap">
+ Reset filters with{" "}
+ <Kbd className="text-muted-foreground group-hover:text-accent-foreground ml-1">
+ <span className="mr-1">⌘</span>
+ <span>Esc</span>
+ </Kbd>
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-store-sync.tsx b/packages/ui/src/components/data-table-filters/data-table-store-sync.tsx
new file mode 100644
index 000000000..aa2c216c9
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-store-sync.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+/**
+ * DataTableStoreSync - Syncs React Table state to/from BYOS adapter
+ *
+ * On initial mount: seeds the table's columnFilters from BYOS state (BYOS → Table).
+ * This handles the case where URL params are available in BYOS but useState missed
+ * them during SSR/hydration (e.g. nuqs reads URL after initial render).
+ *
+ * After mount: syncs changes from React Table's state (columnFilters, sorting,
+ * rowSelection) to the BYOS adapter (Table → BYOS). Filter components update
+ * the table directly via column.setFilterValue(), and this component propagates
+ * those changes to the BYOS adapter for URL sync (nuqs) or state persistence.
+ */
+import { useStoreContext } from "@openstatus/ui/lib/data-table-filters/store/context";
+import { useFilterActions } from "@openstatus/ui/lib/data-table-filters/store/hooks/useFilterActions";
+import { isStateEqual } from "@openstatus/ui/lib/data-table-filters/store/schema/index";
+import { useEffect, useRef } from "react";
+
+import { useDataTable } from "./data-table-provider";
+
+export function DataTableStoreSync() {
+ useDataTableStoreSync();
+ return null;
+}
+
+/**
+ * Hook version for more control - syncs filters, sorting, and selection
+ */
+export function useDataTableStoreSync() {
+ const context = useStoreContext();
+ const { table, filterFields, sorting, rowSelection } = useDataTable();
+ const { setFilters } = useFilterActions();
+
+ const lastSentFiltersRef = useRef<Record<string, unknown>>({});
+ const lastSentSortRef = useRef<{ id: string; desc: boolean } | null>(null);
+ const lastSentUuidRef = useRef<string>("");
+ const isInitialMount = useRef(true);
+
+ const columnFilters = table.getState().columnFilters;
+
+ // Sync column filters
+ useEffect(() => {
+ if (!context) return;
+ if (isInitialMount.current) {
+ isInitialMount.current = false;
+ const filterFieldKeys = new Set(
+ filterFields?.map((f) => f.value as string) || [],
+ );
+ const currentFilters: Record<string, unknown> = {};
+ for (const filter of columnFilters) {
+ if (filterFieldKeys.has(filter.id)) {
+ currentFilters[filter.id] = filter.value;
+ }
+ }
+
+ // Seed table from BYOS on initial mount (handles URL hydration where
+ // useState(defaultColumnFilters) missed the URL-derived values)
+ const byosState = context.adapter.getSnapshot().state as Record<
+ string,
+ unknown
+ >;
+ for (const key of filterFieldKeys) {
+ if (key in currentFilters) continue;
+ const byosValue = byosState[key];
+ if (byosValue == null) continue;
+ if (Array.isArray(byosValue) && byosValue.length === 0) continue;
+ table.getColumn(key)?.setFilterValue(byosValue);
+ currentFilters[key] = byosValue;
+ }
+
+ lastSentFiltersRef.current = { ...currentFilters };
+ lastSentSortRef.current = sorting?.[0] || null;
+ const selectedKeys = Object.keys(rowSelection || {});
+ lastSentUuidRef.current = selectedKeys.length > 0 ? selectedKeys[0] : "";
+ return;
+ }
+
+ const filterFieldKeys = new Set(
+ filterFields?.map((f) => f.value as string) || [],
+ );
+
+ const currentFilters: Record<string, unknown> = {};
+ for (const filter of columnFilters) {
+ if (filterFieldKeys.has(filter.id)) {
+ currentFilters[filter.id] = filter.value;
+ }
+ }
+
+ if (isStateEqual(currentFilters, lastSentFiltersRef.current)) {
+ return;
+ }
+
+ const updates: Record<string, unknown> = { ...currentFilters };
+
+ // Only null out keys that we previously sent — never clear BYOS filters
+ // that were set externally (e.g. from URL) and not managed by this sync.
+ for (const key of Object.keys(lastSentFiltersRef.current)) {
+ if (!(key in currentFilters)) {
+ updates[key] = null;
+ }
+ }
+
+ lastSentFiltersRef.current = { ...currentFilters };
+ setFilters(updates);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [columnFilters, context, filterFields, setFilters]);
+
+ // Sync sorting
+ useEffect(() => {
+ if (!context) return;
+ if (isInitialMount.current) return;
+
+ const newSort = sorting?.[0] || null;
+ const lastSort = lastSentSortRef.current;
+
+ if (newSort?.id === lastSort?.id && newSort?.desc === lastSort?.desc) {
+ return;
+ }
+
+ lastSentSortRef.current = newSort;
+ setFilters({ sort: newSort });
+ }, [sorting, context, setFilters]);
+
+ // Sync row selection (single-select only — skip when multi-row selection is
+ // enabled because rowSelection is used for checkbox bulk actions, not sheet)
+ useEffect(() => {
+ if (!context) return;
+ if (isInitialMount.current) return;
+ if (table.options.enableMultiRowSelection) return;
+
+ const selectedKeys = Object.keys(rowSelection || {});
+ const newUuid = selectedKeys.length > 0 ? selectedKeys[0] : null;
+ const newUuidStr = newUuid || "";
+
+ if (newUuidStr === lastSentUuidRef.current) {
+ return;
+ }
+
+ lastSentUuidRef.current = newUuidStr;
+ setFilters({ uuid: newUuid });
+ }, [
+ rowSelection,
+ context,
+ setFilters,
+ table.options.enableMultiRowSelection,
+ ]);
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-toolbar.tsx b/packages/ui/src/components/data-table-filters/data-table-toolbar.tsx
new file mode 100644
index 000000000..b6d7419ed
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-toolbar.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { useControls } from "@openstatus/ui/components/data-table-filters/controls";
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { Kbd } from "@openstatus/ui/components/ui/kbd";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui/components/ui/tooltip";
+import { useHotKey } from "@openstatus/ui/hooks/use-hot-key";
+import { formatCompactNumber } from "@openstatus/ui/lib/format";
+import { PanelLeftClose, PanelLeftOpen } from "lucide-react";
+
+import { DataTableFilterControlsDrawer } from "./data-table-filter-controls-drawer";
+import { DataTableRefreshButton } from "./data-table-refresh-button";
+import { DataTableResetButton } from "./data-table-reset-button";
+import { DataTableViewOptions } from "./data-table-view-options";
+
+interface DataTableToolbarProps {
+ renderActions?: () => React.ReactNode;
+}
+
+export function DataTableToolbar({ renderActions }: DataTableToolbarProps) {
+ const { table, isLoading, columnFilters, totalRows, filterRows } =
+ useDataTable();
+ const { open, setOpen } = useControls();
+ useHotKey(() => setOpen((prev) => !prev), "b");
+ const rows = {
+ total: totalRows ?? table.getCoreRowModel().rows.length,
+ filtered: filterRows ?? table.getFilteredRowModel().rows.length,
+ };
+
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <div className="flex flex-wrap items-center gap-2">
+ <TooltipProvider>
+ <Tooltip delayDuration={100}>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ onClick={() => setOpen((prev) => !prev)}
+ className="hidden gap-2 sm:flex"
+ >
+ {open ? (
+ <>
+ <PanelLeftClose className="h-4 w-4" />
+ <span className="hidden md:block">Hide Controls</span>
+ </>
+ ) : (
+ <>
+ <PanelLeftOpen className="h-4 w-4" />
+ <span className="hidden md:block">Show Controls</span>
+ </>
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p className="text-nowrap">
+ Toggle controls with{" "}
+ <Kbd className="text-muted-foreground group-hover:text-accent-foreground ml-1">
+ <span className="mr-1">⌘</span>
+ <span>B</span>
+ </Kbd>
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <div className="block sm:hidden">
+ <DataTableFilterControlsDrawer />
+ </div>
+ <div>
+ <p className="text-muted-foreground hidden text-sm sm:block">
+ <span className="font-mono font-medium">
+ {formatCompactNumber(rows.filtered)}
+ </span>{" "}
+ of{" "}
+ <span className="font-mono font-medium">
+ {formatCompactNumber(rows.total)}
+ </span>{" "}
+ row(s) <span className="sr-only sm:not-sr-only">filtered</span>
+ </p>
+ <p className="text-muted-foreground block text-sm sm:hidden">
+ <span className="font-mono font-medium">
+ {formatCompactNumber(rows.filtered)}
+ </span>{" "}
+ row(s)
+ </p>
+ </div>
+ </div>
+ <div className="ml-auto flex items-center gap-2">
+ {columnFilters.length ? <DataTableResetButton /> : null}
+ {renderActions?.()}
+ <DataTableRefreshButton />
+ <DataTableViewOptions />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/data-table-view-options.tsx b/packages/ui/src/components/data-table-filters/data-table-view-options.tsx
new file mode 100644
index 000000000..10baa2907
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/data-table-view-options.tsx
@@ -0,0 +1,127 @@
+"use client";
+
+import {
+ Sortable,
+ SortableDragHandle,
+ SortableItem,
+} from "@openstatus/ui/components/custom/sortable";
+import { useDataTable } from "@openstatus/ui/components/data-table-filters/data-table-provider";
+import { Button } from "@openstatus/ui/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@openstatus/ui/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@openstatus/ui/components/ui/popover";
+import { cn } from "@openstatus/ui/lib/utils";
+import { Check, GripVertical, Settings2 } from "lucide-react";
+import { useMemo, useState } from "react";
+
+export function DataTableViewOptions() {
+ const { table, enableColumnOrdering } = useDataTable();
+ const [open, setOpen] = useState(false);
+ const [drag, setDrag] = useState(false);
+ const [search, setSearch] = useState("");
+
+ const columnOrder = table.getState().columnOrder;
+
+ const sortedColumns = useMemo(
+ () =>
+ table.getAllColumns().sort((a, b) => {
+ return columnOrder.indexOf(a.id) - columnOrder.indexOf(b.id);
+ }),
+ [columnOrder, table],
+ );
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ role="combobox"
+ aria-expanded={open}
+ className="shadow-none"
+ >
+ <Settings2 className="h-4 w-4" />
+ <span className="sr-only">View</span>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent side="bottom" align="end" className="w-[200px] p-0">
+ <Command>
+ <CommandInput
+ value={search}
+ onValueChange={setSearch}
+ placeholder="Search options..."
+ />
+ <CommandList>
+ <CommandEmpty>No option found.</CommandEmpty>
+ <CommandGroup>
+ <Sortable
+ value={sortedColumns.map((c) => ({ id: c.id }))}
+ onValueChange={(items) =>
+ table.setColumnOrder(items.map((c) => c.id))
+ }
+ overlay={<div className="bg-muted/60 h-8 w-full rounded-md" />}
+ onDragStart={() => setDrag(true)}
+ onDragEnd={() => setDrag(false)}
+ onDragCancel={() => setDrag(false)}
+ >
+ {sortedColumns
+ .filter(
+ (column) =>
+ typeof column.accessorFn !== "undefined" &&
+ column.getCanHide(),
+ )
+ .map((column) => (
+ <SortableItem key={column.id} value={column.id} asChild>
+ <CommandItem
+ value={column.id}
+ onSelect={() =>
+ column.toggleVisibility(!column.getIsVisible())
+ }
+ className={"capitalize"}
+ disabled={drag}
+ >
+ <div
+ className={cn(
+ "border-foreground! flex h-4 w-4 items-center justify-center rounded-sm border",
+ column.getIsVisible()
+ ? "bg-primary text-primary-foreground"
+ : "opacity-50 [&_svg]:invisible",
+ )}
+ >
+ <Check className={cn("text-background size-3")} />
+ </div>
+ <span>{column.columnDef.meta?.label || column.id}</span>
+ <span data-slot="command-shortcut" className="hidden" />
+ {enableColumnOrdering && !search ? (
+ <SortableDragHandle
+ variant="ghost"
+ size="icon"
+ className="text-muted-foreground hover:text-foreground focus:bg-muted focus:text-foreground ml-auto size-5"
+ >
+ <GripVertical
+ className="size-4"
+ aria-hidden="true"
+ />
+ </SortableDragHandle>
+ ) : null}
+ </CommandItem>
+ </SortableItem>
+ ))}
+ </Sortable>
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/ui/src/components/data-table-filters/types.ts b/packages/ui/src/components/data-table-filters/types.ts
new file mode 100644
index 000000000..e8d591781
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/types.ts
@@ -0,0 +1,99 @@
+import type { SerializableDisplayConfig } from "@openstatus/ui/lib/data-table-filters/table-schema/types";
+import type { JSX } from "react";
+
+export type SearchParams = {
+ [key: string]: string | string[] | undefined;
+};
+
+export type DatePreset = {
+ label: string;
+ from: Date;
+ to: Date;
+ shortcut: string;
+};
+
+// TODO: we could type the value(!) especially when using enums
+export type Option = {
+ label: string;
+ value: string | boolean | number | undefined;
+};
+
+export type Input = {
+ type: "input";
+ options?: Option[];
+};
+
+export type Checkbox = {
+ type: "checkbox";
+ component?: (props: Option) => JSX.Element | null;
+ options?: Option[];
+ /**
+ * Keep every declared option in the list even when the facets hold no rows
+ * for it, rendering a count of `0` instead of dropping it.
+ */
+ keepEmptyOptions?: boolean;
+};
+
+export type Slider = {
+ type: "slider";
+ min: number;
+ max: number;
+ // if options is undefined, faceted unique values from the data are used in the command
+ options?: Option[];
+ unit?: string;
+};
+
+export type Timerange = {
+ type: "timerange";
+ options?: Option[]; // required for TS
+ presets?: DatePreset[];
+};
+
+export type Base<TData> = {
+ label: string;
+ value: keyof TData;
+ /**
+ * Defines if the accordion in the filter bar is open by default
+ */
+ defaultOpen?: boolean;
+ /**
+ * Defines if the command input is disabled for this field
+ */
+ commandDisabled?: boolean;
+};
+
+export type DataTableCheckboxFilterField<TData> = Base<TData> & Checkbox;
+export type DataTableSliderFilterField<TData> = Base<TData> & Slider;
+export type DataTableInputFilterField<TData> = Base<TData> & Input;
+export type DataTableTimerangeFilterField<TData> = Base<TData> & Timerange;
+
+export type DataTableFilterField<TData> =
+ | DataTableCheckboxFilterField<TData>
+ | DataTableSliderFilterField<TData>
+ | DataTableInputFilterField<TData>
+ | DataTableTimerangeFilterField<TData>;
+
+/** ----------------------------------------- */
+
+export type SheetField<TData, TMeta = Record<string, unknown>> = {
+ id: keyof TData;
+ label: string;
+ // FIXME: rethink that! I dont think we need this as there is no input type
+ // REMINDER: readonly if we only want to copy the value (e.g. uuid)
+ // TODO: we might have some values that are not in the data but can be computed
+ type: "readonly" | "input" | "checkbox" | "slider" | "timerange";
+ display?: SerializableDisplayConfig;
+ component?: (
+ // REMINDER: this is used to pass additional data like the `InfiniteQueryMeta`
+ props: TData & {
+ metadata?: {
+ totalRows: number;
+ filterRows: number;
+ totalRowsFetched: number;
+ } & TMeta;
+ },
+ ) => JSX.Element | null | string;
+ condition?: (props: TData) => boolean;
+ className?: string;
+ skeletonClassName?: string;
+};
diff --git a/packages/ui/src/components/data-table-filters/utils.ts b/packages/ui/src/components/data-table-filters/utils.ts
new file mode 100644
index 000000000..7ab4aeeaa
--- /dev/null
+++ b/packages/ui/src/components/data-table-filters/utils.ts
@@ -0,0 +1,65 @@
+import {
+ ARRAY_DELIMITER,
+ RANGE_DELIMITER,
+ SLIDER_DELIMITER,
+} from "@openstatus/ui/lib/data-table-filters/delimiters";
+import { isArrayOfDates } from "@openstatus/ui/lib/data-table-filters/is-array";
+import {
+ serializeFilterValue,
+ tokenizeFilterInput,
+} from "@openstatus/ui/lib/data-table-filters/tokenize";
+import type { ColumnFiltersState } from "@tanstack/react-table";
+import { z } from "zod";
+
+import type { DataTableFilterField } from "./types";
+
+export function deserialize<T extends z.ZodObject>(schema: T) {
+ const castToSchema = z.preprocess((val) => {
+ if (typeof val !== "string") return val;
+ return tokenizeFilterInput(val).reduce(
+ (prev, [name, value]) => {
+ if (!value) return prev;
+ prev[name] = value;
+ return prev;
+ },
+ {} as Record<string, unknown>,
+ );
+ }, schema);
+ return (value: string) => castToSchema.safeParse(value);
+}
+
+export function serializeColumnFilters<TData>(
+ columnFilters: ColumnFiltersState,
+ filterFields?: DataTableFilterField<TData>[],
+) {
+ return columnFilters.reduce((prev, curr) => {
+ const { type, commandDisabled } = filterFields?.find(
+ (field) => curr.id === field.value,
+ ) || { commandDisabled: true }; // if column filter is not found, disable the command by default
+
+ if (commandDisabled) return prev;
+
+ const append = (value: string) =>
+ `${prev}${curr.id}:${serializeFilterValue(value)} `;
+
+ if (Array.isArray(curr.value)) {
+ if (type === "slider") {
+ return append(curr.value.join(SLIDER_DELIMITER));
+ }
+ if (type === "checkbox") {
+ return append(curr.value.join(ARRAY_DELIMITER));
+ }
+ if (type === "timerange") {
+ // the timerange filter holds `Date[]`, and the parser expects epoch millis
+ if (isArrayOfDates(curr.value)) {
+ return append(
+ curr.value.map((date) => date.getTime()).join(RANGE_DELIMITER),
+ );
+ }
+ return append(curr.value.join(RANGE_DELIMITER));
+ }
+ }
+
+ return append(String(curr.value));
+ }, "");
+}
diff --git a/packages/ui/src/components/ui/accordion.tsx b/packages/ui/src/components/ui/accordion.tsx
new file mode 100644
index 000000000..ea2610a46
--- /dev/null
+++ b/packages/ui/src/components/ui/accordion.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { cn } from "@openstatus/ui/lib/utils";
+import { ChevronDownIcon } from "lucide-react";
+import { Accordion as AccordionPrimitive } from "radix-ui";
+import * as React from "react";
+
+function Accordion({
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
+ return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
+}
+
+function AccordionItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
+ return (
+ <AccordionPrimitive.Item
+ data-slot="accordion-item"
+ className={cn("border-b last:border-b-0", className)}
+ {...props}
+ />
+ );
+}
+
+function AccordionTrigger({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
+ return (
+ <AccordionPrimitive.Header className="flex">
+ <AccordionPrimitive.Trigger
+ data-slot="accordion-trigger"
+ className={cn(
+ "focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
+ </AccordionPrimitive.Trigger>
+ </AccordionPrimitive.Header>
+ );
+}
+
+function AccordionContent({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
+ return (
+ <AccordionPrimitive.Content
+ data-slot="accordion-content"
+ className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
+ {...props}
+ >
+ <div className={cn("pt-0 pb-4", className)}>{children}</div>
+ </AccordionPrimitive.Content>
+ );
+}
+
+export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
diff --git a/packages/ui/src/hooks/use-hot-key.ts b/packages/ui/src/hooks/use-hot-key.ts
new file mode 100644
index 000000000..53f88064a
--- /dev/null
+++ b/packages/ui/src/hooks/use-hot-key.ts
@@ -0,0 +1,33 @@
+import { useEffect, useRef } from "react";
+
+export function useHotKey(
+ callback: () => void,
+ key: string,
+ options?: { shift?: boolean },
+): void {
+ // Use ref to always have the latest callback without re-registering the listener
+ const callbackRef = useRef(callback);
+ // eslint-disable-next-line react-hooks/refs
+ callbackRef.current = callback;
+
+ useEffect(() => {
+ function handler(e: KeyboardEvent) {
+ const shiftMatch = options?.shift ? e.shiftKey : !e.shiftKey;
+ if (
+ e.key.toLowerCase() === key.toLowerCase() &&
+ (e.metaKey || e.ctrlKey) &&
+ shiftMatch
+ ) {
+ // every shortcut is meta/ctrl based, so stop the browser default (⌘K
+ // focusing the address bar, ⌘U opening the source view, …)
+ e.preventDefault();
+ callbackRef.current();
+ }
+ }
+
+ window.addEventListener("keydown", handler);
+ return () => {
+ window.removeEventListener("keydown", handler);
+ };
+ }, [key, options?.shift]);
+}
diff --git a/packages/ui/src/hooks/use-local-storage.ts b/packages/ui/src/hooks/use-local-storage.ts
new file mode 100644
index 000000000..ebb2fd7dd
--- /dev/null
+++ b/packages/ui/src/hooks/use-local-storage.ts
@@ -0,0 +1,83 @@
+"use client";
+
+import { useCallback, useRef, useSyncExternalStore } from "react";
+
+const listeners = new Set<() => void>();
+// getSnapshot must return a referentially stable value, so parsed values are
+// memoized against the raw string they were parsed from.
+const cache = new Map<string, { raw: string | null; value: unknown }>();
+
+function subscribe(onStoreChange: () => void) {
+ listeners.add(onStoreChange);
+ window.addEventListener("storage", onStoreChange);
+ return () => {
+ listeners.delete(onStoreChange);
+ window.removeEventListener("storage", onStoreChange);
+ };
+}
+
+function emit() {
+ for (const listener of listeners) listener();
+}
+
+function readRaw(key: string): string | null {
+ try {
+ return window.localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function getSnapshot<T>(key: string, fallback: T): T {
+ const raw = readRaw(key);
+ const cached = cache.get(key);
+ if (cached && cached.raw === raw) return cached.value as T;
+
+ let value = fallback;
+ if (raw !== null) {
+ try {
+ value = JSON.parse(raw) as T;
+ } catch {
+ value = fallback;
+ }
+ }
+ cache.set(key, { raw, value });
+ return value;
+}
+
+export function useLocalStorage<T>(
+ key: string,
+ initialValue: T,
+): [T, React.Dispatch<React.SetStateAction<T>>] {
+ const initialValueRef = useRef(initialValue);
+
+ // The server snapshot is the fallback, so SSR and hydration agree; React
+ // re-reads localStorage right after hydrating.
+ const storedValue = useSyncExternalStore(
+ subscribe,
+ () => getSnapshot(key, initialValueRef.current),
+ () => initialValueRef.current,
+ );
+
+ const setValue: React.Dispatch<React.SetStateAction<T>> = useCallback(
+ (value) => {
+ const newValue =
+ value instanceof Function
+ ? value(getSnapshot(key, initialValueRef.current))
+ : value;
+
+ try {
+ const raw = JSON.stringify(newValue);
+ window.localStorage.setItem(key, raw);
+ cache.set(key, { raw, value: newValue });
+ } catch {
+ // Storage unavailable or over quota: keep the value in memory only.
+ cache.set(key, { raw: readRaw(key), value: newValue });
+ }
+ emit();
+ },
+ [key],
+ );
+
+ return [storedValue, setValue];
+}
diff --git a/packages/ui/src/lib/data-table-filters/ai/context.ts b/packages/ui/src/lib/data-table-filters/ai/context.ts
new file mode 100644
index 000000000..2f7dedeef
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/ai/context.ts
@@ -0,0 +1,82 @@
+import {
+ resolveColumn,
+ type TableSchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+
+export type AIFieldContext = {
+ key: string;
+ label: string;
+ description?: string;
+ dataType: string;
+ filterType: string;
+ allowedValues?: string[];
+ min?: number;
+ max?: number;
+ unit?: string;
+};
+
+export type AIContext = {
+ fields: AIFieldContext[];
+};
+
+/**
+ * Extracts structured context from a table schema definition for use in LLM prompts.
+ *
+ * Returns metadata about each filterable column: field name, label, data type,
+ * filter type, allowed values, bounds, and description. Non-filterable columns
+ * are excluded. Command-disabled columns are intentionally included so the AI
+ * can set filters (e.g. date ranges) that aren't available in the command palette.
+ */
+export function generateAIContext(schema: TableSchemaDefinition): AIContext {
+ const fields: AIFieldContext[] = [];
+
+ for (const [key, builder] of Object.entries(schema)) {
+ const config = resolveColumn(builder);
+ if (!config.filter) continue;
+
+ const field: AIFieldContext = {
+ key,
+ label: config.label || key,
+ dataType: config.kind,
+ filterType: config.filter.type,
+ };
+
+ if (config.description) {
+ field.description = config.description;
+ }
+
+ // Allowed values for checkbox filters (enums, booleans, arrays)
+ if (config.filter.type === "checkbox" && config.filter.options) {
+ field.allowedValues = config.filter.options.map((o) => String(o.value));
+ } else if (config.kind === "enum" && config.enumValues) {
+ field.allowedValues = [...config.enumValues];
+ } else if (
+ config.kind === "array" &&
+ config.arrayItem?.kind === "enum" &&
+ config.arrayItem.enumValues
+ ) {
+ field.allowedValues = [...config.arrayItem.enumValues];
+ }
+
+ // Bounds for slider filters
+ if (config.filter.type === "slider") {
+ if (config.filter.min !== undefined) field.min = config.filter.min;
+ if (config.filter.max !== undefined) field.max = config.filter.max;
+ }
+
+ // Unit from filter or display config
+ if (config.filter.unit) {
+ field.unit = config.filter.unit;
+ } else if (
+ config.display.type === "number" &&
+ "unit" in config.display &&
+ config.display.unit
+ ) {
+ field.unit = config.display.unit;
+ }
+
+ fields.push(field);
+ }
+
+ return { fields };
+}
diff --git a/packages/ui/src/lib/data-table-filters/ai/detect.ts b/packages/ui/src/lib/data-table-filters/ai/detect.ts
new file mode 100644
index 000000000..bdb2603c4
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/ai/detect.ts
@@ -0,0 +1,47 @@
+import {
+ resolveColumn,
+ type TableSchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+
+/**
+ * Determines if the user's input is a structured `key:value` filter query
+ * or natural language that should be sent to an AI endpoint.
+ *
+ * Returns `true` if the input matches the structured query format (i.e.,
+ * contains a known field name followed by `:`). Returns `false` for natural
+ * language input.
+ *
+ * @param input - The raw user input from the command palette
+ * @param schema - Table schema definition to derive known field names
+ */
+export function isStructuredQuery(
+ input: string,
+ schema: TableSchemaDefinition,
+): boolean {
+ const trimmed = input.trim();
+ if (trimmed.length === 0) return false;
+
+ // Collect known filterable field keys
+ const fieldKeys = new Set<string>();
+ for (const [key, builder] of Object.entries(schema)) {
+ const config = resolveColumn(builder);
+ if (config.filter && !config.filter.commandDisabled) {
+ fieldKeys.add(key);
+ }
+ }
+
+ // Check if any token in the input starts with `knownField:`
+ // This handles both `regions:ams,gru` and `regions:ams latency:100-500`
+ const tokens = trimmed.split(/\s+/);
+ for (const token of tokens) {
+ const colonIndex = token.indexOf(":");
+ if (colonIndex > 0) {
+ const field = token.substring(0, colonIndex);
+ if (fieldKeys.has(field)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
diff --git a/packages/ui/src/lib/data-table-filters/ai/diff-partial.ts b/packages/ui/src/lib/data-table-filters/ai/diff-partial.ts
new file mode 100644
index 000000000..f2b9a9231
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/ai/diff-partial.ts
@@ -0,0 +1,103 @@
+import {
+ resolveColumn,
+ type TableSchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+
+import { parseAIFilterValue } from "./parse-response";
+
+export type CompletedField = {
+ key: string;
+ value: unknown;
+};
+
+/**
+ * Compares two partial objects from an LLM stream and returns newly completed fields.
+ *
+ * Uses type-aware completeness rules based on the table schema's filter type:
+ * - `input` (string/number): complete when non-null and non-undefined
+ * - `checkbox` (array): complete on first value, updates as more arrive
+ * - `slider` (tuple[2]): complete only when both values are present
+ * - `timerange` (tuple[2]): complete only when both values are present
+ *
+ * Completed values go through `parseAIFilterValue` before they are emitted, so a
+ * progressive update can never apply a value the final reconciliation would
+ * reject (an unknown checkbox option, a reversed slider, an unparseable date).
+ * The returned value is the coerced one — Date objects for timeranges, clamped
+ * bounds for sliders — not the raw stream value.
+ *
+ * @param prev - Previous partial state from the stream (or `{}` for first chunk)
+ * @param next - Current partial state from the stream
+ * @param schema - Table schema definition for type-aware completeness checks
+ * @returns Array of newly completed or updated fields ready for `adapter.setField()`
+ */
+export function diffPartialState(
+ prev: Record<string, unknown>,
+ next: Record<string, unknown>,
+ schema: TableSchemaDefinition,
+): CompletedField[] {
+ const completed: CompletedField[] = [];
+
+ for (const [key, builder] of Object.entries(schema)) {
+ const config = resolveColumn(builder);
+ if (!config.filter) continue;
+
+ const nextVal = next[key];
+ const prevVal = prev[key];
+
+ // Skip if the field hasn't appeared yet
+ if (nextVal === undefined || nextVal === null) continue;
+
+ let changed = false;
+
+ switch (config.filter.type) {
+ case "input": {
+ // Complete when non-null. Emit only if changed.
+ changed = nextVal !== prevVal;
+ break;
+ }
+
+ case "checkbox": {
+ // Array — complete on first value, update as more arrive
+ if (!Array.isArray(nextVal)) break;
+ if (nextVal.length === 0) break;
+
+ const prevArr = Array.isArray(prevVal) ? prevVal : [];
+ changed =
+ nextVal.length !== prevArr.length ||
+ nextVal.some((v, i) => v !== prevArr[i]);
+ break;
+ }
+
+ case "slider": {
+ // Tuple[2] — wait for both values
+ if (!Array.isArray(nextVal)) break;
+ if (nextVal.length < 2) break;
+ if (typeof nextVal[0] !== "number" || typeof nextVal[1] !== "number")
+ break;
+
+ const prevArr = Array.isArray(prevVal) ? prevVal : [];
+ changed = nextVal[0] !== prevArr[0] || nextVal[1] !== prevArr[1];
+ break;
+ }
+
+ case "timerange": {
+ // Tuple[2] — wait for both date strings
+ if (!Array.isArray(nextVal)) break;
+ if (nextVal.length < 2) break;
+ if (typeof nextVal[0] !== "string" || typeof nextVal[1] !== "string")
+ break;
+
+ const prevArr = Array.isArray(prevVal) ? prevVal : [];
+ changed = nextVal[0] !== prevArr[0] || nextVal[1] !== prevArr[1];
+ break;
+ }
+ }
+
+ if (!changed) continue;
+
+ const parsed = parseAIFilterValue(config, nextVal);
+ if (parsed.ok) completed.push({ key, value: parsed.value });
+ }
+
+ return completed;
+}
diff --git a/packages/ui/src/lib/data-table-filters/ai/index.ts b/packages/ui/src/lib/data-table-filters/ai/index.ts
new file mode 100644
index 000000000..a4c6eccc7
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/ai/index.ts
@@ -0,0 +1,14 @@
+export {
+ generateAIContext,
+ type AIContext,
+ type AIFieldContext,
+} from "./context";
+export { generateAIPrompt, type GenerateAIPromptOptions } from "./prompt";
+export { generateAIOutputSchema } from "./output-schema";
+export { diffPartialState, type CompletedField } from "./diff-partial";
+export {
+ parseAIFilterValue,
+ parseAIResponse,
+ type ParsedFilterValue,
+} from "./parse-response";
+export { isStructuredQuery } from "./detect";
diff --git a/packages/ui/src/lib/data-table-filters/ai/output-schema.ts b/packages/ui/src/lib/data-table-filters/ai/output-schema.ts
new file mode 100644
index 000000000..f20fb8465
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/ai/output-schema.ts
@@ -0,0 +1,116 @@
+import {
+ resolveColumn,
+ type ResolvedColumn,
+ type TableSchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+import { z } from "zod";
+
+/**
+ * The values a checkbox column accepts, as strings. Mirrors the derivation in
+ * `generateFilterFields` / `parseAIFilterValue`: without it an enum column that
+ * never spelled out `options` would let the model return arbitrary strings that
+ * are then dropped on validation.
+ */
+function checkboxValues(config: ResolvedColumn): string[] | null {
+ const options = config.filter?.options;
+ if (options && options.length > 0) return options.map((o) => String(o.value));
+ if (config.kind === "enum" && config.enumValues.length > 0) {
+ return [...config.enumValues];
+ }
+ if (
+ config.kind === "array" &&
+ config.arrayItem.kind === "enum" &&
+ config.arrayItem.enumValues.length > 0
+ ) {
+ return [...config.arrayItem.enumValues];
+ }
+ if (config.kind === "boolean") return ["true", "false"];
+ return null;
+}
+
+/**
+ * Generates a Zod schema for LLM structured output from a table schema.
+ *
+ * Each filterable column becomes an optional field in the output schema:
+ * - `input` (string) → `z.string().optional()`
+ * - `input` (number) → `z.number().optional()`
+ * - `checkbox` (enum) → `z.array(z.enum([...values])).optional()`
+ * - `checkbox` (boolean) → `z.array(z.enum(["true", "false"])).optional()`
+ * - `checkbox` (number) → `z.array(z.number()).optional()`
+ * - `slider` → `z.tuple([z.number(), z.number()]).optional()`
+ * - `timerange` → `z.tuple([z.string(), z.string()]).optional()`
+ *
+ * Command-disabled columns are intentionally included so the AI can infer
+ * filters that aren't available in the command palette (e.g. date ranges).
+ */
+export function generateAIOutputSchema(schema: TableSchemaDefinition) {
+ const shape: Record<string, z.ZodType> = {};
+
+ for (const [key, builder] of Object.entries(schema)) {
+ const config = resolveColumn(builder);
+ if (!config.filter) continue;
+
+ const filterType = config.filter.type;
+ const desc = config.description || config.label || key;
+
+ switch (filterType) {
+ case "input": {
+ if (config.kind === "number") {
+ shape[key] = z.number().optional().describe(desc);
+ } else {
+ shape[key] = z.string().optional().describe(desc);
+ }
+ break;
+ }
+
+ case "checkbox": {
+ const values = checkboxValues(config);
+ if (values && values.length >= 2) {
+ shape[key] = z
+ .array(z.enum(values as [string, ...string[]]))
+ .optional()
+ .describe(desc);
+ } else if (values && values.length === 1) {
+ shape[key] = z.array(z.literal(values[0]!)).optional().describe(desc);
+ } else if (config.kind === "number") {
+ shape[key] = z.array(z.number()).optional().describe(desc);
+ } else {
+ shape[key] = z.array(z.string()).optional().describe(desc);
+ }
+ break;
+ }
+
+ case "slider": {
+ const parts = [desc];
+ if (
+ config.filter.min !== undefined ||
+ config.filter.max !== undefined
+ ) {
+ const bounds = [];
+ if (config.filter.min !== undefined)
+ bounds.push(`min: ${config.filter.min}`);
+ if (config.filter.max !== undefined)
+ bounds.push(`max: ${config.filter.max}`);
+ parts.push(`Range: ${bounds.join(", ")}`);
+ }
+ if (config.filter.unit) parts.push(`Unit: ${config.filter.unit}`);
+
+ shape[key] = z
+ .tuple([z.number(), z.number()])
+ .optional()
+ .describe(parts.join(". "));
+ break;
+ }
+
+ case "timerange": {
+ shape[key] = z
+ .tuple([z.string(), z.string()])
+ .optional()
+ .describe(desc + ". ISO 8601 datetime strings [start, end].");
+ break;
+ }
+ }
+ }
+
+ return z.object(shape as z.core.$ZodLooseShape);
+}
diff --git a/packages/ui/src/lib/data-table-filters/ai/parse-response.ts b/packages/ui/src/lib/data-table-filters/ai/parse-response.ts
new file mode 100644
index 000000000..ec75c9abb
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/ai/parse-response.ts
@@ -0,0 +1,147 @@
+import {
+ resolveColumn,
+ type ResolvedColumn,
+ type TableSchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+
+export type ParsedFilterValue = { ok: true; value: unknown } | { ok: false };
+
+const INVALID: ParsedFilterValue = { ok: false };
+
+/**
+ * Allowed checkbox values, keyed by their string form so an LLM string can be
+ * coerced back to the typed value. Falls back to the column's own enum when the
+ * filter carries no explicit options — the same derivation `generateFilterFields`
+ * does, so what the AI may emit matches what the UI can render.
+ */
+function checkboxOptionMap(
+ config: ResolvedColumn,
+): Map<string, unknown> | null {
+ const options = config.filter?.options;
+ if (options && options.length > 0) {
+ return new Map(options.map((o) => [String(o.value), o.value]));
+ }
+ if (config.kind === "enum" && config.enumValues.length > 0) {
+ return new Map(config.enumValues.map((v) => [v, v]));
+ }
+ if (
+ config.kind === "array" &&
+ config.arrayItem.kind === "enum" &&
+ config.arrayItem.enumValues.length > 0
+ ) {
+ return new Map(config.arrayItem.enumValues.map((v) => [v, v]));
+ }
+ if (config.kind === "boolean") {
+ return new Map<string, unknown>([
+ ["true", true],
+ ["false", false],
+ ]);
+ }
+ return null;
+}
+
+/**
+ * Validates and coerces a single LLM-produced value for one column.
+ *
+ * The single source of truth for "is this filter value usable?" — used both by
+ * the progressive stream path (`diffPartialState`) and the final reconciliation
+ * (`parseAIResponse`), so a value can never be applied mid-stream and then be
+ * rejected at the end.
+ */
+export function parseAIFilterValue(
+ config: ResolvedColumn,
+ value: unknown,
+): ParsedFilterValue {
+ if (!config.filter) return INVALID;
+ if (value === undefined || value === null) return INVALID;
+
+ switch (config.filter.type) {
+ case "input": {
+ if (config.kind === "number") {
+ if (typeof value !== "number" || !Number.isFinite(value))
+ return INVALID;
+ return { ok: true, value };
+ }
+ if (typeof value !== "string" || value.length === 0) return INVALID;
+ return { ok: true, value };
+ }
+
+ case "checkbox": {
+ if (!Array.isArray(value)) return INVALID;
+ if (value.length === 0) return INVALID;
+
+ const optionMap = checkboxOptionMap(config);
+ if (!optionMap) return { ok: true, value };
+
+ const valid = value
+ .map(String)
+ .filter((v) => optionMap.has(v))
+ .map((v) => optionMap.get(v));
+ if (valid.length === 0) return INVALID;
+ return { ok: true, value: valid };
+ }
+
+ case "slider": {
+ if (!Array.isArray(value)) return INVALID;
+ if (value.length < 2) return INVALID;
+
+ let [min, max] = value as [number, number];
+ if (typeof min !== "number" || typeof max !== "number") return INVALID;
+
+ if (config.filter.min !== undefined)
+ min = Math.max(min, config.filter.min);
+ if (config.filter.max !== undefined)
+ max = Math.min(max, config.filter.max);
+
+ if (min > max) return INVALID;
+ return { ok: true, value: [min, max] };
+ }
+
+ case "timerange": {
+ if (!Array.isArray(value)) return INVALID;
+ if (value.length < 2) return INVALID;
+
+ const [startStr, endStr] = value as [string, string];
+ if (typeof startStr !== "string" || typeof endStr !== "string") {
+ return INVALID;
+ }
+
+ const start = new Date(startStr);
+ const end = new Date(endStr);
+
+ if (isNaN(start.getTime()) || isNaN(end.getTime())) return INVALID;
+ if (start > end) return INVALID;
+ return { ok: true, value: [start, end] };
+ }
+
+ default: {
+ return INVALID;
+ }
+ }
+}
+
+/**
+ * Validates and coerces a complete LLM response into clean filter state.
+ *
+ * - Strips fields not in the schema or not filterable
+ * - Converts ISO date strings to Date objects for timerange fields
+ * - Validates checkbox values against allowed options
+ * - Clamps slider values to min/max bounds
+ * - Returns `null` if the response is empty (no valid filters)
+ */
+export function parseAIResponse(
+ schema: TableSchemaDefinition,
+ response: Record<string, unknown>,
+): Record<string, unknown> | null {
+ const result: Record<string, unknown> = {};
+ let hasFields = false;
+
+ for (const [key, builder] of Object.entries(schema)) {
+ const parsed = parseAIFilterValue(resolveColumn(builder), response[key]);
+ if (!parsed.ok) continue;
+ result[key] = parsed.value;
+ hasFields = true;
+ }
+
+ return hasFields ? result : null;
+}
diff --git a/packages/ui/src/lib/data-table-filters/ai/prompt.ts b/packages/ui/src/lib/data-table-filters/ai/prompt.ts
new file mode 100644
index 000000000..666fe6a52
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/ai/prompt.ts
@@ -0,0 +1,110 @@
+import type { TableSchemaDefinition } from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+
+import {
+ generateAIContext,
+ type AIContext,
+ type AIFieldContext,
+} from "./context";
+
+export type GenerateAIPromptOptions = {
+ /** Current date/time for resolving relative time expressions like "last hour". */
+ now?: Date;
+};
+
+function formatField(field: AIFieldContext): string {
+ const parts: string[] = [];
+ parts.push(`- **${field.key}** (label: "${field.label}")`);
+ parts.push(` Type: ${field.dataType}, Filter: ${field.filterType}`);
+
+ if (field.description) {
+ parts.push(` Description: ${field.description}`);
+ }
+ if (field.allowedValues && field.allowedValues.length > 0) {
+ parts.push(
+ ` Allowed values: ${field.allowedValues.map((v) => `"${v}"`).join(", ")}`,
+ );
+ }
+ if (field.min !== undefined || field.max !== undefined) {
+ const bounds = [];
+ if (field.min !== undefined) bounds.push(`min: ${field.min}`);
+ if (field.max !== undefined) bounds.push(`max: ${field.max}`);
+ parts.push(` Range: ${bounds.join(", ")}`);
+ }
+ if (field.unit) {
+ parts.push(` Unit: ${field.unit}`);
+ }
+
+ return parts.join("\n");
+}
+
+function formatPrompt(
+ context: AIContext,
+ options?: GenerateAIPromptOptions,
+): string {
+ const lines: string[] = [];
+
+ lines.push(
+ "You are a filter assistant for a data table. Given a natural language query, " +
+ "return a JSON object with the appropriate filter values. Only include fields " +
+ "that the user's query references. If the query doesn't match any field, return " +
+ "an empty object {}.",
+ );
+
+ lines.push("");
+ lines.push("## Available filter fields");
+ lines.push("");
+
+ for (const field of context.fields) {
+ lines.push(formatField(field));
+ lines.push("");
+ }
+
+ lines.push("## Output rules");
+ lines.push("");
+ lines.push("- For **input** filters (text search): return a string value.");
+ lines.push(
+ "- For **checkbox** filters (multi-select): return an array of allowed values. Only use values from the allowed values list.",
+ );
+ lines.push(
+ "- For **slider** filters (numeric range): return a [min, max] tuple within the field's bounds.",
+ );
+ lines.push(
+ "- For **timerange** filters (date range): return a [start, end] tuple of ISO 8601 datetime strings.",
+ );
+ lines.push(
+ "- Only include fields relevant to the query. Omit fields the user didn't mention or imply.",
+ );
+ lines.push("- Return valid JSON only. No explanations.");
+ lines.push(
+ '- The user message includes the current date/time. Use it to resolve relative time expressions like "last hour", "yesterday", "past 7 days".',
+ );
+
+ if (options?.now) {
+ lines.push("");
+ lines.push(`## Current date/time`);
+ lines.push("");
+ lines.push(`Now: ${options.now.toISOString()}`);
+ lines.push(
+ 'Use this to resolve relative time expressions like "last hour", "yesterday", "past 7 days".',
+ );
+ }
+
+ return lines.join("\n");
+}
+
+/**
+ * Generates a ready-to-use system prompt string from a table schema.
+ *
+ * The prompt describes all filterable columns and the expected output format
+ * for an LLM to translate natural language queries into structured filter state.
+ *
+ * @param schema - Table schema definition (from `createTableSchema().definition`)
+ * @param options - Optional config. Pass `{ now: new Date() }` to enable relative time resolution.
+ */
+export function generateAIPrompt(
+ schema: TableSchemaDefinition,
+ options?: GenerateAIPromptOptions,
+): string {
+ const context = generateAIContext(schema);
+ return formatPrompt(context, options);
+}
diff --git a/packages/ui/src/lib/data-table-filters/colors.ts b/packages/ui/src/lib/data-table-filters/colors.ts
new file mode 100644
index 000000000..288178342
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/colors.ts
@@ -0,0 +1,28 @@
+export function hexToRgb(hex: string): string {
+ const normalizedHex = hex.trim().replace(/^#/, "");
+
+ let rgbHex: string;
+
+ if (/^[0-9a-fA-F]{3}$/.test(normalizedHex)) {
+ rgbHex = normalizedHex
+ .split("")
+ .map((char) => char + char)
+ .join("");
+ } else if (/^[0-9a-fA-F]{6}$/.test(normalizedHex)) {
+ rgbHex = normalizedHex;
+ } else if (/^[0-9a-fA-F]{8}$/.test(normalizedHex)) {
+ rgbHex = normalizedHex.substring(0, 6);
+ } else {
+ return "0, 0, 0";
+ }
+
+ const r = parseInt(rgbHex.substring(0, 2), 16);
+ const g = parseInt(rgbHex.substring(2, 4), 16);
+ const b = parseInt(rgbHex.substring(4, 6), 16);
+
+ if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {
+ return "0, 0, 0";
+ }
+
+ return `${r}, ${g}, ${b}`;
+}
diff --git a/packages/ui/src/lib/data-table-filters/data-table/faceted.ts b/packages/ui/src/lib/data-table-filters/data-table/faceted.ts
new file mode 100644
index 000000000..26b891efc
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/data-table/faceted.ts
@@ -0,0 +1,60 @@
+import type { RowModel, Table as TTable } from "@tanstack/react-table";
+
+import type { FacetMetadataSchema } from "./types";
+
+/**
+ * Drop-in replacement for TanStack's `getFacetedUniqueValues` that flattens
+ * array column values. The built-in version treats `["a", "b"]` as one unique
+ * value; this version counts each item individually.
+ *
+ * Works for both array and non-array columns.
+ */
+export function getFacetedUniqueValuesFlattened<TData>(): (
+ table: TTable<TData>,
+ columnId: string,
+) => () => Map<unknown, number> {
+ return (table, columnId) => {
+ return () => {
+ const facetedRowModel: RowModel<TData> | undefined = table
+ .getColumn(columnId)
+ ?.getFacetedRowModel();
+ if (!facetedRowModel) return new Map();
+
+ const counts = new Map<unknown, number>();
+ for (const row of facetedRowModel.flatRows) {
+ const value = row.getValue(columnId);
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ counts.set(item, (counts.get(item) ?? 0) + 1);
+ }
+ } else if (value != null) {
+ counts.set(value, (counts.get(value) ?? 0) + 1);
+ }
+ }
+ return counts;
+ };
+ };
+}
+
+export function getFacetedUniqueValues<TData>(
+ facets?: Record<string, FacetMetadataSchema>,
+) {
+ return (_: TTable<TData>, columnId: string): Map<string, number> => {
+ return new Map(
+ facets?.[columnId]?.rows?.map(({ value, total }) => [value, total]) || [],
+ );
+ };
+}
+
+export function getFacetedMinMaxValues<TData>(
+ facets?: Record<string, FacetMetadataSchema>,
+) {
+ return (_: TTable<TData>, columnId: string): [number, number] | undefined => {
+ const min = facets?.[columnId]?.min;
+ const max = facets?.[columnId]?.max;
+ if (typeof min === "number" && typeof max === "number") return [min, max];
+ if (typeof min === "number") return [min, min];
+ if (typeof max === "number") return [max, max];
+ return undefined;
+ };
+}
diff --git a/packages/ui/src/lib/data-table-filters/data-table/types.ts b/packages/ui/src/lib/data-table-filters/data-table/types.ts
new file mode 100644
index 000000000..4a3e2266c
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/data-table/types.ts
@@ -0,0 +1,12 @@
+import { z } from "zod";
+
+export const facetMetadataSchema = z.object({
+ rows: z.array(z.object({ value: z.any(), total: z.number() })),
+ total: z.number(),
+ min: z.number().optional(),
+ max: z.number().optional(),
+});
+
+export type FacetMetadataSchema = z.infer<typeof facetMetadataSchema>;
+
+export type BaseChartSchema = { timestamp: number; [key: string]: number };
diff --git a/packages/ui/src/lib/data-table-filters/delimiters.ts b/packages/ui/src/lib/data-table-filters/delimiters.ts
new file mode 100644
index 000000000..03a1c0708
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/delimiters.ts
@@ -0,0 +1,9 @@
+export const ARRAY_DELIMITER = ",";
+export const SLIDER_DELIMITER = "-";
+export const SPACE_DELIMITER = "_";
+// NOTE: intentionally the same character as SLIDER_DELIMITER. Sliders and
+// timeranges both serialize as `min-max`, and the parser picks the branch from
+// the column's filter type, not the delimiter. Keep these two in sync — changing
+// one without the other silently breaks whichever filter kept the old value.
+export const RANGE_DELIMITER = "-";
+export const SORT_DELIMITER = ".";
diff --git a/packages/ui/src/lib/data-table-filters/filterfns.ts b/packages/ui/src/lib/data-table-filters/filterfns.ts
new file mode 100644
index 000000000..881b2bbe5
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/filterfns.ts
@@ -0,0 +1,27 @@
+import { FilterFn } from "@tanstack/react-table";
+import { isSameDay } from "date-fns";
+
+import { isArrayOfDates } from "./is-array";
+
+export const inDateRange: FilterFn<unknown> = (row, columnId, value) => {
+ const date = new Date(row.getValue(columnId));
+ const [start, end] = value as Date[];
+
+ if (isNaN(date.getTime())) return false;
+
+ // if no end date, check if it's the same day
+ if (!end) return isSameDay(date, start);
+
+ // Inclusive bounds to match server-side filtering
+ return date.getTime() >= start.getTime() && date.getTime() <= end.getTime();
+};
+
+inDateRange.autoRemove = (val: unknown) =>
+ !Array.isArray(val) || !val.length || !isArrayOfDates(val);
+
+export const arrSome: FilterFn<unknown> = (row, columnId, filterValue) => {
+ if (!Array.isArray(filterValue)) return false;
+ return filterValue.some((val) => row.getValue<unknown[]>(columnId) === val);
+};
+
+arrSome.autoRemove = (val: unknown) => !Array.isArray(val) || !val?.length;
diff --git a/packages/ui/src/lib/data-table-filters/filters/evaluate.ts b/packages/ui/src/lib/data-table-filters/filters/evaluate.ts
new file mode 100644
index 000000000..560c27098
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/filters/evaluate.ts
@@ -0,0 +1,102 @@
+import type { FilterOp, Scalar } from "./types";
+
+/**
+ * Read a possibly dotted key off a row.
+ *
+ * Table schema keys are dot-notation (`"timing.dns"`). Rows may store that
+ * either as a literal flat key or as a nested object, so both are tried —
+ * a flat hit wins, since that is the wire shape.
+ */
+export function getValueAtKey(row: unknown, key: string): unknown {
+ if (row === null || typeof row !== "object") return undefined;
+ const flat = (row as Record<string, unknown>)[key];
+ if (flat !== undefined) return flat;
+ if (!key.includes(".")) return undefined;
+ let current: unknown = row;
+ for (const part of key.split(".")) {
+ if (current === null || typeof current !== "object") return undefined;
+ current = (current as Record<string, unknown>)[part];
+ }
+ return current;
+}
+
+function sameScalar(cell: unknown, value: Scalar): boolean {
+ if (cell === value) return true;
+ // The URL layer can only produce strings, so a number column filtered from a
+ // link arrives as one. Compare by string as a last resort rather than by
+ // coercing, which would make `0 == false` true.
+ if (
+ (typeof cell === "number" || typeof cell === "boolean") &&
+ typeof value === "string"
+ ) {
+ return String(cell) === value;
+ }
+ if (typeof cell === "string" && typeof value !== "string") {
+ return cell === String(value);
+ }
+ return false;
+}
+
+function asComparableNumber(cell: unknown): number | null {
+ if (typeof cell === "number") return Number.isNaN(cell) ? null : cell;
+ if (typeof cell === "string" && cell.trim() !== "") {
+ const parsed = Number(cell);
+ return Number.isNaN(parsed) ? null : parsed;
+ }
+ return null;
+}
+
+function asComparableTime(cell: unknown): number | null {
+ if (cell instanceof Date) {
+ return Number.isNaN(cell.getTime()) ? null : cell.getTime();
+ }
+ if (typeof cell === "string" || typeof cell === "number") {
+ const time = new Date(cell).getTime();
+ return Number.isNaN(time) ? null : time;
+ }
+ return null;
+}
+
+/**
+ * Evaluate one canonical op against one cell value.
+ *
+ * Exhaustive over `FilterOp` with no default branch — a seventh op fails to
+ * compile here rather than silently passing every row.
+ */
+export function evaluateOp(op: FilterOp, cell: unknown): boolean {
+ switch (op.op) {
+ case "substring": {
+ if (cell === null || cell === undefined) return false;
+ // Case-insensitive, matching the SQL side's `ilike`.
+ return String(cell).toLowerCase().includes(op.value.toLowerCase());
+ }
+
+ case "equals":
+ return sameScalar(cell, op.value);
+
+ case "oneOf":
+ return op.values.some((value) => sameScalar(cell, value));
+
+ case "overlaps": {
+ // The column is a set. A scalar cell is treated as a one-element set so
+ // a single-value column still matches — this is where the infinite route
+ // used to look only at `row[key][0]`.
+ const cells = Array.isArray(cell) ? cell : [cell];
+ return cells.some((item) =>
+ op.values.some((value) => sameScalar(item, value)),
+ );
+ }
+
+ case "numberRange": {
+ const value = asComparableNumber(cell);
+ return value !== null && value >= op.min && value <= op.max;
+ }
+
+ case "dateRange": {
+ const time = asComparableTime(cell);
+ return (
+ time !== null && time >= op.from.getTime() && time <= op.to.getTime()
+ );
+ }
+ }
+}
diff --git a/packages/ui/src/lib/data-table-filters/filters/index.ts b/packages/ui/src/lib/data-table-filters/filters/index.ts
new file mode 100644
index 000000000..9b9166669
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/filters/index.ts
@@ -0,0 +1,264 @@
+import { resolveColumns } from "../table-schema/col";
+import type {
+ ColumnDescriptor,
+ SchemaJSON,
+ TableSchemaDefinition,
+} from "../table-schema/types";
+import { evaluateOp, getValueAtKey } from "./evaluate";
+import { isActive, normalize } from "./normalize";
+import type { FilterOp, FilterSelection, FilterSpec, Scalar } from "./types";
+
+export { evaluateOp, getValueAtKey } from "./evaluate";
+export { isActive, normalize } from "./normalize";
+export type {
+ ColKind,
+ FilterOp,
+ FilterSelection,
+ FilterSpec,
+ FilterType,
+ Scalar,
+} from "./types";
+
+/**
+ * Where a `Filters` gets its declarations.
+ *
+ * `SchemaJSON` is here so the declaration can cross the `"use client"` boundary
+ * as data: `table-schema.tsx` cannot be imported server-side, but its
+ * `toJSON()` can.
+ */
+export type FilterSource =
+ | TableSchemaDefinition
+ | SchemaJSON
+ | readonly FilterSpec[];
+
+export interface Filters {
+ readonly specs: readonly FilterSpec[];
+
+ /** Look up one column's declaration. */
+ spec(key: string): FilterSpec | undefined;
+
+ /**
+ * Values → canonical ops. Never guesses from the shape of a value.
+ * Inactive and unknown keys are dropped.
+ */
+ plan(
+ values: Record<string, unknown>,
+ selection?: FilterSelection,
+ ): FilterOp[];
+
+ /** In-memory predicate. Replaces `filterData` and `filterGenericData`. */
+ matches(
+ values: Record<string, unknown>,
+ row: unknown,
+ selection?: FilterSelection,
+ ): boolean;
+
+ /** Filter a whole collection. */
+ apply<TRow>(
+ rows: readonly TRow[],
+ values: Record<string, unknown>,
+ selection?: FilterSelection,
+ ): TRow[];
+
+ /**
+ * A TanStack `ColumnDef.filterFn`. Returns a *function*, so nothing has to be
+ * registered on the table via `filterFns: { inDateRange, arrSome }`.
+ */
+ filterFn(
+ key: string,
+ ):
+ | ((
+ row: { getValue: (id: string) => unknown },
+ columnId: string,
+ value: unknown,
+ ) => boolean)
+ | undefined;
+
+ /** Validate and coerce untrusted input (AI structured output, MCP args). */
+ coerce(raw: Record<string, unknown>): Record<string, unknown>;
+}
+
+// ── Deriving specs ──────────────────────────────────────────────────────────
+
+function specFromDescriptor(
+ key: string,
+ column: Pick<ColumnDescriptor, "kind" | "filter"> &
+ Partial<Pick<Extract<ColumnDescriptor, { kind: "array" }>, "arrayItem">>,
+): FilterSpec | null {
+ const { filter } = column;
+ if (!filter) return null;
+
+ const spec: FilterSpec = {
+ key,
+ type: filter.type,
+ kind: column.kind,
+ };
+
+ if (column.kind === "array" && column.arrayItem) {
+ spec.itemKind = column.arrayItem.kind;
+ }
+ if (filter.options) {
+ spec.options = filter.options.map((option) => option.value);
+ }
+ if (filter.min !== undefined) spec.min = filter.min;
+ if (filter.max !== undefined) spec.max = filter.max;
+
+ return spec;
+}
+
+function isSchemaJSON(source: FilterSource): source is SchemaJSON {
+ return (
+ !Array.isArray(source) &&
+ typeof source === "object" &&
+ source !== null &&
+ Array.isArray((source as SchemaJSON).columns)
+ );
+}
+
+function toSpecs(source: FilterSource): FilterSpec[] {
+ if (Array.isArray(source)) {
+ return [...(source as readonly FilterSpec[])];
+ }
+
+ if (isSchemaJSON(source)) {
+ const specs: FilterSpec[] = [];
+ for (const column of source.columns) {
+ const spec = specFromDescriptor(column.key, column);
+ if (spec) specs.push(spec);
+ }
+ return specs;
+ }
+
+ const specs: FilterSpec[] = [];
+ for (const column of resolveColumns(source as TableSchemaDefinition)) {
+ const spec = specFromDescriptor(column.key, column);
+ if (spec) specs.push(spec);
+ }
+ return specs;
+}
+
+function isSelected(key: string, selection?: FilterSelection): boolean {
+ if (selection?.exclude?.includes(key)) return false;
+ if (selection?.only && !selection.only.includes(key)) return false;
+ return true;
+}
+
+// ── Coercion ────────────────────────────────────────────────────────────────
+
+function coerceValue(spec: FilterSpec, raw: unknown): unknown {
+ // Round-tripping through `normalize` is the coercion: if the declared
+ // semantics cannot make an op out of it, it is not a usable filter value.
+ const op = normalize(spec, raw);
+ if (!op) return undefined;
+
+ switch (op.op) {
+ case "substring":
+ return op.value;
+ case "equals":
+ return op.value;
+ case "oneOf":
+ case "overlaps": {
+ // Drop values outside the declared option set — an LLM will happily
+ // invent an enum member that does not exist.
+ if (!spec.options) return op.values;
+ const allowed = op.values.filter((value) =>
+ spec.options!.some((option) => String(option) === String(value)),
+ );
+ return allowed.length > 0 ? allowed : undefined;
+ }
+ case "numberRange": {
+ // Clamp to the declared bounds. `coerce` is the untrusted-input entry
+ // point, and an LLM asked for "slow requests" will happily produce
+ // `[0, 99999]` against a slider declared `{ min: 0, max: 5000 }`.
+ const lower = spec.min ?? -Infinity;
+ const upper = spec.max ?? Infinity;
+ const min = Math.min(Math.max(op.min, lower), upper);
+ const max = Math.min(Math.max(op.max, lower), upper);
+ return [min, max];
+ }
+ case "dateRange":
+ return [op.from, op.to];
+ }
+}
+
+// ── Entry point ─────────────────────────────────────────────────────────────
+
+/**
+ * Build the one interpretation of a table's filter semantics.
+ *
+ * Every engine — SQL, in-memory, TanStack — goes through this, so a column's
+ * declared `(FilterType, ColKind)` pair is honoured identically everywhere
+ * instead of being re-derived from whatever the value happened to look like at
+ * runtime.
+ */
+export function defineFilters(source: FilterSource): Filters {
+ const specs = toSpecs(source);
+ const byKey = new Map(specs.map((spec) => [spec.key, spec]));
+
+ const plan = (
+ values: Record<string, unknown>,
+ selection?: FilterSelection,
+ ): FilterOp[] => {
+ const ops: FilterOp[] = [];
+ for (const [key, value] of Object.entries(values)) {
+ if (!isSelected(key, selection)) continue;
+ const spec = byKey.get(key);
+ if (!spec) continue;
+ const op = normalize(spec, value);
+ if (op) ops.push(op);
+ }
+ return ops;
+ };
+
+ const matches = (
+ values: Record<string, unknown>,
+ row: unknown,
+ selection?: FilterSelection,
+ ): boolean =>
+ plan(values, selection).every((op) =>
+ evaluateOp(op, getValueAtKey(row, op.key)),
+ );
+
+ return {
+ specs,
+
+ spec: (key) => byKey.get(key),
+
+ plan,
+
+ matches,
+
+ apply: (rows, values, selection) => {
+ const ops = plan(values, selection);
+ if (ops.length === 0) return [...rows];
+ return rows.filter((row) =>
+ ops.every((op) => evaluateOp(op, getValueAtKey(row, op.key))),
+ );
+ },
+
+ filterFn: (key) => {
+ const spec = byKey.get(key);
+ if (!spec) return undefined;
+ return (row, columnId, value) => {
+ const op = normalize(spec, value);
+ // An inactive filter matches everything, which is what TanStack expects
+ // when a column filter is present but empty.
+ if (!op) return true;
+ return evaluateOp(op, row.getValue(columnId));
+ };
+ },
+
+ coerce: (raw) => {
+ const result: Record<string, unknown> = {};
+ for (const spec of specs) {
+ const value = raw[spec.key];
+ if (!isActive(value)) continue;
+ const coerced = coerceValue(spec, value);
+ if (coerced !== undefined) result[spec.key] = coerced;
+ }
+ return result;
+ },
+ };
+}
+
+export type { Scalar as FilterScalar };
diff --git a/packages/ui/src/lib/data-table-filters/filters/normalize.ts b/packages/ui/src/lib/data-table-filters/filters/normalize.ts
new file mode 100644
index 000000000..1189e0d28
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/filters/normalize.ts
@@ -0,0 +1,203 @@
+import type { ColKind, FilterOp, FilterSpec, Scalar } from "./types";
+
+/** Unix ms timestamps are 13-digit numbers (> Sep 2001, < Nov 2286). */
+const UNIX_MS_MIN = 1_000_000_000_000;
+
+/**
+ * Is this filter value active?
+ *
+ * Inactive means "the user has not filtered on this column": absent, cleared,
+ * an empty multi-select, or a value that cannot be compared at all. This was
+ * written four slightly different ways across four engines.
+ */
+export function isActive(value: unknown): boolean {
+ if (value === null || value === undefined) return false;
+ if (typeof value === "string") return value.length > 0;
+ if (typeof value === "number") return !Number.isNaN(value);
+ if (value instanceof Date) return !Number.isNaN(value.getTime());
+ if (Array.isArray(value)) {
+ // ANY usable member makes the filter active. `normalize` drops the members
+ // it cannot use, so requiring all of them to be usable would make one blank
+ // entry silently delete the whole filter — and inconsistently, since
+ // `["abc", 500]` on a slider degenerates to 500 while `["", 500]` vanished.
+ return value.some(isActive);
+ }
+ return true;
+}
+
+/** Coerce to a `Date`, or `null` if it cannot be one. */
+function asDate(value: unknown): Date | null {
+ if (value instanceof Date) {
+ return Number.isNaN(value.getTime()) ? null : value;
+ }
+ // superjson revives Dates, but MCP args and LLM output arrive as ISO strings
+ // or epoch millis.
+ if (typeof value === "string" || typeof value === "number") {
+ // Epoch millis that arrived as a string: `new Date("1700000000000")` is an
+ // Invalid Date while `new Date(1700000000000)` is not. The command palette
+ // serializes timeranges with `getTime()`, and JSON has no Date type, so
+ // this shape is common. The magnitude test disambiguates it from a bare
+ // year like "2024", which `Date` should keep parsing as a year.
+ if (typeof value === "string" && /^\d+$/.test(value)) {
+ const millis = Number(value);
+ if (millis >= UNIX_MS_MIN) {
+ const date = new Date(millis);
+ return Number.isNaN(date.getTime()) ? null : date;
+ }
+ }
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? null : date;
+ }
+ return null;
+}
+
+function asNumber(value: unknown): number | null {
+ if (typeof value === "number") return Number.isNaN(value) ? null : value;
+ if (typeof value === "string" && value.trim() !== "") {
+ const parsed = Number(value);
+ return Number.isNaN(parsed) ? null : parsed;
+ }
+ return null;
+}
+
+function asScalar(value: unknown): Scalar | null {
+ if (
+ typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean"
+ ) {
+ return value;
+ }
+ return null;
+}
+
+function asArray(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [value];
+}
+
+function asBoolean(value: unknown): boolean | null {
+ if (typeof value === "boolean") return value;
+ if (value === "true") return true;
+ if (value === "false") return false;
+ return null;
+}
+
+/**
+ * Coerce one checkbox member to the column's declared type.
+ *
+ * The URL layer, MCP args, and LLM output all deliver `["200", "500"]` for a
+ * numeric column. Without this, the SQL backend received
+ * `inArray(integerColumn, ["200", "500"])` and depended on Postgres casting the
+ * literals, and `coerce()` — the entry point documented as producing validated
+ * values — handed back strings for a number column.
+ */
+function asDeclaredScalar(kind: ColKind, value: unknown): Scalar | null {
+ switch (kind) {
+ case "number":
+ return asNumber(value);
+ case "boolean":
+ return asBoolean(value);
+ default: {
+ const scalar = asScalar(value);
+ return scalar === null ? null : String(scalar);
+ }
+ }
+}
+
+function startOfDay(date: Date): Date {
+ const result = new Date(date);
+ result.setHours(0, 0, 0, 0);
+ return result;
+}
+
+function endOfDay(date: Date): Date {
+ const result = new Date(date);
+ result.setHours(23, 59, 59, 999);
+ return result;
+}
+
+/**
+ * Turn one declared filter and its value into a canonical op.
+ *
+ * This is the whole design. Dispatch is on the **declared** `(type, kind)`
+ * pair — never on the runtime shape of `value`. A numeric checkbox is
+ * `{ type: "checkbox", kind: "number" }`, so `[200, 500]` can only become
+ * `oneOf`; `numberRange` is unreachable from a checkbox and
+ * `BETWEEN 200 AND 500` is therefore unrepresentable. Backends never see array
+ * length, so length-based dispatch has nowhere to live.
+ *
+ * Returns `null` when the filter is inactive or the value cannot be coerced
+ * into the declared shape.
+ */
+export function normalize(spec: FilterSpec, value: unknown): FilterOp | null {
+ if (!isActive(value)) return null;
+ const { key } = spec;
+
+ switch (spec.type) {
+ case "input": {
+ // A number column's text box is an exact match, not a substring search —
+ // substring matching on a stringified number makes "5" match 1500.
+ if (spec.kind === "number") {
+ const parsed = asNumber(Array.isArray(value) ? value[0] : value);
+ return parsed === null ? null : { op: "equals", key, value: parsed };
+ }
+ const raw = Array.isArray(value) ? value[0] : value;
+ const text = asScalar(raw);
+ return text === null
+ ? null
+ : { op: "substring", key, value: String(text) };
+ }
+
+ case "checkbox": {
+ // For an array column the members are compared against the *item* type.
+ const memberKind =
+ spec.kind === "array" ? (spec.itemKind ?? "string") : spec.kind;
+ const values = asArray(value)
+ .map((member) => asDeclaredScalar(memberKind, member))
+ .filter((v): v is Scalar => v !== null);
+ if (values.length === 0) return null;
+ // An array column is a set on both sides — overlap, not membership.
+ return spec.kind === "array"
+ ? { op: "overlaps", key, values }
+ : { op: "oneOf", key, values };
+ }
+
+ case "slider": {
+ const numbers = asArray(value)
+ .map(asNumber)
+ .filter((v): v is number => v !== null);
+ if (numbers.length === 0) return null;
+ // A single-handle slider is a degenerate range, not an equality — the
+ // two disagree once the column holds non-integers.
+ const [first, second] = numbers;
+ const min = first!;
+ const max = second ?? first!;
+ return {
+ op: "numberRange",
+ key,
+ min: Math.min(min, max),
+ max: Math.max(min, max),
+ };
+ }
+
+ case "timerange": {
+ const dates = asArray(value)
+ .map(asDate)
+ .filter((v): v is Date => v !== null);
+ if (dates.length === 0) return null;
+ // One date means "that whole day".
+ if (dates.length === 1) {
+ return {
+ op: "dateRange",
+ key,
+ from: startOfDay(dates[0]!),
+ to: endOfDay(dates[0]!),
+ };
+ }
+ const [from, to] = dates;
+ return from!.getTime() <= to!.getTime()
+ ? { op: "dateRange", key, from: from!, to: to! }
+ : { op: "dateRange", key, from: to!, to: from! };
+ }
+ }
+}
diff --git a/packages/ui/src/lib/data-table-filters/filters/types.ts b/packages/ui/src/lib/data-table-filters/filters/types.ts
new file mode 100644
index 000000000..ca4db59b5
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/filters/types.ts
@@ -0,0 +1,52 @@
+import type { ColKind, FilterType } from "../table-schema/types";
+
+export type { ColKind, FilterType };
+
+/** A value a filter can compare against. */
+export type Scalar = string | number | boolean;
+
+/**
+ * A column's declared filter semantics, flattened to plain data.
+ *
+ * This is the whole input to the normalization table. Backends never see
+ * anything else about a column, which is what stops them re-deriving semantics
+ * from the runtime shape of a value.
+ */
+export type FilterSpec = {
+ /** Dot-notation — the ONE identity space, matching the table schema key. */
+ key: string;
+ type: FilterType;
+ kind: ColKind;
+ /** Present when `kind === "array"`. */
+ itemKind?: ColKind;
+ options?: readonly Scalar[];
+ min?: number;
+ max?: number;
+};
+
+/**
+ * The canonical, backend-neutral operation set.
+ *
+ * CLOSED union — exactly six members. Every backend implements all six with an
+ * exhaustive switch and no default branch, so adding a seventh is a compile
+ * error at every backend rather than a silent fallthrough. That is the point of
+ * the design, not a defect: a new op is a breaking change to every engine.
+ */
+export type FilterOp =
+ /** Case-insensitive substring match. */
+ | { op: "substring"; key: string; value: string }
+ | { op: "equals"; key: string; value: Scalar }
+ /** Scalar column, value ∈ set. */
+ | { op: "oneOf"; key: string; values: Scalar[] }
+ /** Array column, column ∩ set ≠ ∅. */
+ | { op: "overlaps"; key: string; values: Scalar[] }
+ /** Inclusive on both ends. */
+ | { op: "numberRange"; key: string; min: number; max: number }
+ /** Inclusive on both ends. */
+ | { op: "dateRange"; key: string; from: Date; to: Date };
+
+/** Restrict which keys `plan` / `matches` consider. */
+export type FilterSelection = {
+ only?: readonly string[];
+ exclude?: readonly string[];
+};
diff --git a/packages/ui/src/lib/data-table-filters/hooks/use-ai-filters.ts b/packages/ui/src/lib/data-table-filters/hooks/use-ai-filters.ts
new file mode 100644
index 000000000..d55aeaaec
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/hooks/use-ai-filters.ts
@@ -0,0 +1,109 @@
+import { experimental_useObject as useObject } from "@ai-sdk/react";
+import {
+ diffPartialState,
+ generateAIOutputSchema,
+ isStructuredQuery,
+ parseAIResponse,
+} from "@openstatus/ui/lib/data-table-filters/ai/index";
+import {
+ serializeSchema,
+ type TableSchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+
+export type UseAIFiltersOptions = {
+ /** The API endpoint that streams AI filter results */
+ api: string;
+ /** Table schema definition for generating the output schema and detecting structured queries */
+ tableSchema: TableSchemaDefinition;
+ /** Called for each progressively completed field */
+ onField: (key: string, value: unknown) => void;
+ /**
+ * Called with the final validated state on stream end. Fields absent from the
+ * state did not survive validation and must be cleared by the consumer.
+ */
+ onFinish: (state: Record<string, unknown>) => void;
+ /** Called when the AI call fails */
+ onError?: (error: Error) => void;
+ /** Called before AI filters are applied — use to reset existing filters */
+ onStart?: () => void;
+ /** Called when the stream ends, regardless of validation success — use for cleanup */
+ onComplete?: () => void;
+};
+
+export function useAIFilters({
+ api,
+ tableSchema,
+ onField,
+ onFinish,
+ onError,
+ onStart,
+ onComplete,
+}: UseAIFiltersOptions) {
+ const prevRef = useRef<Record<string, unknown>>({});
+ const outputSchema = useMemo(
+ () => generateAIOutputSchema(tableSchema),
+ [tableSchema],
+ );
+ // Sent with the request so the server builds its prompt and output schema from
+ // the very schema this table filters on, not a generic stand-in.
+ const serializedSchema = useMemo(
+ () => serializeSchema(tableSchema),
+ [tableSchema],
+ );
+
+ const { submit, object, isLoading, error } = useObject({
+ api,
+ schema: outputSchema,
+ onFinish({ object, error }) {
+ prevRef.current = {};
+ // The final object failing the output schema is a failed request, not an
+ // empty result — leave the table to the error path so it can be restored.
+ if (error) {
+ onComplete?.();
+ onError?.(error);
+ return;
+ }
+ // Always reconcile, even with nothing valid: progressive updates already
+ // touched the table and the consumer has to clear what did not survive.
+ onFinish(
+ parseAIResponse(
+ tableSchema,
+ (object ?? {}) as Record<string, unknown>,
+ ) ?? {},
+ );
+ onComplete?.();
+ },
+ onError(error) {
+ onComplete?.();
+ onError?.(error);
+ },
+ });
+
+ // Progressive application via diffPartialState
+ useEffect(() => {
+ if (!object) return;
+ const next = object as Record<string, unknown>;
+ const completed = diffPartialState(prevRef.current, next, tableSchema);
+ for (const { key, value } of completed) {
+ onField(key, value);
+ }
+ prevRef.current = { ...next };
+ }, [object]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const infer = useCallback(
+ (query: string): boolean => {
+ if (isStructuredQuery(query, tableSchema)) return false;
+ const trimmed = query.trim();
+ if (!trimmed) return false;
+
+ onStart?.();
+ prevRef.current = {};
+ submit({ query: trimmed, schema: serializedSchema });
+ return true;
+ },
+ [submit, tableSchema, onStart, serializedSchema],
+ );
+
+ return { infer, isLoading, error };
+}
diff --git a/packages/ui/src/lib/data-table-filters/is-array.ts b/packages/ui/src/lib/data-table-filters/is-array.ts
new file mode 100644
index 000000000..9662b9d83
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/is-array.ts
@@ -0,0 +1,19 @@
+export function isArrayOfNumbers(arr: unknown): arr is number[] {
+ if (!Array.isArray(arr)) return false;
+ return arr.every((item) => typeof item === "number");
+}
+
+export function isArrayOfDates(arr: unknown): arr is Date[] {
+ if (!Array.isArray(arr)) return false;
+ return arr.every((item) => item instanceof Date);
+}
+
+export function isArrayOfStrings(arr: unknown): arr is string[] {
+ if (!Array.isArray(arr)) return false;
+ return arr.every((item) => typeof item === "string");
+}
+
+export function isArrayOfBooleans(arr: unknown): arr is boolean[] {
+ if (!Array.isArray(arr)) return false;
+ return arr.every((item) => typeof item === "boolean");
+}
diff --git a/packages/ui/src/lib/data-table-filters/local-storage.ts b/packages/ui/src/lib/data-table-filters/local-storage.ts
new file mode 100644
index 000000000..7651f7f70
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/local-storage.ts
@@ -0,0 +1,13 @@
+export const getColumnVisibilityKey = (tableId: string) =>
+ `data-table-visibility-${tableId}`;
+
+// Column order state per table
+export const getColumnOrderKey = (tableId: string) =>
+ `data-table-column-order-${tableId}`;
+
+// Filter command search history per table
+export const getCommandHistoryKey = (tableId: string) =>
+ `data-table-command-${tableId}`;
+
+// Controls panel open/close state (global)
+export const CONTROLS_KEY = "data-table-controls";
diff --git a/packages/ui/src/lib/data-table-filters/status-code.ts b/packages/ui/src/lib/data-table-filters/status-code.ts
new file mode 100644
index 000000000..be2e2b9cd
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/status-code.ts
@@ -0,0 +1,48 @@
+export function getStatusColor(
+ value: number,
+): Record<"text" | "bg" | "border", string> {
+ if (value < 100 || value >= 600)
+ return {
+ text: "text-gray-500",
+ bg: "bg-gray-100 dark:bg-gray-900/50",
+ border: "border-gray-200 dark:border-gray-800",
+ };
+ switch (value.toString().charAt(0)) {
+ case "1":
+ return {
+ text: "text-blue-500",
+ bg: "bg-blue-100 dark:bg-blue-900/50",
+ border: "border-blue-200 dark:border-blue-800",
+ };
+ case "2":
+ return {
+ text: "text-green-500",
+ bg: "bg-green-100 dark:bg-green-900/50",
+ border: "border-green-200 dark:border-green-800",
+ };
+ case "3":
+ return {
+ text: "text-yellow-500",
+ bg: "bg-yellow-100 dark:bg-yellow-900/50",
+ border: "border-yellow-200 dark:border-yellow-800",
+ };
+ case "4":
+ return {
+ text: "text-orange-500",
+ bg: "bg-orange-100 dark:bg-orange-900/50",
+ border: "border-orange-200 dark:border-orange-800",
+ };
+ case "5":
+ return {
+ text: "text-red-500",
+ bg: "bg-red-100 dark:bg-red-900/50",
+ border: "border-red-200 dark:border-red-800",
+ };
+ default:
+ return {
+ text: "text-gray-500",
+ bg: "bg-gray-100 dark:bg-gray-900/50",
+ border: "border-gray-200 dark:border-gray-800",
+ };
+ }
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/adapter/types.ts b/packages/ui/src/lib/data-table-filters/store/adapter/types.ts
new file mode 100644
index 000000000..d1666f6dc
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/adapter/types.ts
@@ -0,0 +1,145 @@
+import type { SchemaDefinition, StoreSnapshot } from "../schema/types";
+
+/**
+ * Store adapter interface that all adapters must implement
+ */
+export interface StoreAdapter<T extends Record<string, unknown>> {
+ /**
+ * Subscribe to state changes.
+ * Compatible with useSyncExternalStore's subscribe parameter.
+ *
+ * @param listener - Callback to invoke when state changes
+ * @returns Unsubscribe function
+ */
+ subscribe(listener: () => void): () => void;
+
+ /**
+ * Get the current state snapshot.
+ * Compatible with useSyncExternalStore's getSnapshot parameter.
+ *
+ * @returns Current state snapshot with version
+ */
+ getSnapshot(): StoreSnapshot<T>;
+
+ /**
+ * Get the server-side state snapshot (for SSR).
+ * Only implemented by URL-based adapters.
+ *
+ * @returns Server state snapshot
+ */
+ getServerSnapshot?(): StoreSnapshot<T>;
+
+ /**
+ * Update state with partial values.
+ * Must use immutable updates (new references for changed values).
+ *
+ * @param partial - Partial state to merge
+ */
+ setState(partial: Partial<T>): void;
+
+ /**
+ * Update a single field value.
+ *
+ * @param key - Field key
+ * @param value - New value
+ */
+ setField<K extends keyof T>(key: K, value: T[K]): void;
+
+ /**
+ * Reset state to defaults.
+ *
+ * @param fields - Optional array of fields to reset. If omitted, resets all.
+ */
+ reset(fields?: (keyof T)[]): void;
+
+ /**
+ * Pause state updates (for live mode).
+ * While paused, setState calls are queued.
+ */
+ pause(): void;
+
+ /**
+ * Resume state updates.
+ * Applies any queued state changes.
+ */
+ resume(): void;
+
+ /**
+ * Check if updates are paused.
+ */
+ isPaused(): boolean;
+
+ /**
+ * Cleanup resources when adapter is destroyed.
+ */
+ destroy(): void;
+
+ /**
+ * Get the unique table ID for this adapter.
+ */
+ getTableId(): string;
+
+ /**
+ * Get the schema definition used by this adapter.
+ */
+ getSchema(): SchemaDefinition;
+
+ /**
+ * Get the default values from the schema.
+ */
+ getDefaults(): T;
+}
+
+/**
+ * Options for creating an adapter
+ */
+export interface CreateAdapterOptions<T extends Record<string, unknown>> {
+ /**
+ * Unique ID for this table (required for multi-table support)
+ */
+ id: string;
+
+ /**
+ * Initial state to override defaults
+ */
+ initialState?: Partial<T>;
+}
+
+/**
+ * Factory function type for creating adapters
+ */
+export type AdapterFactory<T extends Record<string, unknown>> = (
+ schema: SchemaDefinition,
+ options: CreateAdapterOptions<T>,
+) => StoreAdapter<T>;
+
+/**
+ * Available adapter types
+ */
+export type AdapterType = "nuqs" | "zustand";
+
+/**
+ * Internal adapter with additional methods for providers
+ * @internal
+ */
+export interface InternalStoreAdapter<
+ T extends Record<string, unknown>,
+> extends StoreAdapter<T> {
+ /**
+ * Internal method to sync external state (used by nuqs adapter)
+ * @internal
+ */
+ _syncState?(state: T): void;
+
+ /**
+ * Internal method to get the state setter (used by nuqs adapter)
+ * @internal
+ */
+ _getStateSetter?(): ((partial: Partial<T>) => void) | null;
+
+ /**
+ * Internal method to set the state setter (used by nuqs adapter)
+ * @internal
+ */
+ _setStateSetter?(setter: (partial: Partial<T>) => void): void;
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/adapters/memory/index.ts b/packages/ui/src/lib/data-table-filters/store/adapters/memory/index.ts
new file mode 100644
index 000000000..63e9f039d
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/adapters/memory/index.ts
@@ -0,0 +1,120 @@
+"use client";
+
+import { useCallback, useMemo, useRef } from "react";
+
+import type { InternalStoreAdapter } from "../../adapter/types";
+import { getSchemaDefaults } from "../../schema/serialization";
+import type { SchemaDefinition, StoreSnapshot } from "../../schema/types";
+
+export function useMemoryAdapter<T extends Record<string, unknown>>(
+ schema: SchemaDefinition,
+ options?: { id?: string },
+): InternalStoreAdapter<T> {
+ const defaults = useMemo(() => getSchemaDefaults(schema) as T, [schema]);
+
+ const stateRef = useRef<T>({ ...defaults });
+ const versionRef = useRef(0);
+ const listenersRef = useRef(new Set<() => void>());
+ const pausedRef = useRef(false);
+ const pendingRef = useRef<Partial<T> | null>(null);
+
+ // Cached so getServerSnapshot() is referentially stable for useSyncExternalStore
+ const serverSnapshotRef = useRef<StoreSnapshot<T>>({
+ state: { ...defaults } as T,
+ version: 0,
+ });
+
+ const notify = useCallback(() => {
+ for (const listener of listenersRef.current) {
+ listener();
+ }
+ }, []);
+
+ const adapter = useMemo<InternalStoreAdapter<T>>(() => {
+ return {
+ subscribe(listener: () => void) {
+ listenersRef.current.add(listener);
+ return () => {
+ listenersRef.current.delete(listener);
+ };
+ },
+
+ getSnapshot(): StoreSnapshot<T> {
+ return {
+ state: stateRef.current,
+ version: versionRef.current,
+ };
+ },
+
+ getServerSnapshot(): StoreSnapshot<T> {
+ return serverSnapshotRef.current;
+ },
+
+ setState(partial: Partial<T>) {
+ if (pausedRef.current) {
+ pendingRef.current = {
+ ...pendingRef.current,
+ ...partial,
+ } as Partial<T>;
+ return;
+ }
+
+ stateRef.current = { ...stateRef.current, ...partial };
+ versionRef.current++;
+ notify();
+ },
+
+ setField<K extends keyof T>(key: K, value: T[K]) {
+ this.setState({ [key]: value } as unknown as Partial<T>);
+ },
+
+ reset(fields?: (keyof T)[]) {
+ if (fields) {
+ const resetPartial: Partial<T> = {};
+ for (const field of fields) {
+ resetPartial[field] = defaults[field];
+ }
+ this.setState(resetPartial);
+ } else {
+ // Through setState so a reset while paused is queued like any update
+ this.setState({ ...defaults });
+ }
+ },
+
+ pause() {
+ pausedRef.current = true;
+ },
+
+ resume() {
+ pausedRef.current = false;
+ if (pendingRef.current) {
+ const pending = pendingRef.current;
+ pendingRef.current = null;
+ this.setState(pending);
+ }
+ },
+
+ isPaused() {
+ return pausedRef.current;
+ },
+
+ destroy() {
+ listenersRef.current.clear();
+ },
+
+ getTableId() {
+ return options?.id ?? "memory";
+ },
+
+ getSchema() {
+ return schema;
+ },
+
+ getDefaults() {
+ return defaults;
+ },
+ };
+ }, [schema, defaults, notify]);
+
+ return adapter;
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/index.ts b/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/index.ts
new file mode 100644
index 000000000..9526fcf5e
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/index.ts
@@ -0,0 +1,203 @@
+"use client";
+
+import { useQueryStates, type ParserBuilder } from "nuqs";
+import { useEffect, useMemo, useRef } from "react";
+
+import type { InternalStoreAdapter } from "../../adapter/types";
+import { getSchemaDefaults, validateState } from "../../schema/serialization";
+import type { SchemaDefinition, StoreSnapshot } from "../../schema/types";
+import { schemaToNuqsParsers } from "./parser-bridge";
+import type { NuqsAdapterOptions } from "./types";
+
+export type { NuqsAdapterOptions } from "./types";
+
+/**
+ * Create a nuqs adapter for URL-based state management
+ *
+ * @example
+ * ```typescript
+ * const schema = createSchema({
+ * regions: field.array(field.string()).default([]),
+ * host: field.string(),
+ * });
+ *
+ * function MyComponent() {
+ * const adapter = useNuqsAdapter(schema.definition, { id: 'my-table' });
+ * return (
+ * <DataTableStoreProvider adapter={adapter}>
+ * <DataTable />
+ * </DataTableStoreProvider>
+ * );
+ * }
+ * ```
+ */
+export function useNuqsAdapter<T extends Record<string, unknown>>(
+ schema: SchemaDefinition,
+ options: NuqsAdapterOptions<T>,
+): InternalStoreAdapter<T> {
+ const {
+ id,
+ initialState,
+ shallow = true,
+ history = "push",
+ scroll = false,
+ throttleMs = 50,
+ } = options;
+
+ const parsers = useMemo(() => schemaToNuqsParsers(schema), [schema]);
+ const defaults = useMemo(() => getSchemaDefaults(schema) as T, [schema]);
+
+ // Use nuqs hook
+ const [nuqsState, setNuqsState] = useQueryStates(
+ parsers as Record<string, ParserBuilder<unknown>>,
+ {
+ shallow,
+ history,
+ scroll,
+ throttleMs,
+ },
+ );
+
+ // Store state and version
+ const stateRef = useRef<T>(defaults);
+ const versionRef = useRef(0);
+ const listenersRef = useRef(new Set<() => void>());
+ const pausedRef = useRef(false);
+ const pendingStateRef = useRef<Partial<T> | null>(null);
+
+ // Cache server snapshot to avoid infinite loop with useSyncExternalStore
+ const serverSnapshotRef = useRef<StoreSnapshot<T>>({
+ state: { ...defaults, ...initialState } as T,
+ version: 0,
+ });
+
+ // Compute merged state once per render so validateState isn't called twice
+ const currentState = useMemo(() => {
+ // nuqs yields null for params absent from the URL, and validateState turns
+ // those into schema defaults — fall back to initialState for them instead
+ const source: Record<string, unknown> = { ...nuqsState };
+ if (initialState) {
+ for (const [key, value] of Object.entries(initialState)) {
+ if (value !== undefined && source[key] == null) source[key] = value;
+ }
+ }
+ const validated = validateState(schema, source) as T;
+ return { ...defaults, ...initialState, ...validated } as T;
+ }, [nuqsState, schema, defaults, initialState]);
+
+ // Sync ref synchronously so getSnapshot() is always current during this render
+ stateRef.current = currentState;
+
+ // Notify listeners when state changes
+ useEffect(() => {
+ stateRef.current = currentState;
+ versionRef.current++;
+ listenersRef.current.forEach((listener) => listener());
+ }, [currentState]);
+
+ // Create stable adapter reference
+ const adapter = useMemo<InternalStoreAdapter<T>>(() => {
+ return {
+ subscribe(listener: () => void) {
+ listenersRef.current.add(listener);
+ return () => {
+ listenersRef.current.delete(listener);
+ };
+ },
+
+ getSnapshot(): StoreSnapshot<T> {
+ return {
+ state: stateRef.current,
+ version: versionRef.current,
+ };
+ },
+
+ getServerSnapshot(): StoreSnapshot<T> {
+ // Return cached snapshot to avoid infinite loop with useSyncExternalStore
+ return serverSnapshotRef.current;
+ },
+
+ setState(partial: Partial<T>) {
+ if (pausedRef.current) {
+ pendingStateRef.current = {
+ ...pendingStateRef.current,
+ ...partial,
+ };
+ return;
+ }
+
+ // Convert undefined values to null for nuqs
+ const nuqsPartial: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(partial)) {
+ nuqsPartial[key] = value === undefined ? null : value;
+ }
+
+ setNuqsState((prev) => ({ ...prev, ...nuqsPartial }));
+ },
+
+ setField<K extends keyof T>(key: K, value: T[K]) {
+ this.setState({ [key]: value } as unknown as Partial<T>);
+ },
+
+ reset(fields?: (keyof T)[]) {
+ if (fields) {
+ const resetPartial: Partial<T> = {};
+ for (const field of fields) {
+ resetPartial[field] = defaults[field];
+ }
+ this.setState(resetPartial);
+ } else {
+ this.setState(defaults);
+ }
+ },
+
+ pause() {
+ pausedRef.current = true;
+ },
+
+ resume() {
+ pausedRef.current = false;
+ if (pendingStateRef.current) {
+ this.setState(pendingStateRef.current);
+ pendingStateRef.current = null;
+ }
+ },
+
+ isPaused() {
+ return pausedRef.current;
+ },
+
+ destroy() {
+ listenersRef.current.clear();
+ },
+
+ getTableId() {
+ return id;
+ },
+
+ getSchema() {
+ return schema;
+ },
+
+ getDefaults() {
+ return defaults;
+ },
+
+ // Internal methods for provider sync
+ _syncState(state: T) {
+ stateRef.current = state;
+ versionRef.current++;
+ listenersRef.current.forEach((listener) => listener());
+ },
+ };
+ }, [id, schema, defaults, initialState, setNuqsState]);
+
+ return adapter;
+}
+
+// Re-export parser bridge utilities for advanced use cases
+export { schemaToNuqsParsers, createSchemaSerializer } from "./parser-bridge";
+
+// Re-export nuqs types for components that need them
+// This allows components to import from the adapter layer instead of nuqs directly
+export type { ParserBuilder } from "nuqs";
diff --git a/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/parser-bridge.ts b/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/parser-bridge.ts
new file mode 100644
index 000000000..ec15d5fd9
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/parser-bridge.ts
@@ -0,0 +1,181 @@
+import { SORT_DELIMITER } from "@openstatus/ui/lib/data-table-filters/delimiters";
+import {
+ createParser,
+ parseAsArrayOf,
+ parseAsBoolean,
+ parseAsInteger,
+ parseAsString,
+ parseAsStringLiteral,
+ parseAsTimestamp,
+ type ParserBuilder,
+} from "nuqs/server";
+
+import type {
+ FieldBuilder,
+ FieldConfig,
+ SchemaDefinition,
+} from "../../schema/types";
+
+/**
+ * Type mapping: Schema field type → nuqs ParserBuilder type
+ */
+export type SchemaToNuqsParsers<T extends SchemaDefinition> = {
+ [K in keyof T]: T[K] extends FieldBuilder<infer U>
+ ? ParserBuilder<U>
+ : ParserBuilder<unknown>;
+};
+
+/**
+ * Convert a single field config to a nuqs parser
+ */
+function fieldConfigToParser(
+ config: FieldConfig<unknown>,
+): ParserBuilder<unknown> {
+ // A schema-level serialize/parse override defines the URL format, so it wins
+ // over the built-in parser for the field type
+ if (config.hasCustomTransform) {
+ return createParser({
+ parse: (queryValue: string) => config.parse(queryValue),
+ serialize: (value: unknown) => config.serialize(value),
+ }) as ParserBuilder<unknown>;
+ }
+
+ switch (config.type) {
+ case "string":
+ return parseAsString as ParserBuilder<unknown>;
+
+ case "number":
+ return parseAsInteger as ParserBuilder<unknown>;
+
+ case "boolean":
+ return parseAsBoolean as ParserBuilder<unknown>;
+
+ case "timestamp":
+ return parseAsTimestamp as ParserBuilder<unknown>;
+
+ case "stringLiteral":
+ if (config.literals) {
+ return parseAsStringLiteral(
+ config.literals as unknown as readonly string[],
+ ) as ParserBuilder<unknown>;
+ }
+ return parseAsString as ParserBuilder<unknown>;
+
+ case "array":
+ if (config.itemConfig) {
+ const itemParser = fieldConfigToParser(config.itemConfig);
+ return parseAsArrayOf(
+ itemParser as ParserBuilder<string>,
+ config.delimiter,
+ ) as ParserBuilder<unknown>;
+ }
+ return parseAsArrayOf(
+ parseAsString,
+ config.delimiter,
+ ) as ParserBuilder<unknown>;
+
+ case "sort":
+ return createParser({
+ parse(queryValue: string) {
+ const [id, desc] = queryValue.split(SORT_DELIMITER);
+ if (!id) return null;
+ return { id, desc: desc === "desc" };
+ },
+ serialize(value: { id: string; desc: boolean }) {
+ return `${value.id}${SORT_DELIMITER}${value.desc ? "desc" : "asc"}`;
+ },
+ }) as ParserBuilder<unknown>;
+
+ default:
+ return parseAsString as ParserBuilder<unknown>;
+ }
+}
+
+/**
+ * Apply default value to a nuqs parser
+ */
+function applyDefault(
+ parser: ParserBuilder<unknown>,
+ defaultValue: unknown,
+): ParserBuilder<unknown> {
+ if (defaultValue !== null && defaultValue !== undefined) {
+ // Arrays default to empty array, not worth adding .withDefault
+ if (Array.isArray(defaultValue) && defaultValue.length === 0) {
+ return parser;
+ }
+ // Only apply withDefault for non-null primitive defaults
+ if (
+ typeof defaultValue === "string" ||
+ typeof defaultValue === "number" ||
+ typeof defaultValue === "boolean" ||
+ defaultValue instanceof Date
+ ) {
+ return (
+ parser as ParserBuilder<unknown> & {
+ withDefault: (d: unknown) => ParserBuilder<unknown>;
+ }
+ ).withDefault(defaultValue);
+ }
+ }
+ return parser;
+}
+
+/**
+ * Convert a schema definition to nuqs parsers
+ *
+ * @example
+ * ```typescript
+ * const schema = createSchema({
+ * level: field.array(field.string()),
+ * latency: field.number(),
+ * });
+ *
+ * // Type is inferred: { level: ParserBuilder<string[]>, latency: ParserBuilder<number> }
+ * const parsers = schemaToNuqsParsers(schema.definition);
+ * ```
+ */
+export function schemaToNuqsParsers<T extends SchemaDefinition>(
+ schema: T,
+): SchemaToNuqsParsers<T> {
+ const parsers: Record<string, ParserBuilder<unknown>> = {};
+
+ for (const [key, fieldBuilder] of Object.entries(schema)) {
+ const config = fieldBuilder._config;
+ let parser = fieldConfigToParser(config);
+ parser = applyDefault(parser, config.defaultValue);
+ parsers[key] = parser;
+ }
+
+ return parsers as SchemaToNuqsParsers<T>;
+}
+
+/**
+ * Create a nuqs cache serializer from schema
+ */
+export function createSchemaSerializer(schema: SchemaDefinition) {
+ const parsers = schemaToNuqsParsers(schema);
+
+ return (state: Record<string, unknown>): string => {
+ const params = new URLSearchParams();
+
+ for (const [key, parser] of Object.entries(parsers)) {
+ const value = state[key];
+ if (value === null || value === undefined) continue;
+ if (Array.isArray(value) && value.length === 0) continue;
+
+ try {
+ const serialized = (
+ parser as { serialize?: (v: unknown) => string }
+ ).serialize?.(value);
+ if (serialized) {
+ params.set(key, serialized);
+ }
+ } catch {
+ // Skip invalid values
+ }
+ }
+
+ const str = params.toString();
+ return str ? `?${str}` : "";
+ };
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/server.ts b/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/server.ts
new file mode 100644
index 000000000..4b5e7f6d8
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/server.ts
@@ -0,0 +1,118 @@
+import {
+ createSearchParamsCache,
+ createSerializer,
+ type ParserBuilder,
+} from "nuqs/server";
+
+import type { SchemaDefinition } from "../../schema/types";
+import { schemaToNuqsParsers, type SchemaToNuqsParsers } from "./parser-bridge";
+
+export type { SchemaToNuqsParsers } from "./parser-bridge";
+
+/**
+ * Options for creating nuqs search params utilities
+ */
+export interface CreateNuqsSearchParamsOptions<
+ TExtra extends Record<string, ParserBuilder<any>> = {},
+> {
+ /**
+ * Additional parsers to include (e.g., pagination params)
+ */
+ extraParsers?: TExtra;
+}
+
+/**
+ * Result of createNuqsSearchParams
+ */
+export interface NuqsSearchParamsResult<
+ TSchema extends SchemaDefinition,
+ TExtra extends Record<string, ParserBuilder<any>> = {},
+> {
+ /**
+ * Combined parser object for useQueryStates
+ */
+ searchParamsParser: SchemaToNuqsParsers<TSchema> & TExtra;
+
+ /**
+ * Search params cache for server-side parsing
+ */
+ searchParamsCache: ReturnType<
+ typeof createSearchParamsCache<SchemaToNuqsParsers<TSchema> & TExtra>
+ >;
+
+ /**
+ * Serializer for converting state to URL string
+ */
+ searchParamsSerializer: ReturnType<
+ typeof createSerializer<SchemaToNuqsParsers<TSchema> & TExtra>
+ >;
+}
+
+/**
+ * Create nuqs search params utilities from a BYOS schema
+ *
+ * This creates searchParamsParser, searchParamsCache, and searchParamsSerializer
+ * from a schema definition, with optional extra parsers for pagination etc.
+ *
+ * @example
+ * ```typescript
+ * import { createNuqsSearchParams } from '@openstatus/ui/lib/data-table-filters/store/adapters/nuqs/server';
+ * import { parseAsInteger, parseAsTimestamp } from 'nuqs/server';
+ *
+ * export const {
+ * searchParamsParser,
+ * searchParamsCache,
+ * searchParamsSerializer,
+ * } = createNuqsSearchParams(filterSchema.definition, {
+ * extraParsers: {
+ * size: parseAsInteger.withDefault(40),
+ * start: parseAsInteger.withDefault(0),
+ * cursor: parseAsTimestamp,
+ * },
+ * });
+ * ```
+ */
+export function createNuqsSearchParams<
+ TSchema extends SchemaDefinition,
+ TExtra extends Record<string, ParserBuilder<any>> = {},
+>(
+ schema: TSchema,
+ options: CreateNuqsSearchParamsOptions<TExtra> = {},
+): NuqsSearchParamsResult<TSchema, TExtra> {
+ const { extraParsers = {} as TExtra } = options;
+
+ // Generate parsers from schema
+ const schemaParsers = schemaToNuqsParsers(schema);
+
+ // Combine with extra parsers
+ const searchParamsParser = {
+ ...schemaParsers,
+ ...extraParsers,
+ } as SchemaToNuqsParsers<TSchema> & TExtra;
+
+ // Create cache and serializer
+ const searchParamsCache = createSearchParamsCache(searchParamsParser);
+ const searchParamsSerializer = createSerializer(searchParamsParser);
+
+ return {
+ searchParamsParser,
+ searchParamsCache,
+ searchParamsSerializer,
+ };
+}
+
+// Re-export commonly used nuqs parsers for convenience
+export {
+ parseAsArrayOf,
+ parseAsBoolean,
+ parseAsInteger,
+ parseAsString,
+ parseAsStringLiteral,
+ parseAsTimestamp,
+ createParser,
+ type ParserBuilder,
+ type inferParserType,
+} from "nuqs/server";
+
+// Re-export schema parser utilities
+export { schemaToNuqsParsers, createSchemaSerializer } from "./parser-bridge";
diff --git a/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/types.ts b/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/types.ts
new file mode 100644
index 000000000..b2e73af90
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/adapters/nuqs/types.ts
@@ -0,0 +1,28 @@
+import type { CreateAdapterOptions } from "../../adapter/types";
+
+/**
+ * nuqs-specific adapter options
+ */
+export interface NuqsAdapterOptions<
+ T extends Record<string, unknown>,
+> extends CreateAdapterOptions<T> {
+ /**
+ * Use shallow routing (default: true)
+ */
+ shallow?: boolean;
+
+ /**
+ * History mode: 'push' | 'replace' (default: 'push')
+ */
+ history?: "push" | "replace";
+
+ /**
+ * Scroll to top on change (default: false)
+ */
+ scroll?: boolean;
+
+ /**
+ * Throttle URL updates in milliseconds (default: 50)
+ */
+ throttleMs?: number;
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/context.ts b/packages/ui/src/lib/data-table-filters/store/context.ts
new file mode 100644
index 000000000..8fd96eff6
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/context.ts
@@ -0,0 +1,39 @@
+"use client";
+
+import { createContext, useContext } from "react";
+
+import type { StoreAdapter } from "./adapter/types";
+import type { SchemaDefinition } from "./schema/types";
+
+/**
+ * Context value for the store provider
+ */
+export interface StoreContextValue<T extends Record<string, unknown>> {
+ adapter: StoreAdapter<T>;
+ schema: SchemaDefinition;
+ tableId: string;
+}
+
+/**
+ * React context for the store adapter
+ * @internal
+ */
+export const StoreContext = createContext<StoreContextValue<
+ Record<string, unknown>
+> | null>(null);
+
+/**
+ * Hook to access the store context
+ * Returns null if used outside of DataTableStoreProvider
+ */
+export function useStoreContext<
+ T extends Record<string, unknown> = Record<string, unknown>,
+>(): StoreContextValue<T> {
+ const context = useContext(StoreContext) as StoreContextValue<T> | null;
+ if (!context) {
+ throw new Error(
+ "useStoreContext must be used within a DataTableStoreProvider",
+ );
+ }
+ return context;
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/hooks/index.ts b/packages/ui/src/lib/data-table-filters/store/hooks/index.ts
new file mode 100644
index 000000000..078e2e087
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/hooks/index.ts
@@ -0,0 +1,3 @@
+export { useFilterState } from "./useFilterState";
+export { useFilterActions, type FilterActions } from "./useFilterActions";
+export { useFilterField, type FilterFieldResult } from "./useFilterField";
diff --git a/packages/ui/src/lib/data-table-filters/store/hooks/useFilterActions.ts b/packages/ui/src/lib/data-table-filters/store/hooks/useFilterActions.ts
new file mode 100644
index 000000000..2980b205d
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/hooks/useFilterActions.ts
@@ -0,0 +1,138 @@
+"use client";
+
+import { useCallback, useMemo } from "react";
+
+import { useStoreContext } from "../context";
+
+/**
+ * Actions returned by useFilterActions
+ */
+export interface FilterActions<T extends Record<string, unknown>> {
+ /**
+ * Set a single filter field value
+ */
+ setFilter: <K extends keyof T>(key: K, value: T[K]) => void;
+
+ /**
+ * Set multiple filter fields at once
+ */
+ setFilters: (partial: Partial<T>) => void;
+
+ /**
+ * Reset a single filter field to its default value
+ */
+ resetFilter: (key: keyof T) => void;
+
+ /**
+ * Reset all filters to default values
+ */
+ resetAllFilters: () => void;
+
+ /**
+ * Pause state updates (for live mode)
+ */
+ pause: () => void;
+
+ /**
+ * Resume state updates
+ */
+ resume: () => void;
+
+ /**
+ * Check if updates are paused
+ */
+ isPaused: () => boolean;
+}
+
+/**
+ * Hook to get filter actions
+ *
+ * @example
+ * ```typescript
+ * const { setFilter, setFilters, resetAllFilters, pause, resume } = useFilterActions();
+ *
+ * // Set single field
+ * setFilter('regions', ['ams', 'gru']);
+ *
+ * // Set multiple fields
+ * setFilters({ regions: ['ams'], host: 'api.example.com' });
+ *
+ * // Reset all
+ * resetAllFilters();
+ *
+ * // Pause/resume for live mode
+ * pause();
+ * resume();
+ * ```
+ */
+export function useFilterActions<
+ T extends Record<string, unknown>,
+>(): FilterActions<T> {
+ const context = useStoreContext();
+
+ if (!context) {
+ throw new Error(
+ "useFilterActions must be used within a DataTableStoreProvider",
+ );
+ }
+
+ const { adapter } = context;
+
+ const setFilter = useCallback(
+ <K extends keyof T>(key: K, value: T[K]) => {
+ adapter.setField(key as string, value);
+ },
+ [adapter],
+ );
+
+ const setFilters = useCallback(
+ (partial: Partial<T>) => {
+ adapter.setState(partial as Partial<Record<string, unknown>>);
+ },
+ [adapter],
+ );
+
+ const resetFilter = useCallback(
+ (key: keyof T) => {
+ adapter.reset([key as string]);
+ },
+ [adapter],
+ );
+
+ const resetAllFilters = useCallback(() => {
+ adapter.reset();
+ }, [adapter]);
+
+ const pause = useCallback(() => {
+ adapter.pause();
+ }, [adapter]);
+
+ const resume = useCallback(() => {
+ adapter.resume();
+ }, [adapter]);
+
+ const isPaused = useCallback(() => {
+ return adapter.isPaused();
+ }, [adapter]);
+
+ return useMemo(
+ () => ({
+ setFilter,
+ setFilters,
+ resetFilter,
+ resetAllFilters,
+ pause,
+ resume,
+ isPaused,
+ }),
+ [
+ setFilter,
+ setFilters,
+ resetFilter,
+ resetAllFilters,
+ pause,
+ resume,
+ isPaused,
+ ],
+ );
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/hooks/useFilterField.ts b/packages/ui/src/lib/data-table-filters/store/hooks/useFilterField.ts
new file mode 100644
index 000000000..2397a9611
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/hooks/useFilterField.ts
@@ -0,0 +1,87 @@
+"use client";
+
+import { useCallback, useMemo, useSyncExternalStore } from "react";
+
+import { useStoreContext } from "../context";
+
+/**
+ * Return type for useFilterField
+ */
+export interface FilterFieldResult<T> {
+ /**
+ * Current value of the field
+ */
+ value: T;
+
+ /**
+ * Set the field value
+ */
+ setValue: (value: T) => void;
+
+ /**
+ * Reset the field to its default value
+ */
+ reset: () => void;
+}
+
+/**
+ * Hook to work with a single filter field
+ *
+ * @example
+ * ```typescript
+ * const { value, setValue, reset } = useFilterField<FilterState, 'regions'>('regions');
+ *
+ * // Read value
+ * console.log(value); // ['ams', 'gru']
+ *
+ * // Update value
+ * setValue(['ams', 'gru', 'fra']);
+ *
+ * // Reset to default
+ * reset();
+ * ```
+ */
+export function useFilterField<
+ T extends Record<string, unknown>,
+ K extends keyof T,
+>(key: K): FilterFieldResult<T[K]> {
+ const context = useStoreContext();
+
+ if (!context) {
+ throw new Error(
+ "useFilterField must be used within a DataTableStoreProvider",
+ );
+ }
+
+ const { adapter } = context;
+
+ const subscribe = useCallback(
+ (onStoreChange: () => void) => adapter.subscribe(onStoreChange),
+ [adapter],
+ );
+
+ const getSnapshot = useCallback(() => {
+ const snapshot = adapter.getSnapshot();
+ return (snapshot.state as T)[key];
+ }, [adapter, key]);
+
+ const getServerSnapshot = useCallback(() => {
+ const snapshot = adapter.getServerSnapshot?.() ?? adapter.getSnapshot();
+ return (snapshot.state as T)[key];
+ }, [adapter, key]);
+
+ const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
+
+ const setValue = useCallback(
+ (newValue: T[K]) => {
+ adapter.setField(key as string, newValue);
+ },
+ [adapter, key],
+ );
+
+ const reset = useCallback(() => {
+ adapter.reset([key as string]);
+ }, [adapter, key]);
+
+ return useMemo(() => ({ value, setValue, reset }), [value, setValue, reset]);
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/hooks/useFilterState.ts b/packages/ui/src/lib/data-table-filters/store/hooks/useFilterState.ts
new file mode 100644
index 000000000..e0fd88c75
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/hooks/useFilterState.ts
@@ -0,0 +1,117 @@
+"use client";
+
+import { useCallback, useRef, useSyncExternalStore } from "react";
+
+import { useStoreContext } from "../context";
+
+/**
+ * Hook to read filter state from the adapter
+ *
+ * @example
+ * ```typescript
+ * // Read entire state
+ * const state = useFilterState();
+ *
+ * // Read with selector (for performance)
+ * const regions = useFilterState(s => s.regions);
+ * ```
+ */
+export function useFilterState<T extends Record<string, unknown>, R = T>(
+ selector?: (state: T) => R,
+): R {
+ const context = useStoreContext();
+
+ if (!context) {
+ throw new Error(
+ "useFilterState must be used within a DataTableStoreProvider",
+ );
+ }
+
+ const { adapter } = context;
+
+ const subscribe = useCallback(
+ (onStoreChange: () => void) => adapter.subscribe(onStoreChange),
+ [adapter],
+ );
+
+ // useSyncExternalStore requires a cached snapshot: a selector returning a new
+ // array/object on every call would otherwise re-render forever.
+ const cacheRef = useRef<{
+ state: unknown;
+ selector: unknown;
+ result: R;
+ } | null>(null);
+
+ const select = useCallback(
+ (state: T): R => {
+ if (!selector) return state as unknown as R;
+
+ const cached = cacheRef.current;
+ if (cached && cached.state === state && cached.selector === selector) {
+ return cached.result;
+ }
+
+ const next = selector(state);
+ // Keep the previous reference when the contents match so consumers
+ // don't re-render on a new selector identity alone
+ const result =
+ cached && shallowEqual(cached.result, next) ? cached.result : next;
+
+ cacheRef.current = { state, selector, result };
+ return result;
+ },
+ [selector],
+ );
+
+ const getSnapshot = useCallback(
+ () => select(adapter.getSnapshot().state as T),
+ [adapter, select],
+ );
+
+ const getServerSnapshot = useCallback(() => {
+ const snapshot = adapter.getServerSnapshot?.() ?? adapter.getSnapshot();
+ return select(snapshot.state as T);
+ }, [adapter, select]);
+
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
+}
+
+function isPlainObject(value: object): boolean {
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
+}
+
+function shallowEqual(a: unknown, b: unknown): boolean {
+ if (Object.is(a, b)) return true;
+ if (
+ typeof a !== "object" ||
+ typeof b !== "object" ||
+ a === null ||
+ b === null
+ ) {
+ return false;
+ }
+
+ if (Array.isArray(a) || Array.isArray(b)) {
+ if (!Array.isArray(a) || !Array.isArray(b)) return false;
+ if (a.length !== b.length) return false;
+ return a.every((item, i) => Object.is(item, b[i]));
+ }
+
+ // Only arrays and plain objects carry their contents in enumerable keys. A
+ // `Date`, `Map` or `Set` has none, so key-walking two different ones reports
+ // them equal and the selector keeps handing back the stale value.
+ if (!isPlainObject(a) || !isPlainObject(b)) return false;
+
+ const keysA = Object.keys(a);
+ const keysB = Object.keys(b);
+ if (keysA.length !== keysB.length) return false;
+ return keysA.every(
+ (key) =>
+ Object.hasOwn(b, key) &&
+ Object.is(
+ (a as Record<string, unknown>)[key],
+ (b as Record<string, unknown>)[key],
+ ),
+ );
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/parser/index.ts b/packages/ui/src/lib/data-table-filters/store/parser/index.ts
new file mode 100644
index 000000000..0c6ce6d16
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/parser/index.ts
@@ -0,0 +1,2 @@
+export { createTextParser } from "./text-parser";
+export type { TextParser, TextParserOptions } from "./types";
diff --git a/packages/ui/src/lib/data-table-filters/store/parser/text-parser.ts b/packages/ui/src/lib/data-table-filters/store/parser/text-parser.ts
new file mode 100644
index 000000000..7f9dd8eed
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/parser/text-parser.ts
@@ -0,0 +1,202 @@
+import {
+ serializeFilterValue,
+ tokenizeFilterInput,
+} from "@openstatus/ui/lib/data-table-filters/tokenize";
+
+import type {
+ FieldBuilder,
+ InferSchemaType,
+ SchemaDefinition,
+} from "../schema/types";
+import type { TextParser, TextParserOptions } from "./types";
+
+/**
+ * Create a text parser for filter command input
+ *
+ * @example
+ * ```typescript
+ * import { createTextParser } from '@openstatus/ui/lib/data-table-filters/store/parser';
+ *
+ * const parser = createTextParser(schema.definition, {
+ * aliases: { l: 'level', r: 'regions' },
+ * });
+ *
+ * // Parse text to state
+ * const state = parser.parse('level:error,warn regions:ams');
+ *
+ * // Serialize state to text
+ * const text = parser.serialize({ level: ['error', 'warn'], regions: ['ams'] });
+ * ```
+ */
+export function createTextParser<T extends SchemaDefinition>(
+ schema: T,
+ options: TextParserOptions = {},
+): TextParser<T> {
+ const {
+ aliases = {},
+ fieldDelimiter = " ",
+ keyValueDelimiter = ":",
+ } = options;
+
+ // Build reverse alias map
+ const reverseAliases: Record<string, string> = {};
+ for (const [alias, field] of Object.entries(aliases)) {
+ reverseAliases[field] = alias;
+ }
+
+ // Resolve alias to field name
+ const resolveAlias = (key: string): string => {
+ return aliases[key] || key;
+ };
+
+ return {
+ parse(input: string): Partial<InferSchemaType<T>> {
+ const result: Record<string, unknown> = {};
+
+ if (!input.trim()) {
+ return result as Partial<InferSchemaType<T>>;
+ }
+
+ const tokens = tokenizeFilterInput(input, {
+ fieldDelimiter,
+ keyValueDelimiter,
+ });
+
+ for (const [rawKey, rawValue] of tokens) {
+ if (!rawKey || !rawValue) continue;
+
+ const fieldKey = resolveAlias(rawKey);
+ // own-property only: `toString:x` would otherwise resolve on the prototype
+ if (!Object.prototype.hasOwnProperty.call(schema, fieldKey)) continue;
+
+ const fieldBuilder = schema[fieldKey] as
+ | FieldBuilder<unknown>
+ | undefined;
+
+ if (!fieldBuilder) continue;
+
+ try {
+ const parsed = fieldBuilder._config.parse(rawValue);
+ if (parsed !== null) {
+ result[fieldKey] = parsed;
+ }
+ } catch {
+ // Skip invalid values
+ }
+ }
+
+ return result as Partial<InferSchemaType<T>>;
+ },
+
+ serialize(state: Partial<InferSchemaType<T>>): string {
+ const parts: string[] = [];
+
+ for (const [key, value] of Object.entries(state)) {
+ if (value === null || value === undefined) continue;
+ if (Array.isArray(value) && value.length === 0) continue;
+
+ const fieldBuilder = schema[key] as FieldBuilder<unknown> | undefined;
+ if (!fieldBuilder) continue;
+
+ try {
+ const serialized = fieldBuilder._config.serialize(value);
+ if (serialized) {
+ const quoted = serializeFilterValue(serialized, { fieldDelimiter });
+ parts.push(`${key}${keyValueDelimiter}${quoted}`);
+ }
+ } catch {
+ // Skip invalid values
+ }
+ }
+
+ return parts.join(fieldDelimiter);
+ },
+
+ getWordAtCaret(input: string, caretPosition: number) {
+ // Find word boundaries
+ let start = caretPosition;
+ let end = caretPosition;
+
+ // Move start backwards to find word start
+ while (start > 0 && input[start - 1] !== fieldDelimiter) {
+ start--;
+ }
+
+ // Move end forwards to find word end
+ while (end < input.length && input[end] !== fieldDelimiter) {
+ end++;
+ }
+
+ const word = input.slice(start, end);
+ const colonIndex = word.indexOf(keyValueDelimiter);
+
+ let field: string | null = null;
+ let value: string | null = null;
+
+ if (colonIndex !== -1) {
+ field = resolveAlias(word.slice(0, colonIndex));
+ value = word.slice(colonIndex + 1);
+ } else {
+ // Could be a partial field name
+ field = null;
+ value = null;
+ }
+
+ return { word, start, end, field, value };
+ },
+
+ replaceWordAtCaret(
+ input: string,
+ caretPosition: number,
+ replacement: string,
+ ) {
+ const { start, end } = this.getWordAtCaret(input, caretPosition);
+
+ const before = input.slice(0, start);
+ const after = input.slice(end);
+
+ const newInput = before + replacement + after;
+ const newCaretPosition = start + replacement.length;
+
+ return { newInput, newCaretPosition };
+ },
+
+ getSuggestions(
+ input: string,
+ caretPosition: number,
+ fieldOptions: Record<string, string[]>,
+ ) {
+ const { word, field, value } = this.getWordAtCaret(input, caretPosition);
+
+ // If we have a field and are typing a value
+ if (field && value !== null) {
+ const options = fieldOptions[field] || [];
+ const filtered = options.filter((opt) =>
+ opt.toLowerCase().includes(value.toLowerCase()),
+ );
+
+ return {
+ type: "value" as const,
+ field,
+ suggestions: filtered,
+ };
+ }
+
+ // Otherwise, suggest field names
+ const schemaKeys = Object.keys(schema);
+ const aliasKeys = Object.keys(aliases);
+ const allFields = [...schemaKeys, ...aliasKeys];
+
+ const filtered = word
+ ? allFields.filter((f) =>
+ f.toLowerCase().startsWith(word.toLowerCase()),
+ )
+ : allFields;
+
+ return {
+ type: "field" as const,
+ suggestions: filtered,
+ };
+ },
+ };
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/parser/types.ts b/packages/ui/src/lib/data-table-filters/store/parser/types.ts
new file mode 100644
index 000000000..e53ab9416
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/parser/types.ts
@@ -0,0 +1,87 @@
+import type { InferSchemaType, SchemaDefinition } from "../schema/types";
+
+/**
+ * Options for creating a text parser
+ */
+export interface TextParserOptions {
+ /**
+ * Field aliases for shorthand (e.g., { l: 'level', r: 'regions' })
+ */
+ aliases?: Record<string, string>;
+
+ /**
+ * Delimiter between field:value pairs (default: ' ')
+ */
+ fieldDelimiter?: string;
+
+ /**
+ * Delimiter between field and value (default: ':')
+ */
+ keyValueDelimiter?: string;
+}
+
+/**
+ * Text parser interface
+ */
+export interface TextParser<T extends SchemaDefinition> {
+ /**
+ * Parse a text input string into filter state
+ *
+ * @example
+ * ```typescript
+ * parser.parse('regions:ams,gru latency:0-1000');
+ * // => { regions: ['ams', 'gru'], latency: [0, 1000] }
+ * ```
+ */
+ parse(input: string): Partial<InferSchemaType<T>>;
+
+ /**
+ * Serialize filter state to text format
+ *
+ * @example
+ * ```typescript
+ * parser.serialize({ regions: ['ams', 'gru'], latency: [0, 1000] });
+ * // => 'regions:ams,gru latency:0-1000'
+ * ```
+ */
+ serialize(state: Partial<InferSchemaType<T>>): string;
+
+ /**
+ * Get the current word at caret position
+ */
+ getWordAtCaret(
+ input: string,
+ caretPosition: number,
+ ): {
+ word: string;
+ start: number;
+ end: number;
+ field: string | null;
+ value: string | null;
+ };
+
+ /**
+ * Replace the current word at caret position
+ */
+ replaceWordAtCaret(
+ input: string,
+ caretPosition: number,
+ replacement: string,
+ ): {
+ newInput: string;
+ newCaretPosition: number;
+ };
+
+ /**
+ * Get suggestions for autocomplete
+ */
+ getSuggestions(
+ input: string,
+ caretPosition: number,
+ fieldOptions: Record<string, string[]>,
+ ): {
+ type: "field" | "value";
+ field?: string;
+ suggestions: string[];
+ };
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/provider/DataTableStoreProvider.tsx b/packages/ui/src/lib/data-table-filters/store/provider/DataTableStoreProvider.tsx
new file mode 100644
index 000000000..a0eb78f83
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/provider/DataTableStoreProvider.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import React, { useEffect, useMemo } from "react";
+
+import type { StoreAdapter } from "../adapter/types";
+import { StoreContext, type StoreContextValue } from "../context";
+
+export interface DataTableStoreProviderProps<
+ T extends Record<string, unknown>,
+> {
+ /**
+ * The store adapter to use
+ */
+ adapter: StoreAdapter<T>;
+
+ /**
+ * Child components
+ */
+ children: React.ReactNode;
+}
+
+/**
+ * Provider component for data table store
+ *
+ * @example
+ * ```typescript
+ * const adapter = useNuqsAdapter(schema.definition, { id: 'my-table' });
+ *
+ * return (
+ * <DataTableStoreProvider adapter={adapter}>
+ * <DataTable />
+ * </DataTableStoreProvider>
+ * );
+ * ```
+ */
+export function DataTableStoreProvider<T extends Record<string, unknown>>({
+ adapter,
+ children,
+}: DataTableStoreProviderProps<T>) {
+ const value = useMemo<StoreContextValue<T>>(
+ () => ({
+ adapter,
+ schema: adapter.getSchema(),
+ tableId: adapter.getTableId(),
+ }),
+ [adapter],
+ );
+
+ // Cleanup on unmount
+ useEffect(() => {
+ return () => {
+ adapter.destroy();
+ };
+ }, [adapter]);
+
+ return (
+ <StoreContext.Provider
+ value={value as StoreContextValue<Record<string, unknown>>}
+ >
+ {children}
+ </StoreContext.Provider>
+ );
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/schema/field.ts b/packages/ui/src/lib/data-table-filters/store/schema/field.ts
new file mode 100644
index 000000000..4980290f1
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/schema/field.ts
@@ -0,0 +1,200 @@
+import {
+ ARRAY_DELIMITER,
+ SLIDER_DELIMITER,
+ SORT_DELIMITER,
+} from "@openstatus/ui/lib/data-table-filters/delimiters";
+
+import type { FieldBuilder, FieldConfig } from "./types";
+
+// Helper to create a field builder from config
+function createFieldBuilder<T>(config: FieldConfig<T>): FieldBuilder<T> {
+ const builder: FieldBuilder<T> = {
+ default(value: T) {
+ return createFieldBuilder({ ...config, defaultValue: value });
+ },
+
+ delimiter(separator: string) {
+ // Update serialize/parse functions when delimiter changes for arrays
+ if (config.type === "array" && config.itemConfig) {
+ const itemConfig = config.itemConfig as FieldConfig<unknown>;
+ return createFieldBuilder({
+ ...config,
+ delimiter: separator,
+ serialize: (value: T) => {
+ if (!Array.isArray(value)) return "";
+ return value
+ .map((item) => itemConfig.serialize(item))
+ .join(separator);
+ },
+ parse: (str: string) => {
+ if (!str) return config.defaultValue;
+ const items = str.split(separator);
+ const parsed = items
+ .map((item) => itemConfig.parse(item))
+ .filter(
+ (item): item is NonNullable<typeof item> => item !== null,
+ );
+ return parsed as T;
+ },
+ });
+ }
+ return createFieldBuilder({ ...config, delimiter: separator });
+ },
+
+ serialize(fn: (value: T) => string) {
+ return createFieldBuilder({
+ ...config,
+ serialize: fn,
+ hasCustomTransform: true,
+ });
+ },
+
+ parse(fn: (value: string) => T | null) {
+ return createFieldBuilder({
+ ...config,
+ parse: fn,
+ hasCustomTransform: true,
+ });
+ },
+
+ get _config() {
+ return config;
+ },
+ };
+
+ return builder;
+}
+
+// String field
+function string(): FieldBuilder<string | null> {
+ return createFieldBuilder<string | null>({
+ type: "string",
+ defaultValue: null,
+ delimiter: "",
+ serialize: (value) => (value === null ? "" : String(value)),
+ parse: (str) => (str === "" ? null : str),
+ });
+}
+
+// Number field (integer)
+function number(): FieldBuilder<number | null> {
+ return createFieldBuilder<number | null>({
+ type: "number",
+ defaultValue: null,
+ delimiter: "",
+ serialize: (value) => (value === null ? "" : String(value)),
+ parse: (str) => {
+ if (str === "") return null;
+ const num = parseInt(str, 10);
+ return isNaN(num) ? null : num;
+ },
+ });
+}
+
+// Boolean field
+function boolean(): FieldBuilder<boolean | null> {
+ return createFieldBuilder<boolean | null>({
+ type: "boolean",
+ defaultValue: null,
+ delimiter: "",
+ serialize: (value) => (value === null ? "" : String(value)),
+ parse: (str) => {
+ if (str === "") return null;
+ if (str === "true") return true;
+ if (str === "false") return false;
+ return null;
+ },
+ });
+}
+
+// Timestamp field (Date)
+function timestamp(): FieldBuilder<Date | null> {
+ return createFieldBuilder<Date | null>({
+ type: "timestamp",
+ defaultValue: null,
+ delimiter: "",
+ serialize: (value) => (value === null ? "" : String(value.getTime())),
+ parse: (str) => {
+ if (str === "") return null;
+ const time = parseInt(str, 10);
+ if (isNaN(time)) return null;
+ const date = new Date(time);
+ return isNaN(date.getTime()) ? null : date;
+ },
+ });
+}
+
+// String literal field (enum-like)
+function stringLiteral<T extends readonly string[]>(
+ literals: T,
+): FieldBuilder<T[number] | null> {
+ return createFieldBuilder<T[number] | null>({
+ type: "stringLiteral",
+ defaultValue: null,
+ delimiter: "",
+ literals,
+ serialize: (value) => (value === null ? "" : String(value)),
+ parse: (str) => {
+ if (str === "") return null;
+ return literals.includes(str as T[number]) ? (str as T[number]) : null;
+ },
+ });
+}
+
+// Array field
+function array<T>(itemBuilder: FieldBuilder<T>): FieldBuilder<T[]> {
+ const itemConfig = itemBuilder._config;
+ const defaultDelimiter =
+ itemConfig.type === "number" ? SLIDER_DELIMITER : ARRAY_DELIMITER;
+
+ return createFieldBuilder<T[]>({
+ type: "array",
+ defaultValue: [],
+ delimiter: defaultDelimiter,
+ itemConfig: itemConfig as FieldConfig<unknown>,
+ serialize: (value) => {
+ if (!Array.isArray(value) || value.length === 0) return "";
+ return value
+ .map((item) => itemConfig.serialize(item))
+ .join(defaultDelimiter);
+ },
+ parse: (str) => {
+ if (!str) return [];
+ const items = str.split(defaultDelimiter);
+ const parsed = items
+ .map((item) => itemConfig.parse(item))
+ .filter((item): item is T => item !== null);
+ return parsed;
+ },
+ });
+}
+
+// Sort field { id: string, desc: boolean }
+function sort(): FieldBuilder<{ id: string; desc: boolean } | null> {
+ return createFieldBuilder<{ id: string; desc: boolean } | null>({
+ type: "sort",
+ defaultValue: null,
+ delimiter: SORT_DELIMITER,
+ serialize: (value) => {
+ if (value === null) return "";
+ return `${value.id}${SORT_DELIMITER}${value.desc ? "desc" : "asc"}`;
+ },
+ parse: (str) => {
+ if (!str) return null;
+ const [id, desc] = str.split(SORT_DELIMITER);
+ if (!id) return null;
+ return { id, desc: desc === "desc" };
+ },
+ });
+}
+
+// Export field builders
+export const field = {
+ string,
+ number,
+ boolean,
+ timestamp,
+ stringLiteral,
+ array,
+ sort,
+};
diff --git a/packages/ui/src/lib/data-table-filters/store/schema/index.ts b/packages/ui/src/lib/data-table-filters/store/schema/index.ts
new file mode 100644
index 000000000..e65c48b9c
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/schema/index.ts
@@ -0,0 +1,70 @@
+import { getSchemaDefaults } from "./serialization";
+import type { InferSchemaType, Schema, SchemaDefinition } from "./types";
+
+/**
+ * Schema System for BYOS (Bring Your Own Store)
+ *
+ * Provides a fluent API for defining filter schemas with type inference.
+ *
+ * @example
+ * ```typescript
+ * import { createSchema, field } from '@openstatus/ui/lib/data-table-filters/store/schema';
+ *
+ * const schema = createSchema({
+ * regions: field.array(field.string()).default([]).delimiter(','),
+ * latency: field.array(field.number()).delimiter('-'),
+ * host: field.string().default(''),
+ * live: field.boolean().default(false),
+ * });
+ *
+ * type FilterState = typeof schema._type;
+ * ```
+ */
+
+export { field } from "./field";
+export type {
+ FieldBuilder,
+ FieldConfig,
+ SchemaDefinition,
+ InferSchemaType,
+ Schema,
+ StoreSnapshot,
+ AdapterOptions,
+} from "./types";
+export {
+ getSchemaDefaults,
+ serializeState,
+ parseState,
+ validateState,
+ mergeWithDefaults,
+ isStateEqual,
+ stateToSearchString,
+} from "./serialization";
+
+/**
+ * Create a schema from field definitions
+ *
+ * @param definition - Object mapping field names to field builders
+ * @returns Schema object with definition, defaults, and type inference
+ *
+ * @example
+ * ```typescript
+ * const schema = createSchema({
+ * level: field.array(field.stringLiteral(['error', 'warn', 'info'])).default([]),
+ * latency: field.array(field.number()).delimiter('-'),
+ * host: field.string(),
+ * });
+ * ```
+ */
+export function createSchema<T extends SchemaDefinition>(
+ definition: T,
+): Schema<T> {
+ const defaults = getSchemaDefaults(definition);
+
+ return {
+ definition,
+ defaults,
+ // This is a type-only property for inference
+ _type: defaults,
+ };
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/schema/serialization.ts b/packages/ui/src/lib/data-table-filters/store/schema/serialization.ts
new file mode 100644
index 000000000..08a5ad246
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/schema/serialization.ts
@@ -0,0 +1,187 @@
+import type { FieldBuilder, InferSchemaType, SchemaDefinition } from "./types";
+
+/**
+ * Get default values from a schema definition
+ */
+export function getSchemaDefaults<T extends SchemaDefinition>(
+ schema: T,
+): InferSchemaType<T> {
+ const defaults: Record<string, unknown> = {};
+
+ for (const [key, fieldBuilder] of Object.entries(schema)) {
+ defaults[key] = fieldBuilder._config.defaultValue;
+ }
+
+ return defaults as InferSchemaType<T>;
+}
+
+/**
+ * Serialize state to a string map (for URL params or storage)
+ */
+export function serializeState<T extends SchemaDefinition>(
+ schema: T,
+ state: Partial<InferSchemaType<T>>,
+): Record<string, string> {
+ const result: Record<string, string> = {};
+
+ for (const [key, value] of Object.entries(state)) {
+ const fieldBuilder = schema[key] as FieldBuilder<unknown> | undefined;
+ if (!fieldBuilder) continue;
+
+ const serialized = fieldBuilder._config.serialize(value);
+ if (serialized !== "") {
+ result[key] = serialized;
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Parse a string map back to state
+ */
+export function parseState<T extends SchemaDefinition>(
+ schema: T,
+ stringMap: Record<string, string | string[] | undefined>,
+): Partial<InferSchemaType<T>> {
+ const result: Record<string, unknown> = {};
+
+ for (const [key, fieldBuilder] of Object.entries(schema)) {
+ const rawValue = stringMap[key];
+ if (rawValue === undefined) continue;
+
+ // Handle array values from URL (Next.js can pass arrays)
+ const strValue = Array.isArray(rawValue) ? rawValue.join(",") : rawValue;
+
+ const parsed = (fieldBuilder as FieldBuilder<unknown>)._config.parse(
+ strValue,
+ );
+ if (parsed !== null) {
+ result[key] = parsed;
+ }
+ }
+
+ return result as Partial<InferSchemaType<T>>;
+}
+
+/**
+ * Validate and coerce state, returning defaults for invalid values
+ */
+export function validateState<T extends SchemaDefinition>(
+ schema: T,
+ state: unknown,
+): InferSchemaType<T> {
+ const defaults = getSchemaDefaults(schema);
+
+ if (!state || typeof state !== "object") {
+ return defaults;
+ }
+
+ const result: Record<string, unknown> = { ...defaults };
+
+ for (const [key, fieldBuilder] of Object.entries(schema)) {
+ const value = (state as Record<string, unknown>)[key];
+ if (value === undefined) continue;
+
+ // Serialize and re-parse to validate
+ const config = (fieldBuilder as FieldBuilder<unknown>)._config;
+ const serialized = config.serialize(value);
+ const parsed = config.parse(serialized);
+
+ if (parsed !== null) {
+ result[key] = parsed;
+ }
+ // If invalid, default is already in result
+ }
+
+ return result as InferSchemaType<T>;
+}
+
+/**
+ * Merge partial state with defaults
+ */
+export function mergeWithDefaults<T extends SchemaDefinition>(
+ schema: T,
+ partial: Partial<InferSchemaType<T>>,
+): InferSchemaType<T> {
+ const defaults = getSchemaDefaults(schema);
+ return { ...defaults, ...partial };
+}
+
+/**
+ * Check if two states are equal (shallow comparison for primitives, deep for arrays)
+ */
+export function isStateEqual<T extends Record<string, unknown>>(
+ a: T,
+ b: T,
+): boolean {
+ const keysA = Object.keys(a);
+ const keysB = Object.keys(b);
+
+ if (keysA.length !== keysB.length) return false;
+
+ for (const key of keysA) {
+ const valA = a[key];
+ const valB = b[key];
+
+ if (valA === valB) continue;
+
+ // Handle arrays
+ if (Array.isArray(valA) && Array.isArray(valB)) {
+ if (valA.length !== valB.length) return false;
+ for (let i = 0; i < valA.length; i++) {
+ const itemA = valA[i];
+ const itemB = valB[i];
+ if (itemA instanceof Date && itemB instanceof Date) {
+ if (itemA.getTime() !== itemB.getTime()) return false;
+ } else if (itemA !== itemB) {
+ return false;
+ }
+ }
+ continue;
+ }
+
+ // Handle dates
+ if (valA instanceof Date && valB instanceof Date) {
+ if (valA.getTime() !== valB.getTime()) return false;
+ continue;
+ }
+
+ // Handle objects (sort field)
+ if (
+ valA !== null &&
+ valB !== null &&
+ typeof valA === "object" &&
+ typeof valB === "object"
+ ) {
+ const objA = valA as Record<string, unknown>;
+ const objB = valB as Record<string, unknown>;
+ if (!isStateEqual(objA, objB)) return false;
+ continue;
+ }
+
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Create a URL search string from state
+ */
+export function stateToSearchString<T extends SchemaDefinition>(
+ schema: T,
+ state: Partial<InferSchemaType<T>>,
+): string {
+ const serialized = serializeState(schema, state);
+ const params = new URLSearchParams();
+
+ for (const [key, value] of Object.entries(serialized)) {
+ if (value) {
+ params.set(key, value);
+ }
+ }
+
+ const str = params.toString();
+ return str ? `?${str}` : "";
+}
diff --git a/packages/ui/src/lib/data-table-filters/store/schema/types.ts b/packages/ui/src/lib/data-table-filters/store/schema/types.ts
new file mode 100644
index 000000000..165708df3
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/store/schema/types.ts
@@ -0,0 +1,100 @@
+export type PrimitiveType =
+ | "string"
+ | "number"
+ | "boolean"
+ | "timestamp"
+ | "stringLiteral";
+
+// Field configuration stored internally
+export interface FieldConfig<T> {
+ type: PrimitiveType | "array" | "sort";
+ defaultValue: T;
+ delimiter: string;
+ serialize: (value: T) => string;
+ parse: (value: string) => T | null;
+ // For stringLiteral type
+ literals?: readonly string[];
+ // For array type
+ itemConfig?: FieldConfig<unknown>;
+ /**
+ * Set when the caller overrode serialize/parse, so adapters bridge to those
+ * instead of the built-in parser for the field type
+ * @internal
+ */
+ hasCustomTransform?: boolean;
+}
+
+// Field builder interface (fluent API)
+export interface FieldBuilder<T> {
+ /**
+ * Set the default value for this field
+ */
+ default(value: T): FieldBuilder<T>;
+
+ /**
+ * Set the delimiter for serialization (used for arrays)
+ */
+ delimiter(separator: string): FieldBuilder<T>;
+
+ /**
+ * Custom serialization function
+ */
+ serialize(fn: (value: T) => string): FieldBuilder<T>;
+
+ /**
+ * Custom parse function
+ */
+ parse(fn: (value: string) => T | null): FieldBuilder<T>;
+
+ /**
+ * Internal config - do not use directly
+ * @internal
+ */
+ readonly _config: FieldConfig<T>;
+}
+
+// Schema definition as a record of field builders
+
+export type SchemaDefinition = Record<string, FieldBuilder<any>>;
+
+// Infer the TypeScript type from a schema definition
+export type InferSchemaType<T extends SchemaDefinition> = {
+ [K in keyof T]: T[K] extends FieldBuilder<infer U> ? U : never;
+};
+
+// Schema object returned by createSchema
+export interface Schema<T extends SchemaDefinition> {
+ /**
+ * The raw schema definition
+ */
+ readonly definition: T;
+
+ /**
+ * Get default values for all fields
+ */
+ readonly defaults: InferSchemaType<T>;
+
+ /**
+ * Inferred TypeScript type (for type inference only)
+ */
+ readonly _type: InferSchemaType<T>;
+}
+
+// Store snapshot with version for change detection
+export interface StoreSnapshot<T> {
+ state: T;
+ version: number;
+}
+
+// Adapter options passed during creation
+export interface AdapterOptions {
+ /**
+ * Unique ID for this table (required for multi-table support)
+ */
+ id: string;
+
+ /**
+ * Initial state to override defaults
+ */
+ initialState?: Record<string, unknown>;
+}
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/col.ts b/packages/ui/src/lib/data-table-filters/table-schema/col.ts
new file mode 100644
index 000000000..ecaeeb0fb
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/col.ts
@@ -0,0 +1,576 @@
+import type {
+ DatePreset,
+ Option,
+} from "@openstatus/ui/components/data-table-filters/types";
+
+import type {
+ ColBuilder,
+ ColKind,
+ ColRenderers,
+ ColumnDescriptor,
+ ColumnDescriptorCommon,
+ DatePresetDescriptor,
+ DisplayDescriptor,
+ FilterDescriptor,
+ FilterType,
+ OptionDescriptor,
+ Provenance,
+ ResolvedColumn,
+ ResolvedColumnEntry,
+ SheetConfig,
+ TableSchemaDefinition,
+} from "./types";
+
+// ── Per-kind defaults — the ONE definition ──────────────────────────────────
+
+/**
+ * The default cell display for a column kind.
+ *
+ * This is the single definition. `infer.ts`, `generators/sheet-fields.ts`, and
+ * `serialize.ts` each used to carry their own copy, and the third disagreed
+ * with the other two.
+ */
+export function defaultDisplayForKind(kind: ColKind): DisplayDescriptor {
+ switch (kind) {
+ case "number":
+ return { type: "number" };
+ case "boolean":
+ case "select":
+ return { type: "boolean" };
+ case "timestamp":
+ return { type: "timestamp" };
+ case "enum":
+ case "array":
+ return { type: "badge" };
+ case "string":
+ case "record":
+ return { type: "text" };
+ }
+}
+
+const MANUAL: Provenance = { source: "manual" };
+
+/**
+ * Drop keys whose value is `undefined`.
+ *
+ * Descriptors have to be canonical: `JSON.stringify` erases an explicit
+ * `undefined`, so a descriptor carrying one compares unequal to its own round
+ * trip under `toStrictEqual` and under any key-based comparison, while looking
+ * identical through `JSON`. `display("number", { unit: undefined })` — which
+ * `col.presets.duration()` produces whenever no unit is given — is the case
+ * that actually occurs.
+ *
+ * Exported for `infer.ts`, which builds descriptors outside the builder and so
+ * has to hold the same invariant.
+ */
+export function compact<T extends Record<string, unknown>>(object: T): T {
+ const result = {} as Record<string, unknown>;
+ for (const [key, value] of Object.entries(object)) {
+ if (value !== undefined) result[key] = value;
+ }
+ return result as T;
+}
+
+/**
+ * Strip caller-supplied `Option`s down to their serializable fields.
+ *
+ * `Option.value` is `string | boolean | number | undefined`, but an option with
+ * no value cannot be selected, cannot be encoded into filter state, and would
+ * vanish from the descriptor on `JSON.stringify` — so it is dropped here,
+ * at construction, rather than disappearing later at serialization time.
+ */
+function toOptionDescriptors(options: readonly Option[]): OptionDescriptor[] {
+ const result: OptionDescriptor[] = [];
+ for (const option of options) {
+ if (option.value === undefined) continue;
+ result.push({ label: option.label, value: option.value });
+ }
+ return result;
+}
+
+/** Store preset bounds as ISO instants so they survive JSON. */
+function toPresetDescriptor(preset: DatePreset): DatePresetDescriptor {
+ return {
+ label: preset.label,
+ shortcut: preset.shortcut,
+ from: preset.from.toISOString(),
+ to: preset.to.toISOString(),
+ };
+}
+
+/** Revive a serialized preset back into the `DatePreset` the UI consumes. */
+export function fromPresetDescriptor(
+ descriptor: DatePresetDescriptor,
+): DatePreset {
+ return {
+ label: descriptor.label,
+ shortcut: descriptor.shortcut,
+ from: new Date(descriptor.from),
+ to: new Date(descriptor.to),
+ };
+}
+
+// ── The builder ─────────────────────────────────────────────────────────────
+
+/**
+ * Build a `ColBuilder` over an explicit descriptor + renderers pair.
+ *
+ * Exported because `deserializeSchema` reconstructs builders by handing a
+ * descriptor straight back — no per-field replay of the fluent chain.
+ */
+export function createColBuilder<T, F extends FilterType = FilterType>(
+ descriptor: ColumnDescriptor,
+ renderers: ColRenderers = {},
+): ColBuilder<T, F> {
+ // The implementation uses loose parameter types to satisfy all overload
+ // signatures at once. TypeScript enforces the constraints at call sites
+ // via the ColBuilder<T, F> interface overloads, not here.
+ const next = <U, G extends FilterType>(
+ patch: Partial<ColumnDescriptor>,
+ rendererPatch?: ColRenderers,
+ ): ColBuilder<U, G> =>
+ createColBuilder<U, G>(
+ { ...descriptor, ...patch } as ColumnDescriptor,
+ rendererPatch ? compact({ ...renderers, ...rendererPatch }) : renderers,
+ );
+
+ /** Return `renderers` without the named closures. */
+ const withoutRenderers = (...keys: (keyof ColRenderers)[]): ColRenderers => {
+ const result = { ...renderers };
+ for (const key of keys) delete result[key];
+ return result;
+ };
+
+ const builder = {
+ get _descriptor() {
+ return descriptor;
+ },
+
+ get _renderers() {
+ return renderers;
+ },
+
+ label(text: string): ColBuilder<T, F> {
+ return next<T, F>({ label: text });
+ },
+
+ description(text: string): ColBuilder<T, F> {
+ return next<T, F>({ description: text });
+ },
+
+ display(type: string, options?: Record<string, unknown>): ColBuilder<T, F> {
+ // "custom" is not a descriptor state — the closure goes to the renderers
+ // half and the descriptor keeps whatever serializable display it had, so
+ // it is already the correct fallback for the sheet and for toJSON().
+ if (type === "custom") {
+ const { cell, colorMap } = options as {
+ cell: ColRenderers["cell"];
+ colorMap?: Record<string, string>;
+ };
+ return next<T, F>(
+ colorMap
+ ? {
+ display: {
+ ...descriptor.display,
+ colorMap,
+ } as DisplayDescriptor,
+ }
+ : {},
+ { cell },
+ );
+ }
+ const display = compact(
+ options ? { type, ...options } : { type },
+ ) as DisplayDescriptor;
+ // Selecting a built-in display drops any custom cell closure — otherwise
+ // it keeps winning in `generateColumns`, which checks renderers first.
+ return createColBuilder<T, F>(
+ { ...descriptor, display },
+ withoutRenderers("cell"),
+ );
+ },
+
+ filterable(
+ type?: string,
+ options?: Record<string, unknown>,
+ ): ColBuilder<T, F> {
+ const filterType = (type ||
+ descriptor.filter?.type ||
+ "input") as FilterType;
+ const existing = descriptor.filter;
+ const sameType = filterType === existing?.type;
+ const {
+ component,
+ options: rawOptions,
+ presets: rawPresets,
+ ...rest
+ } = (options ?? {}) as {
+ component?: ColRenderers["filterComponent"];
+ options?: Option[];
+ presets?: DatePreset[];
+ min?: number;
+ max?: number;
+ unit?: string;
+ };
+
+ const filter: FilterDescriptor = {
+ type: filterType,
+ defaultOpen: existing?.defaultOpen ?? false,
+ commandDisabled: existing?.commandDisabled ?? false,
+ // Preserve auto-derived options when the filter type stays the same
+ // and no explicit options are provided by the caller.
+ ...(sameType && existing?.options ? { options: existing.options } : {}),
+ ...compact(rest),
+ ...(rawOptions ? { options: toOptionDescriptors(rawOptions) } : {}),
+ ...(rawPresets
+ ? { presets: rawPresets.map(toPresetDescriptor) }
+ : sameType && existing?.presets
+ ? { presets: existing.presets }
+ : {}),
+ };
+ return next<T, F>(
+ { filter },
+ component ? { filterComponent: component } : undefined,
+ );
+ },
+
+ notFilterable(): ColBuilder<T, never> {
+ return createColBuilder<T, never>(
+ { ...descriptor, filter: null },
+ // The filter component is meaningless without a filter.
+ withoutRenderers("filterComponent"),
+ );
+ },
+
+ defaultOpen(): ColBuilder<T, F> {
+ if (!descriptor.filter) return next<T, F>({});
+ return next<T, F>({
+ filter: { ...descriptor.filter, defaultOpen: true },
+ });
+ },
+
+ commandDisabled(): ColBuilder<T, F> {
+ if (!descriptor.filter) return next<T, F>({});
+ return next<T, F>({
+ filter: { ...descriptor.filter, commandDisabled: true },
+ });
+ },
+
+ hidden(): ColBuilder<T, F> {
+ return next<T, F>({ hidden: true });
+ },
+
+ hideHeader(): ColBuilder<T, F> {
+ return next<T, F>({ hideHeader: true });
+ },
+
+ resizable(): ColBuilder<T, F> {
+ return next<T, F>({ resizable: true });
+ },
+
+ size(px: number): ColBuilder<T, F> {
+ return next<T, F>({ size: px });
+ },
+
+ sortable(): ColBuilder<T, F> {
+ return next<T, F>({ sortable: true });
+ },
+
+ optional(): ColBuilder<T | undefined, F> {
+ return next<T | undefined, F>({ optional: true });
+ },
+
+ sheet(sheetConfig?: SheetConfig): ColBuilder<T, F> {
+ const { component, condition, ...sheetDescriptor } = sheetConfig ?? {};
+ return next<T, F>(
+ { sheet: compact(sheetDescriptor) },
+ compact({ sheetComponent: component, sheetCondition: condition }),
+ );
+ },
+
+ sheetOnly(): ColBuilder<T, never> {
+ return createColBuilder<T, never>(
+ {
+ ...descriptor,
+ hidden: true,
+ filter: null,
+ enableHiding: false,
+ },
+ withoutRenderers("filterComponent"),
+ );
+ },
+ } as ColBuilder<T, F>;
+
+ return builder;
+}
+
+/**
+ * Attach provenance to a builder.
+ *
+ * Internal to this package — `col.presets.*` records which preset produced the
+ * column and with what arguments, and `infer.ts` records which heuristic fired.
+ * `schemaToTypeScript` reads this instead of pattern-matching the descriptor.
+ */
+export function withProvenance<T, F extends FilterType>(
+ builder: ColBuilder<T, F>,
+ provenance: Provenance,
+): ColBuilder<T, F> {
+ return createColBuilder<T, F>(
+ { ...builder._descriptor, provenance },
+ builder._renderers,
+ );
+}
+
+// ── The public read model ───────────────────────────────────────────────────
+
+/**
+ * Read a column's complete state — both halves — through one public accessor.
+ *
+ * Prefer this over reaching into `_descriptor` / `_renderers`, which are
+ * `@internal` and may change shape.
+ */
+// `any` on the filter-type parameter: callers hold builders of every filter
+// type at once, and the read model does not depend on which one it is.
+export function resolveColumn(
+ builder: ColBuilder<unknown, any>,
+): ResolvedColumn {
+ return { ...builder._descriptor, renderers: builder._renderers };
+}
+
+/** `resolveColumn` over a whole definition, preserving key insertion order. */
+export function resolveColumns(
+ definition: TableSchemaDefinition,
+): ResolvedColumnEntry[] {
+ return Object.entries(definition).map(([key, builder]) => ({
+ key,
+ ...resolveColumn(builder),
+ }));
+}
+
+// ── Factories ───────────────────────────────────────────────────────────────
+
+/** The descriptor every `col.*` factory starts from, before kind-specific bits. */
+function base(kind: ColKind): ColumnDescriptorCommon {
+ return {
+ optional: false,
+ label: "",
+ display: defaultDisplayForKind(kind),
+ hidden: false,
+ enableHiding: true,
+ hideHeader: false,
+ resizable: false,
+ sortable: false,
+ filter: null,
+ sheet: null,
+ provenance: MANUAL,
+ };
+}
+
+/**
+ * A string column.
+ *
+ * - Data type: `string`
+ * - Default display: `"text"` (plain text with overflow tooltip)
+ * - Default filter: `"input"` (text search)
+ * - Allowed filters: `"input"`
+ *
+ * @example
+ * col.string().label("Host").size(125).sheet()
+ * col.string().label("Message").notFilterable().optional().hidden()
+ */
+function string(): ColBuilder<string, "input"> {
+ return createColBuilder<string, "input">({
+ ...base("string"),
+ kind: "string",
+ filter: { type: "input", defaultOpen: false, commandDisabled: false },
+ });
+}
+
+/**
+ * A numeric column.
+ *
+ * - Data type: `number`
+ * - Default display: `"number"` (formatted, with optional unit)
+ * - Default filter: `"input"` (exact match)
+ * - Allowed filters: `"input"` | `"slider"` | `"checkbox"`
+ * - Use `"slider"` for continuous values (latency, file size)
+ * - Use `"checkbox"` for discrete values (HTTP status codes, port numbers)
+ *
+ * @example
+ * col.number().label("Latency").display("number", { unit: "ms" }).filterable("slider", { min: 0, max: 5000 }).sortable()
+ * col.number().label("Status").filterable("checkbox", { options: [{ label: "200", value: 200 }] })
+ */
+function number(): ColBuilder<number, "input" | "slider" | "checkbox"> {
+ return createColBuilder<number, "input" | "slider" | "checkbox">({
+ ...base("number"),
+ kind: "number",
+ filter: { type: "input", defaultOpen: false, commandDisabled: false },
+ });
+}
+
+/**
+ * A boolean column.
+ *
+ * - Data type: `boolean`
+ * - Default display: `"boolean"` (checkmark / dash icon)
+ * - Default filter: `"checkbox"` with `true` / `false` options pre-wired
+ * - Allowed filters: `"checkbox"`
+ *
+ * @example
+ * col.boolean().label("Cache Hit").defaultOpen()
+ */
+function boolean(): ColBuilder<boolean, "checkbox"> {
+ return createColBuilder<boolean, "checkbox">({
+ ...base("boolean"),
+ kind: "boolean",
+ filter: {
+ type: "checkbox",
+ defaultOpen: false,
+ commandDisabled: false,
+ options: [
+ { label: "true", value: true },
+ { label: "false", value: false },
+ ],
+ },
+ });
+}
+
+/**
+ * A timestamp column.
+ *
+ * - Data type: `Date`
+ * - Default display: `"timestamp"` (relative time, absolute datetime on hover)
+ * - Default filter: `"timerange"` (date range picker)
+ * - Allowed filters: `"timerange"`
+ *
+ * @example
+ * col.timestamp().label("Date").sortable().commandDisabled().size(200).sheet()
+ */
+function timestamp(): ColBuilder<Date, "timerange"> {
+ return createColBuilder<Date, "timerange">({
+ ...base("timestamp"),
+ kind: "timestamp",
+ filter: { type: "timerange", defaultOpen: false, commandDisabled: true },
+ });
+}
+
+/**
+ * An enum column from a `readonly string[]` union.
+ *
+ * - Data type: `T[number]` (union of the provided string literals)
+ * - Default display: `"badge"` (colored chip)
+ * - Default filter: `"checkbox"` with options auto-derived from `values`
+ * - Allowed filters: `"checkbox"`
+ *
+ * Checkbox options are auto-derived from `values` by default. Override them via
+ * `.filterable("checkbox", { options: [...] })` when you need custom labels,
+ * icons, or a subset of values.
+ *
+ * @param values - `as const` array of allowed string values
+ *
+ * @example
+ * col.enum(LEVELS).label("Level").defaultOpen()
+ * col.enum(LEVELS).label("Level").filterable("checkbox", {
+ * options: LEVELS.map(v => ({ label: v, value: v })), // override labels
+ * })
+ */
+function colEnum<T extends readonly string[]>(
+ values: T,
+): ColBuilder<T[number], "checkbox"> {
+ return createColBuilder<T[number], "checkbox">({
+ ...base("enum"),
+ kind: "enum",
+ enumValues: values,
+ filter: {
+ type: "checkbox",
+ defaultOpen: false,
+ commandDisabled: false,
+ options: Array.from(values).map((v) => ({ label: v, value: v })),
+ },
+ });
+}
+
+/**
+ * An array column, typically used for multi-value enum fields.
+ *
+ * - Data type: `U[]` where `U` is the item builder's type
+ * - Default display: `"badge"` (colored chip per value)
+ * - Default filter: `"checkbox"`
+ * - Allowed filters: `"checkbox"`
+ *
+ * Most commonly used as `col.array(col.enum(values))` for tags / regions / labels.
+ * `col.array(col.string())` is equally valid — the item type is recorded, so a
+ * `string[]` column stays a `string[]` column across a JSON round trip.
+ *
+ * @param itemBuilder - A `ColBuilder` describing the array item type
+ *
+ * @example
+ * col.array(col.enum(REGIONS)).label("Regions").filterable("checkbox", {
+ * options: REGIONS.map(r => ({ label: r, value: r })),
+ * })
+ */
+function array<U>(
+ itemBuilder: ColBuilder<U, any>,
+): ColBuilder<U[], "checkbox"> {
+ return createColBuilder<U[], "checkbox">({
+ ...base("array"),
+ kind: "array",
+ arrayItem: itemBuilder._descriptor,
+ filter: { type: "checkbox", defaultOpen: false, commandDisabled: false },
+ });
+}
+
+/**
+ * A key-value record column.
+ *
+ * - Data type: `Record<string, string>`
+ * - Default display: `"text"`
+ * - Not filterable (`F = never`)
+ *
+ * Use for metadata maps, HTTP headers, environment variables, etc.
+ * Typically rendered with a custom sheet component (key-value table / tabs).
+ *
+ * @example
+ * col.record().label("Headers").hidden().sheet({
+ * component: (row) => <KVTabs data={row.headers} />,
+ * className: "flex-col items-start w-full gap-1",
+ * })
+ */
+function record(): ColBuilder<Record<string, string>, never> {
+ return createColBuilder<Record<string, string>, never>({
+ ...base("record"),
+ kind: "record",
+ });
+}
+
+/**
+ * A row-selection checkbox column.
+ *
+ * - Data type: `boolean` (selected state)
+ * - Not filterable (`F = never`)
+ * - Not shown in sheet or filters
+ * - Renders a checkbox in both the header (select all) and each row
+ *
+ * @example
+ * col.select().label("Select")
+ */
+function select(): ColBuilder<boolean, never> {
+ return createColBuilder<boolean, never>({
+ ...base("select"),
+ kind: "select",
+ label: "Select",
+ enableHiding: false,
+ size: 40,
+ });
+}
+
+export const col = {
+ string,
+ number,
+ boolean,
+ timestamp,
+ enum: colEnum,
+ array,
+ record,
+ select,
+};
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/generators/columns.tsx b/packages/ui/src/lib/data-table-filters/table-schema/generators/columns.tsx
new file mode 100644
index 000000000..550bcdabb
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/generators/columns.tsx
@@ -0,0 +1,327 @@
+"use client";
+
+import {
+ DataTableCellBadge,
+ DataTableCellBar,
+ DataTableCellBoolean,
+ DataTableCellCode,
+ DataTableCellGauge,
+ DataTableCellHeatmap,
+ DataTableCellLevelIndicator,
+ DataTableCellNumber,
+ DataTableCellStar,
+ DataTableCellStatusCode,
+ DataTableCellText,
+ DataTableCellTimestamp,
+} from "@openstatus/ui/components/data-table-filters/data-table-cell/index";
+import { DataTableColumnHeader } from "@openstatus/ui/components/data-table-filters/data-table-column-header";
+import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
+import {
+ defineFilters,
+ getValueAtKey,
+} from "@openstatus/ui/lib/data-table-filters/filters/index";
+import type { ColumnDef } from "@tanstack/react-table";
+import type { JSX } from "react";
+
+import { resolveColumns } from "../col";
+import type { DisplayDescriptor, TableSchemaDefinition } from "../types";
+
+/**
+ * Render the cell based on the display config.
+ */
+function renderCell(
+ display: DisplayDescriptor,
+ value: unknown,
+ context?: { min: number; max: number },
+): JSX.Element | null {
+ const fallback = <DataTableCellText value={String(value ?? "")} />;
+ const colorMap = "colorMap" in display ? display.colorMap : undefined;
+ switch (display.type) {
+ case "text": {
+ const hex = colorMap?.[String(value)];
+ return typeof value === "string" || typeof value === "number" ? (
+ <DataTableCellText value={value} color={hex} />
+ ) : (
+ fallback
+ );
+ }
+ case "code": {
+ const hex = colorMap?.[String(value)];
+ return typeof value === "string" || typeof value === "number" ? (
+ <DataTableCellCode value={value} color={hex} />
+ ) : (
+ fallback
+ );
+ }
+ case "number": {
+ const hex = colorMap?.[String(value)];
+ return typeof value === "number" ? (
+ <DataTableCellNumber value={value} unit={display.unit} color={hex} />
+ ) : (
+ fallback
+ );
+ }
+ case "timestamp": {
+ const hex = colorMap?.[String(value)];
+ return value instanceof Date ||
+ typeof value === "string" ||
+ typeof value === "number" ? (
+ <DataTableCellTimestamp date={value} color={hex} />
+ ) : (
+ fallback
+ );
+ }
+ case "badge": {
+ if (Array.isArray(value)) {
+ return (
+ <div className="flex-no-wrap flex gap-1">
+ {value.map((item, i) => (
+ <DataTableCellBadge
+ key={i}
+ value={item}
+ color={colorMap?.[String(item)]}
+ />
+ ))}
+ </div>
+ );
+ }
+ const hex = colorMap?.[String(value)];
+ return typeof value === "string" || typeof value === "number" ? (
+ <DataTableCellBadge value={value} color={hex} />
+ ) : (
+ fallback
+ );
+ }
+ case "boolean": {
+ const hex = colorMap?.[String(value)];
+ return typeof value === "boolean" ? (
+ <DataTableCellBoolean value={value} color={hex} />
+ ) : (
+ fallback
+ );
+ }
+ case "star": {
+ return typeof value === "boolean" ? (
+ <DataTableCellStar value={value} />
+ ) : (
+ fallback
+ );
+ }
+ case "status-code": {
+ const hex = colorMap?.[String(value)];
+ return typeof value === "number" ? (
+ <DataTableCellStatusCode value={value} color={hex} />
+ ) : (
+ fallback
+ );
+ }
+ case "level-indicator": {
+ const hex = colorMap?.[String(value)];
+ return typeof value === "string" ? (
+ <DataTableCellLevelIndicator value={value} color={hex} />
+ ) : (
+ fallback
+ );
+ }
+ case "heatmap": {
+ const { min = 0, max = 100 } = context ?? {};
+ return typeof value === "number" ? (
+ <DataTableCellHeatmap
+ value={value}
+ min={min}
+ max={max}
+ unit={display.unit}
+ color={display.color}
+ />
+ ) : (
+ fallback
+ );
+ }
+ case "bar": {
+ const { min = 0, max = 100 } = context ?? {};
+ return typeof value === "number" ? (
+ <DataTableCellBar
+ value={value}
+ min={min}
+ max={max}
+ unit={display.unit}
+ color={display.color}
+ />
+ ) : (
+ fallback
+ );
+ }
+ case "gauge": {
+ const { min = 0, max = 100 } = context ?? {};
+ return typeof value === "number" ? (
+ <DataTableCellGauge
+ value={value}
+ min={min}
+ max={max}
+ unit={display.unit}
+ color={display.color}
+ />
+ ) : (
+ fallback
+ );
+ }
+ }
+}
+
+/**
+ * Generate ColumnDef[] from a table schema definition.
+ *
+ * Rules:
+ * - Dotted keys (e.g. "timing.dns") → id + accessorFn
+ * - Non-dotted keys → accessorKey
+ * - Sortable columns get DataTableColumnHeader; others get a plain string header
+ * - filterFn comes from the shared filter-semantics module
+ * - Cell renders via built-in display components or the "custom" cell function
+ * - meta.label is always set; meta.hidden reflects .hidden() calls
+ *
+ * Composite/virtual columns that span multiple fields must be appended manually:
+ * @example
+ * ```ts
+ * const columns = [
+ * ...generateColumns(tableSchema),
+ * { id: "timing", header: ..., cell: ..., size: 130 },
+ * ];
+ * ```
+ */
+export function generateColumns<TData>(
+ schema: TableSchemaDefinition,
+): ColumnDef<TData>[] {
+ // One interpretation of filter semantics, shared with the SQL and in-memory
+ // engines. `filterFn` returns a *function*, so the consuming table no longer
+ // has to register `filterFns: { inDateRange, arrSome }` — a contract that was
+ // undocumented outside a comment and silently broke filtering when missed.
+ const filters = defineFilters(schema);
+
+ return resolveColumns(schema).map((config) => {
+ const { key } = config;
+
+ // Select column — checkbox header + cell
+ if (config.kind === "select") {
+ return {
+ id: key,
+ header: ({ table }) => (
+ <div className="flex items-center justify-center">
+ <Checkbox
+ checked={
+ table.getIsAllPageRowsSelected() ||
+ (table.getIsSomePageRowsSelected() && "indeterminate")
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ aria-label="Select all"
+ className="shadow-none"
+ />
+ </div>
+ ),
+ cell: ({ row }) => (
+ <div
+ className="flex items-center justify-center"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ aria-label="Select row"
+ className="shadow-none"
+ />
+ </div>
+ ),
+ enableSorting: false,
+ enableHiding: false,
+ enableResizing: false,
+ ...(config.size !== undefined
+ ? { size: config.size, minSize: config.size, maxSize: config.size }
+ : {}),
+ meta: { label: config.label, kind: "select", hidden: config.hidden },
+ } as ColumnDef<TData>;
+ }
+
+ const isDotted = key.includes(".");
+ const filterFn = filters.filterFn(key);
+
+ const header = config.hideHeader
+ ? () => <span className="sr-only">{config.label}</span>
+ : config.sortable
+ ? ({
+ column,
+ }: {
+ column: Parameters<typeof DataTableColumnHeader>[0]["column"];
+ }) => <DataTableColumnHeader column={column} title={config.label} />
+ : config.label;
+
+ const needsMinMax =
+ config.display.type === "heatmap" ||
+ config.display.type === "bar" ||
+ config.display.type === "gauge";
+
+ const customCell = config.renderers.cell;
+
+ const cell = ({
+ getValue,
+ row,
+ column,
+ }: {
+ getValue: () => unknown;
+ row: { original: TData };
+ column: { getFacetedMinMaxValues?: () => [number, number] | undefined };
+ }) => {
+ // A custom renderer overrides the descriptor's display. The descriptor
+ // still carries a real display type, which is what the sheet and
+ // `toJSON()` fall back to.
+ if (customCell) return customCell(getValue(), row.original);
+ if (needsMinMax) {
+ const display = config.display as {
+ min?: number;
+ max?: number;
+ };
+ const faceted = column.getFacetedMinMaxValues?.();
+ const min = faceted?.[0] ?? display.min ?? 0;
+ const max = faceted?.[1] ?? display.max ?? 100;
+ return renderCell(config.display, getValue(), { min, max });
+ }
+ return renderCell(config.display, getValue());
+ };
+
+ const meta = {
+ label: config.label,
+ hidden: config.hidden,
+ kind: config.kind,
+ };
+
+ const base = {
+ header,
+ cell,
+ enableResizing: config.resizable,
+ ...(config.enableHiding === false ? { enableHiding: false } : {}),
+ ...(filterFn ? { filterFn } : {}),
+ ...(config.size !== undefined
+ ? {
+ size: config.size,
+ ...(config.resizable ? {} : { minSize: config.size }),
+ }
+ : {}),
+ meta,
+ };
+
+ if (isDotted) {
+ return {
+ ...base,
+ id: key,
+ // Same reader as the filter engine: a flat `"timing.dns"` key wins,
+ // a nested `{ timing: { dns } }` row is walked.
+ accessorFn: (row: TData) => getValueAtKey(row, key),
+ } as ColumnDef<TData>;
+ }
+
+ return {
+ ...base,
+ accessorKey: key,
+ } as ColumnDef<TData>;
+ });
+}
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/generators/filter-fields.ts b/packages/ui/src/lib/data-table-filters/table-schema/generators/filter-fields.ts
new file mode 100644
index 000000000..39303e454
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/generators/filter-fields.ts
@@ -0,0 +1,90 @@
+import type { DataTableFilterField } from "@openstatus/ui/components/data-table-filters/types";
+
+import { fromPresetDescriptor, resolveColumns } from "../col";
+import type { TableSchemaDefinition } from "../types";
+
+/**
+ * Generate DataTableFilterField[] from a table schema definition.
+ *
+ * Only includes fields where filter !== null.
+ * Order follows schema definition order (JS object key insertion order).
+ *
+ * Options for checkbox fields are auto-derived from col.enum(values) or
+ * col.boolean() if not explicitly provided via filterable("checkbox", { options }).
+ */
+export function generateFilterFields<TData>(
+ schema: TableSchemaDefinition,
+): DataTableFilterField<TData>[] {
+ const result: DataTableFilterField<TData>[] = [];
+
+ for (const config of resolveColumns(schema)) {
+ const { key, filter, label, kind } = config;
+ if (!filter) continue;
+
+ const base = {
+ label,
+ value: key as keyof TData,
+ defaultOpen: filter.defaultOpen || undefined,
+ commandDisabled: filter.commandDisabled || undefined,
+ };
+
+ switch (filter.type) {
+ case "input": {
+ result.push({ ...base, type: "input" });
+ break;
+ }
+ case "timerange": {
+ result.push({
+ ...base,
+ type: "timerange",
+ presets: filter.presets?.map(fromPresetDescriptor),
+ });
+ break;
+ }
+ case "checkbox": {
+ // Derive options if not explicitly provided
+ let options = filter.options;
+ if (!options) {
+ if (config.kind === "enum") {
+ options = config.enumValues.map((v) => ({ label: v, value: v }));
+ } else if (kind === "boolean") {
+ options = [
+ { label: "Yes", value: true },
+ { label: "No", value: false },
+ ];
+ } else if (
+ config.kind === "array" &&
+ config.arrayItem.kind === "enum"
+ ) {
+ options = config.arrayItem.enumValues.map((v) => ({
+ label: v,
+ value: v,
+ }));
+ }
+ }
+ result.push({
+ ...base,
+ type: "checkbox",
+ options,
+ keepEmptyOptions: filter.keepEmptyOptions || undefined,
+ component: config.renderers.filterComponent,
+ });
+ break;
+ }
+ case "slider": {
+ const displayUnit =
+ "unit" in config.display ? config.display.unit : undefined;
+ result.push({
+ ...base,
+ type: "slider",
+ min: filter.min ?? 0,
+ max: filter.max ?? 100,
+ unit: filter.unit ?? displayUnit,
+ });
+ break;
+ }
+ }
+ }
+
+ return result;
+}
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/generators/filter-schema.ts b/packages/ui/src/lib/data-table-filters/table-schema/generators/filter-schema.ts
new file mode 100644
index 000000000..0d0d2e808
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/generators/filter-schema.ts
@@ -0,0 +1,188 @@
+import {
+ ARRAY_DELIMITER,
+ RANGE_DELIMITER,
+ SLIDER_DELIMITER,
+} from "@openstatus/ui/lib/data-table-filters/delimiters";
+import {
+ createSchema,
+ field,
+} from "@openstatus/ui/lib/data-table-filters/store/schema/index";
+import type {
+ FieldBuilder,
+ Schema,
+ SchemaDefinition,
+} from "@openstatus/ui/lib/data-table-filters/store/schema/index";
+
+import { resolveColumns } from "../col";
+import type { ColBuilder, TableSchemaDefinition } from "../types";
+
+/**
+ * Extract keys from a TableSchemaDefinition where the column is filterable.
+ * A column is filterable when its filter type `F` is not `never`.
+ * Uses `[F] extends [never]` to avoid distribution issues with `any`.
+ */
+type FilterableKeys<T extends TableSchemaDefinition> = {
+ [K in keyof T]: T[K] extends ColBuilder<infer _T, infer F>
+ ? [F] extends [never]
+ ? never
+ : K
+ : never;
+}[keyof T];
+
+// Extract T and F separately — TS struggles to infer both at once from ColBuilder
+type GetColValue<B> = B extends ColBuilder<infer T, any> ? T : never;
+type GetColFilter<B> = B extends ColBuilder<any, infer F> ? F : never;
+
+/**
+ * Map a single ColBuilder to the correct FieldBuilder type based on its
+ * value type `T` and filter type `F`.
+ */
+type InferFilterFieldType<B> = [GetColFilter<B>] extends [never]
+ ? never
+ : GetColFilter<B> extends "input"
+ ? GetColValue<B> extends string
+ ? FieldBuilder<string | null>
+ : GetColValue<B> extends number
+ ? FieldBuilder<number | null>
+ : FieldBuilder<unknown>
+ : GetColFilter<B> extends "slider"
+ ? FieldBuilder<(number | null)[]>
+ : GetColFilter<B> extends "timerange"
+ ? FieldBuilder<(Date | null)[]>
+ : GetColFilter<B> extends "checkbox"
+ ? GetColValue<B> extends (infer U)[]
+ ? FieldBuilder<(U | null)[]>
+ : FieldBuilder<(GetColValue<B> | null)[]>
+ : FieldBuilder<unknown>;
+
+/** The generated filter definition — preserves the filterable keys from `T`. */
+type GeneratedFilterDef<T extends TableSchemaDefinition> = {
+ [K in FilterableKeys<T>]: InferFilterFieldType<T[K]>;
+};
+
+/**
+ * A numeric field that survives decimals.
+ *
+ * `field.number()` parses with `parseInt`, so a latency of `1.5` comes back
+ * from the URL as `1`. Numeric columns are continuous far more often than not,
+ * so every numeric filter branch uses this instead.
+ */
+function decimalNumber(): FieldBuilder<number | null> {
+ return field.number().parse((str) => {
+ if (str.trim() === "") return null;
+ const num = Number(str);
+ return Number.isFinite(num) ? num : null;
+ });
+}
+
+function buildFilterDefinition(
+ schema: TableSchemaDefinition,
+): SchemaDefinition {
+ const definition: SchemaDefinition = {};
+
+ for (const config of resolveColumns(schema)) {
+ const { key, kind, filter } = config;
+ if (!filter) continue;
+
+ switch (filter.type) {
+ case "input": {
+ if (kind === "string") {
+ definition[key] = field.string();
+ } else if (kind === "number") {
+ definition[key] = decimalNumber();
+ }
+ break;
+ }
+ case "checkbox": {
+ if (config.kind === "enum") {
+ definition[key] = field.array(field.stringLiteral(config.enumValues));
+ } else if (kind === "number") {
+ definition[key] = field
+ .array(decimalNumber())
+ .delimiter(ARRAY_DELIMITER);
+ } else if (kind === "boolean") {
+ definition[key] = field
+ .array(field.boolean())
+ .delimiter(ARRAY_DELIMITER);
+ } else if (
+ config.kind === "array" &&
+ config.arrayItem.kind === "enum"
+ ) {
+ definition[key] = field.array(
+ field.stringLiteral(config.arrayItem.enumValues),
+ );
+ } else if (config.kind === "array") {
+ // Non-enum array item — filter on the item's own scalar type.
+ definition[key] =
+ config.arrayItem.kind === "number"
+ ? field.array(decimalNumber()).delimiter(ARRAY_DELIMITER)
+ : field.array(field.string()).delimiter(ARRAY_DELIMITER);
+ }
+ break;
+ }
+ case "slider": {
+ definition[key] = field
+ .array(decimalNumber())
+ .delimiter(SLIDER_DELIMITER);
+ break;
+ }
+ case "timerange": {
+ definition[key] = field
+ .array(field.timestamp())
+ .delimiter(RANGE_DELIMITER);
+ break;
+ }
+ }
+ }
+
+ return definition;
+}
+
+/**
+ * Generate a BYOS filter schema from a table schema definition.
+ *
+ * Each filterable column maps to the appropriate field.* builder:
+ * - col.string() + input → field.string()
+ * - col.number() + input → field.number()
+ * - col.number() + slider → field.array(field.number()).delimiter(SLIDER_DELIMITER)
+ * - col.number() + checkbox → field.array(field.number()).delimiter(ARRAY_DELIMITER)
+ * - col.boolean() + checkbox → field.array(field.boolean()).delimiter(ARRAY_DELIMITER)
+ * - col.timestamp()+ timerange→ field.array(field.timestamp()).delimiter(RANGE_DELIMITER)
+ * - col.enum(v) + checkbox → field.array(field.stringLiteral(v))
+ * - col.array(col.enum(v)) + checkbox → field.array(field.stringLiteral(v))
+ *
+ * Every numeric field carries a decimal-safe parse — `field.number()` on its
+ * own truncates `1.5` to `1`.
+ *
+ * Non-filterable fields are excluded. Pass `extraFields` for pagination,
+ * sorting, and other non-filter state.
+ *
+ * @example
+ * ```ts
+ * // Without extra fields (filter fields only)
+ * const filterSchema = generateFilterSchema(tableSchema.definition);
+ *
+ * // With extra fields (recommended)
+ * const filterSchema = generateFilterSchema(tableSchema.definition, {
+ * sort: field.sort(),
+ * uuid: field.string(),
+ * live: field.boolean().default(false),
+ * size: field.number().default(40),
+ * });
+ * ```
+ */
+export function generateFilterSchema<T extends TableSchemaDefinition>(
+ schema: T,
+): Schema<GeneratedFilterDef<T>>;
+export function generateFilterSchema<
+ T extends TableSchemaDefinition,
+ E extends SchemaDefinition,
+>(schema: T, extraFields: E): Schema<GeneratedFilterDef<T> & E>;
+export function generateFilterSchema<
+ T extends TableSchemaDefinition,
+ E extends SchemaDefinition,
+>(schema: T, extraFields?: E) {
+ const generated = buildFilterDefinition(schema);
+ const merged = extraFields ? { ...generated, ...extraFields } : generated;
+ return createSchema(merged);
+}
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/generators/sheet-fields.ts b/packages/ui/src/lib/data-table-filters/table-schema/generators/sheet-fields.ts
new file mode 100644
index 000000000..48d4173b6
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/generators/sheet-fields.ts
@@ -0,0 +1,43 @@
+import type { SheetField } from "@openstatus/ui/components/data-table-filters/types";
+
+import { resolveColumns } from "../col";
+import type { TableSchemaDefinition } from "../types";
+
+/**
+ * Generate SheetField[] from a table schema definition.
+ *
+ * Only includes fields where sheet !== null (.sheet() was called).
+ * Sheet type is derived from the filter type, or "readonly" if not filterable.
+ * Sheet label falls back to the column label if not overridden in .sheet({ label }).
+ */
+export function generateSheetFields<TData>(
+ schema: TableSchemaDefinition,
+): SheetField<TData>[] {
+ const result: SheetField<TData>[] = [];
+
+ for (const config of resolveColumns(schema)) {
+ const sheetConfig = config.sheet;
+ if (sheetConfig === null) continue;
+
+ // Derive sheet type from filter type, or "readonly" if not filterable
+ const sheetType: SheetField<TData>["type"] =
+ config.filter?.type ?? "readonly";
+
+ result.push({
+ id: config.key as keyof TData,
+ label: sheetConfig.label ?? config.label,
+ type: sheetType,
+ // The descriptor's display is always a real serializable display, even
+ // when a custom cell renderer was supplied — no per-kind fallback needed.
+ display: config.display,
+ component: config.renderers
+ .sheetComponent as SheetField<TData>["component"],
+ condition: config.renderers
+ .sheetCondition as SheetField<TData>["condition"],
+ className: sheetConfig.className,
+ skeletonClassName: sheetConfig.skeletonClassName,
+ });
+ }
+
+ return result;
+}
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/index.ts b/packages/ui/src/lib/data-table-filters/table-schema/index.ts
new file mode 100644
index 000000000..ac9f8ce9b
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/index.ts
@@ -0,0 +1,153 @@
+import { col as _col, resolveColumns } from "./col";
+import { presets } from "./presets";
+import {
+ deserializeSchema,
+ migrateSchemaJSON,
+ serializeSchema,
+} from "./serialize";
+import { validateSchema } from "./validate";
+
+/**
+ * Column builder factories and presets for defining table schemas.
+ *
+ * **Primitive factories** — choose based on the data type of the column:
+ * - `col.string()` — text data (`string`)
+ * - `col.number()` — numeric data (`number`)
+ * - `col.boolean()` — boolean data (`boolean`)
+ * - `col.timestamp()` — date/time data (`Date`)
+ * - `col.enum(values)` — string union (`T[number]`)
+ * - `col.array(item)` — array of values (`U[]`)
+ * - `col.record()` — key-value map (`Record<string, string>`)
+ *
+ * **Presets** — pre-configured builders for common log table patterns:
+ * - `col.presets.logLevel(values)` — severity levels
+ * - `col.presets.httpMethod(values)` — HTTP verbs
+ * - `col.presets.httpStatus(codes?)` — HTTP status codes
+ * - `col.presets.duration(unit?, slider?)` — timing / latency
+ * - `col.presets.timestamp()` — sortable timestamp with timerange filter
+ * - `col.presets.traceId()` — trace / request ID (code display, not filterable)
+ * - `col.presets.pathname()` — URL path with text search
+ *
+ * @example
+ * ```ts
+ * import { col, createTableSchema } from "@openstatus/ui/lib/data-table-filters/table-schema/index";
+ *
+ * export const tableSchema = createTableSchema({
+ * level: col.presets.logLevel(LEVELS).description("Log severity"),
+ * date: col.presets.timestamp().label("Date").size(200).sheet(),
+ * latency: col.presets.duration("ms").label("Latency").sortable().size(110).sheet(),
+ * status: col.presets.httpStatus().label("Status").size(60),
+ * method: col.presets.httpMethod(METHODS).size(69),
+ * host: col.string().label("Host").size(125).sheet(),
+ * headers: col.record().label("Headers").hidden().sheet(),
+ * });
+ * ```
+ */
+export const col = { ..._col, presets };
+export type {
+ ColBuilder,
+ ColKind,
+ ColRenderers,
+ ColumnDescriptor,
+ ColumnDescriptorCommon,
+ DatePresetDescriptor,
+ DisplayConfig,
+ DisplayDescriptor,
+ FilterDescriptor,
+ FilterType,
+ InferTableType,
+ JsonValue,
+ OptionDescriptor,
+ Provenance,
+ ResolvedColumn,
+ ResolvedColumnEntry,
+ SchemaJSON,
+ SchemaJSONVersion,
+ SerializableDisplayConfig,
+ SheetConfig,
+ SheetDescriptor,
+ TableSchemaDefinition,
+} from "./types";
+export { resolveColumn, resolveColumns } from "./col";
+export { generateColumns } from "./generators/columns";
+export { generateFilterFields } from "./generators/filter-fields";
+export { generateFilterSchema } from "./generators/filter-schema";
+export { generateSheetFields } from "./generators/sheet-fields";
+export {
+ SCHEMA_JSON_VERSION,
+ deserializeSchema,
+ migrateSchemaJSON,
+ serializeSchema,
+} from "./serialize";
+
+/**
+ * Derive defaultColumnVisibility from the schema.
+ * Returns { [key]: false } for every column marked with .hidden().
+ */
+export function getDefaultColumnVisibility(
+ schema: import("./types").TableSchemaDefinition,
+): Record<string, boolean> {
+ const visibility: Record<string, boolean> = {};
+ for (const { key, hidden } of resolveColumns(schema)) {
+ if (hidden) visibility[key] = false;
+ }
+ return visibility;
+}
+
+/**
+ * Create a table schema from a map of col.* builders.
+ *
+ * The returned object holds the definition and exposes:
+ * - `toJSON()` — serializes the schema to a function-free JSON descriptor,
+ * suitable for AI agents, MCP tools, and `JSON.stringify`.
+ *
+ * Use `createTableSchema.fromJSON(json)` to reconstruct a schema from a
+ * JSON descriptor (e.g. one generated by an AI agent). Custom renderers
+ * (display.cell, filter.component, sheet.component) are not serialized and
+ * must be applied manually on top of the reconstructed builders.
+ *
+ * @example
+ * ```ts
+ * export const tableSchema = createTableSchema({
+ * level: col.enum(LEVELS).label("Level").defaultOpen().sheet(),
+ * date: col.timestamp().label("Date").sortable().size(200).sheet(),
+ * });
+ *
+ * export type ColumnSchema = InferTableType<typeof tableSchema.definition>;
+ *
+ * // Serialize for an AI agent or MCP tool
+ * const json = tableSchema.toJSON();
+ * // JSON.stringify(tableSchema) also works — toJSON() is called automatically
+ *
+ * // Reconstruct from AI-generated JSON
+ * const schema = createTableSchema.fromJSON(json);
+ * ```
+ */
+export function createTableSchema<
+ T extends import("./types").TableSchemaDefinition,
+>(definition: T): { definition: T; toJSON(): import("./types").SchemaJSON } {
+ validateSchema(definition);
+ return {
+ definition,
+ toJSON() {
+ return serializeSchema(definition);
+ },
+ };
+}
+
+/**
+ * Reconstruct a schema from a JSON descriptor.
+ *
+ * Takes `unknown` on purpose: the builder pastes user-typed text in here, and
+ * the cache replays JSON written by an older build. `migrateSchemaJSON` brings
+ * older versions forward and throws on anything unrecognisable, so the cast
+ * that used to sit on untrusted input is gone.
+ */
+createTableSchema.fromJSON = (
+ json: unknown,
+): {
+ definition: import("./types").TableSchemaDefinition;
+ toJSON(): import("./types").SchemaJSON;
+} => {
+ return createTableSchema(deserializeSchema(migrateSchemaJSON(json)));
+};
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/presets.ts b/packages/ui/src/lib/data-table-filters/table-schema/presets.ts
new file mode 100644
index 000000000..8cbe4dc4b
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/presets.ts
@@ -0,0 +1,315 @@
+import { col, withProvenance } from "./col";
+import type { ColBuilder, FilterType, JsonValue } from "./types";
+
+/**
+ * Tag a preset-built column so `schemaToTypeScript` can re-emit the exact call
+ * instead of reverse-engineering it from the descriptor's shape.
+ */
+function tag<T, F extends FilterType>(
+ preset: string,
+ args: readonly (JsonValue | undefined)[],
+ builder: ColBuilder<T, F>,
+): ColBuilder<T, F> {
+ // Trailing omitted args are dropped so the re-emitted call matches what the
+ // author wrote: `duration("ms")`, not `duration("ms", undefined)`. An omitted
+ // arg in the *middle* becomes `null`, which the emitter prints as `undefined`
+ // — `undefined` inside a JSON array does not survive `JSON.stringify`.
+ const trimmed = [...args];
+ while (trimmed.length > 0 && trimmed[trimmed.length - 1] === undefined) {
+ trimmed.pop();
+ }
+ return withProvenance(builder, {
+ source: "preset",
+ preset,
+ args: trimmed.map((a) => (a === undefined ? null : a)),
+ });
+}
+
+const DEFAULT_HTTP_STATUS_CODES = [
+ 200, 201, 204, 301, 302, 400, 401, 403, 404, 422, 429, 500, 502, 503, 504,
+];
+
+/**
+ * Pre-configured column builders for patterns common in log and observability tables.
+ *
+ * Every preset returns a `ColBuilder` with sensible defaults already applied.
+ * All builders remain fully customizable — chain additional methods to override
+ * any default (label, size, display, sheet, etc.).
+ *
+ * @example
+ * ```ts
+ * const tableSchema = createTableSchema({
+ * level: col.presets.logLevel(LEVELS).description("Log severity"),
+ * date: col.presets.timestamp().label("Date").size(200).sheet(),
+ * latency: col.presets.duration("ms").label("Latency").sortable().size(110).sheet(),
+ * status: col.presets.httpStatus().label("Status").size(60),
+ * method: col.presets.httpMethod(METHODS).size(69),
+ * path: col.presets.pathname().label("Path").size(130).sheet(),
+ * traceId: col.presets.traceId().label("Request ID").hidden().sheet(),
+ * });
+ * ```
+ */
+export const presets = {
+ /**
+ * A log severity level column.
+ *
+ * Defaults: enum + badge display + checkbox filter + `defaultOpen`.
+ * Checkbox options are auto-derived from `values` — no need to map them manually.
+ *
+ * @param values - The allowed severity levels, e.g. `["error", "warn", "info", "debug"] as const`
+ *
+ * @example
+ * ```ts
+ * col.presets.logLevel(LEVELS)
+ * .label("Level")
+ * .description("Log severity: error > warn > info > debug")
+ * .size(27)
+ * ```
+ */
+ logLevel<T extends readonly string[]>(
+ values: T,
+ ): ColBuilder<T[number], "checkbox"> {
+ return tag(
+ "logLevel",
+ [values as readonly string[]],
+ col
+ .enum(values)
+ .label("Level")
+ .filterable("checkbox", {
+ options: values.map((v) => ({ label: v, value: v })),
+ })
+ .defaultOpen(),
+ );
+ },
+
+ /**
+ * An HTTP method column.
+ *
+ * Defaults: enum + plain text display + checkbox filter.
+ * Options are auto-derived from `values`.
+ *
+ * @param values - The allowed HTTP methods, e.g. `["GET", "POST", "PUT", "DELETE"] as const`
+ *
+ * @example
+ * ```ts
+ * col.presets.httpMethod(METHODS).size(69)
+ * ```
+ */
+ httpMethod<T extends readonly string[]>(
+ values: T,
+ ): ColBuilder<T[number], "checkbox"> {
+ return tag(
+ "httpMethod",
+ [values as readonly string[]],
+ col
+ .enum(values)
+ .label("Method")
+ .display("text")
+ .filterable("checkbox", {
+ options: values.map((v) => ({ label: v, value: v })),
+ }),
+ );
+ },
+
+ /**
+ * An HTTP status code column.
+ *
+ * Defaults: number + checkbox filter with a standard set of common status codes.
+ * Pass a custom `codes` array to override the defaults.
+ *
+ * Default codes: 200, 201, 204, 301, 302, 400, 401, 403, 404, 422, 429, 500, 502, 503, 504
+ *
+ * @param codes - Override the default status code options
+ *
+ * @example
+ * ```ts
+ * col.presets.httpStatus().label("Status").size(60)
+ * col.presets.httpStatus([200, 400, 500]).label("Status") // custom codes
+ * ```
+ */
+ httpStatus(
+ codes?: number[],
+ ): ColBuilder<number, "input" | "slider" | "checkbox"> {
+ return tag(
+ "httpStatus",
+ [codes as readonly number[] | undefined],
+ col
+ .number()
+ .label("Status")
+ .filterable("checkbox", {
+ options: (codes ?? DEFAULT_HTTP_STATUS_CODES).map((code) => ({
+ label: String(code),
+ value: code,
+ })),
+ }),
+ );
+ },
+
+ /**
+ * A duration / latency / timing column.
+ *
+ * Defaults: number + formatted number display with unit + slider filter
+ * with bounds `{ min: 0, max: 5000 }`.
+ *
+ * @param unit - Unit label shown after the value, e.g. `"ms"`, `"s"`, `"µs"`
+ * @param slider - Override the slider bounds (default: `{ min: 0, max: 5000 }`)
+ *
+ * @example
+ * ```ts
+ * col.presets.duration("ms").label("Latency").sortable().size(110).sheet()
+ * col.presets.duration("s", { min: 0, max: 60 }).label("Response time")
+ * ```
+ */
+ duration(
+ unit?: string,
+ slider?: { min: number; max: number },
+ ): ColBuilder<number, "input" | "slider" | "checkbox"> {
+ return tag(
+ "duration",
+ [unit, slider],
+ col
+ .number()
+ .label("Duration")
+ .display("number", { unit })
+ .filterable("slider", slider ?? { min: 0, max: 5000 }),
+ );
+ },
+
+ /**
+ * A timestamp column.
+ *
+ * Defaults: Date + relative timestamp display (absolute on hover) +
+ * timerange filter + sortable.
+ *
+ * @example
+ * ```ts
+ * col.presets.timestamp().label("Date").commandDisabled().size(200).sheet()
+ * ```
+ */
+ timestamp(): ColBuilder<Date, "timerange"> {
+ return tag(
+ "timestamp",
+ [],
+ col.timestamp().label("Timestamp").display("timestamp").sortable(),
+ );
+ },
+
+ /**
+ * A trace / span / request ID column.
+ *
+ * Defaults: string + monospace code display + not filterable.
+ * Typically hidden in the table and shown only in the row detail drawer.
+ *
+ * @example
+ * ```ts
+ * col.presets.traceId().label("Request ID").hidden().sheet({ skeletonClassName: "w-64" })
+ * ```
+ */
+ traceId(): ColBuilder<string, never> {
+ return tag(
+ "traceId",
+ [],
+ col.string().label("Trace ID").display("code").notFilterable(),
+ );
+ },
+
+ /**
+ * A URL pathname column.
+ *
+ * Defaults: string + plain text display + input (text search) filter.
+ *
+ * @example
+ * ```ts
+ * col.presets.pathname().size(130).sheet()
+ * ```
+ */
+ pathname(): ColBuilder<string, "input"> {
+ return tag(
+ "pathname",
+ [],
+ col.string().label("Pathname").filterable("input"),
+ );
+ },
+
+ /**
+ * A latency column with heatmap visualization.
+ *
+ * Defaults: number + heatmap display with unit + slider filter
+ * with bounds `{ min: 0, max: 5000 }` + sortable.
+ *
+ * @param unit - Unit label shown after the value, e.g. `"ms"`, `"s"`, `"µs"`
+ * @param slider - Override the slider bounds (default: `{ min: 0, max: 5000 }`)
+ *
+ * @example
+ * ```ts
+ * col.presets.latency("ms").label("Latency").size(110).sheet()
+ * col.presets.latency("s", { min: 0, max: 60 }).label("Response time")
+ * ```
+ */
+ latency(
+ unit?: string,
+ slider?: { min: number; max: number },
+ ): ColBuilder<number, "input" | "slider" | "checkbox"> {
+ const bounds = slider ?? { min: 0, max: 5000 };
+ return tag(
+ "latency",
+ [unit, slider],
+ col
+ .number()
+ .label("Latency")
+ .display("heatmap", { unit, min: bounds.min, max: bounds.max })
+ .filterable("slider", bounds)
+ .sortable(),
+ );
+ },
+
+ /**
+ * A health/score column with gauge visualization.
+ *
+ * Defaults: number + gauge display (0–100) + sortable.
+ *
+ * @param range - Override the min/max range (default: `{ min: 0, max: 100 }`)
+ *
+ * @example
+ * ```ts
+ * col.presets.health().label("Health")
+ * col.presets.health({ min: 0, max: 1000 }).label("Score")
+ * ```
+ */
+ health(range?: {
+ min: number;
+ max: number;
+ }): ColBuilder<number, "input" | "slider" | "checkbox"> {
+ const { min = 0, max = 100 } = range ?? {};
+ return tag(
+ "health",
+ [range],
+ col.number().label("Health").display("gauge", { min, max }).sortable(),
+ );
+ },
+
+ /**
+ * A progress column with bar visualization.
+ *
+ * Defaults: number + bar display (0–100) + sortable.
+ *
+ * @param range - Override the min/max range (default: `{ min: 0, max: 100 }`)
+ *
+ * @example
+ * ```ts
+ * col.presets.progress().label("Progress")
+ * col.presets.progress({ min: 0, max: 1000 }).label("Completion")
+ * ```
+ */
+ progress(range?: {
+ min: number;
+ max: number;
+ }): ColBuilder<number, "input" | "slider" | "checkbox"> {
+ const { min = 0, max = 100 } = range ?? {};
+ return tag(
+ "progress",
+ [range],
+ col.number().label("Progress").display("bar", { min, max }).sortable(),
+ );
+ },
+};
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/serialize.ts b/packages/ui/src/lib/data-table-filters/table-schema/serialize.ts
new file mode 100644
index 000000000..2175d3ac9
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/serialize.ts
@@ -0,0 +1,273 @@
+import { createColBuilder, defaultDisplayForKind } from "./col";
+import type {
+ ColKind,
+ ColumnDescriptor,
+ DisplayDescriptor,
+ FilterDescriptor,
+ Provenance,
+ SchemaJSON,
+ SchemaJSONVersion,
+ SheetDescriptor,
+ TableSchemaDefinition,
+} from "./types";
+
+/** The current `SchemaJSON` version. Bump alongside a `migrateSchemaJSON` step. */
+export const SCHEMA_JSON_VERSION: SchemaJSONVersion = 1;
+
+// ── Serialization ───────────────────────────────────────────────────────────
+//
+// The descriptor IS the serializable state, so serialization is a rename of the
+// key and nothing else. There is no projection to keep in sync, which is why
+// `unit`, `presets`, and `resizable` can no longer be silently dropped.
+
+export function serializeSchema(definition: TableSchemaDefinition): SchemaJSON {
+ return {
+ version: SCHEMA_JSON_VERSION,
+ columns: Object.entries(definition).map(([key, builder]) => ({
+ key,
+ ...builder._descriptor,
+ })),
+ };
+}
+
+// ── Deserialization ─────────────────────────────────────────────────────────
+//
+// Descriptors are stored verbatim, so reconstruction hands the descriptor
+// straight back to the builder. The old ~40-branch replay of the fluent chain
+// — including the `enableHiding === false && hidden ⇒ .sheetOnly()` inference
+// archaeology — is gone.
+//
+// Limitation, unchanged: renderers (display cell, filter component, sheet
+// component/condition) are closures and cannot be serialized. A deserialized
+// column falls back to its descriptor's display, which is why the descriptor
+// keeps a real display type even when a custom renderer was supplied.
+
+export function deserializeSchema(json: SchemaJSON): TableSchemaDefinition {
+ const definition: TableSchemaDefinition = {};
+ for (const { key, ...descriptor } of json.columns) {
+ definition[key] = createColBuilder(descriptor as ColumnDescriptor, {});
+ }
+ return definition;
+}
+
+// ── Migration ───────────────────────────────────────────────────────────────
+
+const COL_KINDS: readonly ColKind[] = [
+ "string",
+ "number",
+ "boolean",
+ "timestamp",
+ "enum",
+ "array",
+ "record",
+ "select",
+];
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function asKind(value: unknown, key: unknown): ColKind {
+ if (COL_KINDS.includes(value as ColKind)) return value as ColKind;
+ // Falling back is better than throwing — one bad column should not make a
+ // whole saved schema unloadable — but it is a real loss, so say so.
+ if (value !== undefined) {
+ console.warn(
+ `[migrateSchemaJSON] Column ${JSON.stringify(key)} has unknown kind ` +
+ `${JSON.stringify(value)}. Falling back to "string".`,
+ );
+ }
+ return "string";
+}
+
+const DISPLAY_TYPES: readonly DisplayDescriptor["type"][] = [
+ "text",
+ "code",
+ "boolean",
+ "star",
+ "badge",
+ "timestamp",
+ "number",
+ "bar",
+ "heatmap",
+ "gauge",
+ "status-code",
+ "level-indicator",
+];
+
+/**
+ * Normalize a display descriptor.
+ *
+ * `renderCell` switches on `display.type` with no default branch, so an
+ * unrecognised discriminator renders an empty cell and says nothing. The typed
+ * options are sanitized too — a string `min` would reach the bar/gauge cells as
+ * a bound. Unknown keys ride along, like the ones on `filter`.
+ */
+function asDisplay(
+ value: unknown,
+ kind: ColKind,
+ key: unknown,
+): DisplayDescriptor {
+ if (!isRecord(value)) return defaultDisplayForKind(kind);
+
+ const fallback = defaultDisplayForKind(kind);
+ const { type, unit, color, min, max, colorMap, ...rest } = value;
+ if (!DISPLAY_TYPES.includes(type as DisplayDescriptor["type"])) {
+ if (type !== undefined) {
+ console.warn(
+ `[migrateSchemaJSON] Column ${JSON.stringify(key)} has unknown display ` +
+ `type ${JSON.stringify(type)}. Falling back to "${fallback.type}".`,
+ );
+ }
+ return fallback;
+ }
+
+ const display: Record<string, unknown> = { ...rest, type };
+ if (typeof unit === "string") display.unit = unit;
+ if (typeof color === "string") display.color = color;
+ if (Number.isFinite(min)) display.min = min;
+ if (Number.isFinite(max)) display.max = max;
+ if (isRecord(colorMap)) {
+ display.colorMap = Object.fromEntries(
+ Object.entries(colorMap).filter(([, v]) => typeof v === "string"),
+ );
+ }
+ return display as DisplayDescriptor;
+}
+
+/**
+ * Normalize an array column's item descriptor.
+ *
+ * v1 nests a full `ColumnDescriptor`; v0 carried only `{ dataType, enumValues }`
+ * under `arrayItemType` — and, for non-enum items, nothing at all, which is
+ * exactly how `string[]` columns used to collapse into `string` columns.
+ */
+function normalizeArrayItem(raw: unknown): ColumnDescriptor {
+ const { key: _key, ...item } = normalizeColumn(raw);
+ return item as ColumnDescriptor;
+}
+
+function isProvenance(value: unknown): value is Provenance {
+ if (!isRecord(value)) return false;
+ return (
+ value.source === "manual" ||
+ (value.source === "preset" &&
+ typeof value.preset === "string" &&
+ Array.isArray(value.args)) ||
+ (value.source === "inferred" && typeof value.rule === "string")
+ );
+}
+
+/**
+ * Normalize one column from either version into a complete `ColumnDescriptor`.
+ *
+ * v1 payloads go through this too rather than being trusted: `fromJSON` accepts
+ * user-typed text, so "it says version 1" is not evidence that its columns are
+ * well-formed. Every required field is filled or defaulted here, which is what
+ * makes the unchecked `as SchemaJSON` cast on untrusted input unnecessary.
+ */
+function normalizeColumn(raw: unknown): ColumnDescriptor & { key: string } {
+ const c = isRecord(raw) ? raw : {};
+ // v1 writes `kind`; v0 wrote `dataType`.
+ const kind = asKind(c.kind ?? c.dataType, c.key);
+
+ // v0 wrote `{ type: "text" }` for custom displays and omitted `unit`,
+ // `presets`, and `resizable` entirely. Nothing can recover those — the
+ // migration fills the type-required defaults and validates the rest.
+ const display = asDisplay(c.display, kind, c.key);
+
+ // Carried through wholesale, like `display` and `sheet`. Whitelisting the
+ // optional fields here would reintroduce exactly the hand-maintained
+ // projection this split removed from `serializeSchema` — a new
+ // `FilterDescriptor` field would be dropped on migration and nothing would
+ // say so. Only the three required fields are coerced, because they must exist.
+ const filter: FilterDescriptor | null = isRecord(c.filter)
+ ? {
+ ...(c.filter as Partial<FilterDescriptor>),
+ type: (c.filter.type ?? "input") as FilterDescriptor["type"],
+ defaultOpen: c.filter.defaultOpen === true,
+ commandDisabled: c.filter.commandDisabled === true,
+ }
+ : null;
+
+ const sheet: SheetDescriptor | null = isRecord(c.sheet)
+ ? (c.sheet as SheetDescriptor)
+ : null;
+
+ const common = {
+ label: typeof c.label === "string" ? c.label : "",
+ ...(typeof c.description === "string"
+ ? { description: c.description }
+ : {}),
+ optional: c.optional === true,
+ display,
+ ...(typeof c.size === "number" ? { size: c.size } : {}),
+ hidden: c.hidden === true,
+ enableHiding: c.enableHiding !== false,
+ hideHeader: c.hideHeader === true,
+ // v0 had no `resizable` at all, so it defaults to false there; v1 writes it.
+ resizable: c.resizable === true,
+ sortable: c.sortable === true,
+ filter,
+ sheet,
+ provenance: (isProvenance(c.provenance)
+ ? c.provenance
+ : { source: "manual" }) as Provenance,
+ };
+
+ const key = typeof c.key === "string" ? c.key : "";
+
+ if (kind === "enum") {
+ return {
+ key,
+ ...common,
+ kind: "enum",
+ enumValues: Array.isArray(c.enumValues) ? (c.enumValues as string[]) : [],
+ };
+ }
+ if (kind === "array") {
+ return {
+ key,
+ ...common,
+ kind: "array",
+ // v1 nests a full descriptor under `arrayItem`; v0 carried only
+ // `{ dataType, enumValues }` under `arrayItemType`.
+ arrayItem: normalizeArrayItem(c.arrayItem ?? c.arrayItemType),
+ };
+ }
+ return { key, ...common, kind } as ColumnDescriptor & { key: string };
+}
+
+/**
+ * Bring untrusted schema JSON up to the current version.
+ *
+ * `SchemaJSON` is persisted (the builder cache) and pasted by hand into the
+ * schema editor, so every entry point that accepts it must run through here
+ * first. This is the one hand-written conversion the descriptor split
+ * deliberately keeps.
+ *
+ * v0 (no `version` field) → v1: `dataType` → `kind`, `arrayItemType` →
+ * recursive `arrayItem`, and the newly-required `resizable`, `enableHiding`,
+ * `hideHeader`, and `provenance` get their defaults.
+ *
+ * @throws if `json` is not an object with a `columns` array.
+ */
+export function migrateSchemaJSON(json: unknown): SchemaJSON {
+ if (!isRecord(json) || !Array.isArray(json.columns)) {
+ throw new Error(
+ "[migrateSchemaJSON] Expected an object with a `columns` array.",
+ );
+ }
+
+ if (json.version !== undefined && json.version !== SCHEMA_JSON_VERSION) {
+ throw new Error(
+ `[migrateSchemaJSON] Unknown schema version ${JSON.stringify(json.version)}. ` +
+ `This build understands version ${SCHEMA_JSON_VERSION}.`,
+ );
+ }
+
+ return {
+ version: SCHEMA_JSON_VERSION,
+ columns: json.columns.map(normalizeColumn),
+ };
+}
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/types.ts b/packages/ui/src/lib/data-table-filters/table-schema/types.ts
new file mode 100644
index 000000000..3a9c37ce2
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/types.ts
@@ -0,0 +1,510 @@
+import type {
+ DatePreset,
+ Option,
+} from "@openstatus/ui/components/data-table-filters/types";
+import type { JSX } from "react";
+
+export type ColKind =
+ | "string"
+ | "number"
+ | "boolean"
+ | "timestamp"
+ | "enum"
+ | "array"
+ | "record"
+ | "select";
+
+/** The set of filter UI types. Used as the `F` generic on `ColBuilder<T, F>`. */
+export type FilterType = "input" | "checkbox" | "slider" | "timerange";
+
+export type DisplayConfig =
+ | { type: "text"; colorMap?: Record<string, string> }
+ | { type: "code"; colorMap?: Record<string, string> }
+ | { type: "boolean"; colorMap?: Record<string, string> }
+ | { type: "star"; colorMap?: Record<string, string> }
+ | { type: "badge"; colorMap?: Record<string, string> }
+ | { type: "timestamp"; colorMap?: Record<string, string> }
+ | { type: "number"; unit?: string; colorMap?: Record<string, string> }
+ | {
+ type: "bar";
+ min?: number;
+ max?: number;
+ unit?: string;
+ color?: string;
+ colorMap?: Record<string, string>;
+ }
+ | {
+ type: "heatmap";
+ min?: number;
+ max?: number;
+ unit?: string;
+ color?: string;
+ colorMap?: Record<string, string>;
+ }
+ | {
+ type: "gauge";
+ min?: number;
+ max?: number;
+ unit?: string;
+ color?: string;
+ colorMap?: Record<string, string>;
+ }
+ | { type: "status-code"; colorMap?: Record<string, string> }
+ | { type: "level-indicator"; colorMap?: Record<string, string> }
+ | {
+ type: "custom";
+ cell: (value: unknown, row: unknown) => JSX.Element | null;
+ colorMap?: Record<string, string>;
+ };
+
+export type SheetConfig = {
+ label?: string;
+ component?: (row: unknown) => JSX.Element | null | string;
+ condition?: (row: unknown) => boolean;
+ className?: string;
+ skeletonClassName?: string;
+};
+
+/**
+ * A fluent builder for a single table column.
+ *
+ * `T` — TypeScript type of the column's data value (inferred by `InferTableType`).
+ * `F` — union of filter UI types valid for this col kind (compile-time constraint):
+ *
+ * | Factory | Allowed filter types |
+ * |--------------------|-----------------------------------------|
+ * | `col.string()` | `"input"` |
+ * | `col.number()` | `"input" \| "slider" \| "checkbox"` |
+ * | `col.boolean()` | `"checkbox"` |
+ * | `col.timestamp()` | `"timerange"` |
+ * | `col.enum()` | `"checkbox"` |
+ * | `col.array()` | `"checkbox"` |
+ * | `col.record()` | `never` — `filterable()` is an error |
+ *
+ * Calling `filterable(type)` with a type not in `F` is a **compile-time error**.
+ */
+export interface ColBuilder<T, F extends FilterType = FilterType> {
+ /**
+ * @internal The serializable half of the column. Read it through
+ * {@link resolveColumn} / {@link resolveColumns} rather than directly.
+ */
+ readonly _descriptor: ColumnDescriptor;
+
+ /**
+ * @internal The non-serializable half — the closures. Disjoint from
+ * `_descriptor`: the two share no property name.
+ */
+ readonly _renderers: ColRenderers;
+
+ /**
+ * Sets the column header label shown in the table and filter sidebar.
+ *
+ * @example
+ * col.string().label("Host")
+ * col.enum(LEVELS).label("Severity")
+ */
+ label(text: string): ColBuilder<T, F>;
+
+ /**
+ * Attaches a human-readable description of the column's domain meaning.
+ *
+ * Not shown in the UI. Used by AI agents and MCP tools (via `toJSON()`) to
+ * understand what the column represents.
+ *
+ * @example
+ * col.number().label("Latency").description("Round-trip time from request to response, in ms")
+ * col.enum(LEVELS).label("Level").description("Log severity: error > warn > info > debug")
+ */
+ description(text: string): ColBuilder<T, F>;
+
+ /**
+ * Sets how the column value is rendered in table cells.
+ *
+ * Built-in display types:
+ * - `"text"` — plain text, truncated with tooltip on overflow
+ * - `"code"` — monospace font (IDs, hashes, paths, hostnames)
+ * - `"boolean"` — checkmark / dash icon
+ * - `"badge"` — colored chip (enums, categories, tags)
+ * - `"timestamp"` — relative time ("3m ago"), absolute datetime on hover
+ * - `"number"` — formatted number with optional `unit` suffix
+ * - `"bar"` — horizontal bar with `min`/`max` range and optional `unit`
+ * - `"heatmap"` — background color intensity based on `min`/`max` range
+ * - `"custom"` — developer-supplied JSX renderer (not serializable)
+ *
+ * @example
+ * col.string().display("code")
+ * col.number().display("number", { unit: "ms" })
+ * col.number().display("bar", { min: 0, max: 5000, unit: "ms" })
+ * col.number().display("heatmap", { min: 0, max: 100 })
+ * col.enum(LEVELS).display("custom", { cell: (value) => <LevelBadge value={value} /> })
+ */
+ display(
+ type:
+ | "text"
+ | "code"
+ | "boolean"
+ | "star"
+ | "badge"
+ | "timestamp"
+ | "status-code"
+ | "level-indicator",
+ options?: { colorMap?: Record<string, string> },
+ ): ColBuilder<T, F>;
+ display(
+ type: "number",
+ options?: { unit?: string; colorMap?: Record<string, string> },
+ ): ColBuilder<T, F>;
+ display(
+ type: "bar",
+ options: {
+ min: number;
+ max: number;
+ unit?: string;
+ colorMap?: Record<string, string>;
+ },
+ ): ColBuilder<T, F>;
+ display(
+ type: "heatmap",
+ options: {
+ min: number;
+ max: number;
+ color?: string;
+ colorMap?: Record<string, string>;
+ },
+ ): ColBuilder<T, F>;
+ display(
+ type: "custom",
+ options: {
+ cell: (value: unknown, row: unknown) => JSX.Element | null;
+ colorMap?: Record<string, string>;
+ },
+ ): ColBuilder<T, F>;
+ display(
+ type: "heatmap" | "bar" | "gauge",
+ options?: {
+ min?: number;
+ max?: number;
+ unit?: string;
+ color?: string;
+ },
+ ): ColBuilder<T, F>;
+
+ /**
+ * Enables filtering for this column using its default filter type.
+ *
+ * For `col.record()` (`F = never`) this is a **compile-time error**.
+ * Use `.notFilterable()` on record columns instead (it is already the default).
+ */
+ filterable(...args: [F] extends [never] ? [never] : []): ColBuilder<T, F>;
+
+ /**
+ * Enables filtering with an explicit filter type and optional configuration.
+ *
+ * Only types in `F` are accepted — passing an invalid type is a **compile-time error**:
+ * - `"input"` — free-text or number search field
+ * - `"timerange"` — date range picker (with optional `presets`)
+ * - `"checkbox"` — multi-select from a list of `options`
+ * - `"slider"` — numeric range with required `min` / `max` bounds
+ *
+ * @example
+ * col.string().filterable("input")
+ * col.timestamp().filterable("timerange")
+ * col.enum(LEVELS).filterable("checkbox", { options: LEVELS.map(v => ({ label: v, value: v })) })
+ * col.number().filterable("slider", { min: 0, max: 5000 })
+ */
+ filterable(type: F & "input"): ColBuilder<T, "input">;
+ filterable(
+ type: F & "timerange",
+ options?: { presets?: DatePreset[] },
+ ): ColBuilder<T, "timerange">;
+ filterable(
+ type: F & "checkbox",
+ options?: {
+ options?: Option[];
+ component?: (props: Option) => JSX.Element | null;
+ /**
+ * Offer every declared option even when the facets report no rows for it,
+ * showing a count of `0`. Off by default: a column whose declared set is
+ * far wider than what the data holds (regions, status codes) is better
+ * pruned to what exists. Turn it on for a small closed set where a missing
+ * option reads as a broken filter rather than an absent value.
+ */
+ keepEmptyOptions?: boolean;
+ },
+ ): ColBuilder<T, "checkbox">;
+ filterable(
+ type: F & "slider",
+ options: { min: number; max: number; unit?: string },
+ ): ColBuilder<T, "slider">;
+
+ /**
+ * Removes filtering from this column.
+ *
+ * After calling `.notFilterable()`, subsequent `.filterable()` calls are
+ * **compile-time errors** (`F` becomes `never`).
+ *
+ * @example
+ * col.string().label("Request ID").notFilterable().hidden()
+ */
+ notFilterable(): ColBuilder<T, never>;
+
+ /**
+ * Opens the filter accordion for this column by default in the filter sidebar.
+ *
+ * Only applies to filterable columns. Use for high-priority filters that
+ * users should see immediately without expanding the sidebar manually.
+ *
+ * @example
+ * col.enum(LEVELS).label("Level").filterable("checkbox").defaultOpen()
+ */
+ defaultOpen(): ColBuilder<T, F>;
+
+ /**
+ * Excludes this column from the command palette filter search.
+ *
+ * Useful for columns whose filter state is managed elsewhere (e.g. a date
+ * picker in the toolbar) or for UI-only state fields like `cursor`.
+ *
+ * @example
+ * col.timestamp().label("Date").filterable("timerange").commandDisabled()
+ */
+ commandDisabled(): ColBuilder<T, F>;
+
+ /**
+ * Hides the column by default (not shown on first render).
+ *
+ * Hidden columns appear in the column visibility menu and can be toggled on.
+ * Use `getDefaultColumnVisibility(schema)` to derive the initial visibility map.
+ *
+ * @example
+ * col.number().label("DNS").filterable("slider", { min: 0, max: 5000 }).hidden()
+ */
+ hidden(): ColBuilder<T, F>;
+
+ /**
+ * Hides the column header label in the table while keeping the column visible.
+ *
+ * The label is still used in the filter sidebar and other UI elements.
+ *
+ * @example
+ * col.enum(LEVELS).label("Level").hideHeader()
+ */
+ hideHeader(): ColBuilder<T, F>;
+
+ /**
+ * Enables column resizing via a drag handle in the header.
+ *
+ * Without this, `size` locks the column to a fixed width (`minSize === size`).
+ * With this, the column can be freely resized; `size` becomes the initial width only.
+ *
+ * @example
+ * col.string().label("Host").size(125).resizable()
+ */
+ resizable(): ColBuilder<T, F>;
+
+ /**
+ * Sets a fixed column width in pixels.
+ *
+ * Without `.resizable()`, both `size` and `minSize` are set to this value.
+ * With `.resizable()`, only `size` is set (initial width), allowing free resizing.
+ *
+ * @example
+ * col.enum(LEVELS).label("Level").size(27)
+ * col.timestamp().label("Date").size(200)
+ */
+ size(px: number): ColBuilder<T, F>;
+
+ /**
+ * Enables click-to-sort on the column header.
+ *
+ * Renders a `DataTableColumnHeader` with ascending/descending/none sort controls.
+ *
+ * @example
+ * col.timestamp().label("Date").sortable()
+ * col.number().label("Latency").filterable("slider", { min: 0, max: 5000 }).sortable()
+ */
+ sortable(): ColBuilder<T, F>;
+
+ /**
+ * Marks the data field as potentially `undefined` in the row type.
+ *
+ * Changes `T` to `T | undefined` in the inferred schema type (`InferTableType`).
+ * Use when the column field may be absent from some rows.
+ *
+ * @example
+ * col.number().optional().label("Percentile").notFilterable().hidden()
+ * col.string().optional().label("Message").notFilterable()
+ */
+ optional(): ColBuilder<T | undefined, F>;
+
+ /**
+ * Includes this column in the row detail drawer (`DataTableSheet`).
+ *
+ * Pass a `SheetConfig` to customize label, renderer, visibility condition,
+ * and layout class. Calling `.sheet()` with no arguments uses defaults
+ * (label from `.label()`, no custom renderer).
+ *
+ * @example
+ * col.timestamp().label("Date").sheet()
+ * col.string().label("Host").sheet({ skeletonClassName: "w-24" })
+ * col.number().label("Latency").sheet({
+ * component: (row) => <>{row.latency}ms</>,
+ * skeletonClassName: "w-16",
+ * })
+ */
+ sheet(config?: SheetConfig): ColBuilder<T, F>;
+
+ /**
+ * Marks the column as sheet-only: hidden, not filterable, and excluded
+ * from the column visibility dropdown (`enableHiding: false`).
+ *
+ * Convenience for `.hidden().notFilterable()` + `enableHiding: false`.
+ *
+ * @example
+ * col.record().label("Headers").sheetOnly().sheet({ ... })
+ * col.string().optional().label("Message").sheetOnly().sheet({ ... })
+ */
+ sheetOnly(): ColBuilder<T, never>;
+}
+
+export type TableSchemaDefinition = Record<string, ColBuilder<unknown, any>>;
+
+// Infer the data row type from a table schema definition
+export type InferTableType<T extends TableSchemaDefinition> = {
+ [K in keyof T]: T[K] extends ColBuilder<infer U, any> ? U : never;
+};
+
+// ── Serializable descriptors (function-free) ────────────────────────────────
+//
+// `ColumnDescriptor` is TOTAL: no serializable property of a column may live
+// outside it. `ColRenderers` holds everything that cannot survive JSON. The two
+// are disjoint — they share no property name — and that disjointness is
+// asserted at compile time in `descriptor-laws.test-d.ts`.
+
+/** A JSON value. Used for `Provenance.args`. */
+export type JsonValue =
+ | string
+ | number
+ | boolean
+ | null
+ | readonly JsonValue[]
+ | { readonly [key: string]: JsonValue };
+
+/** Serializable display config — excludes the `custom` variant (contains JSX). */
+export type SerializableDisplayConfig = Exclude<
+ DisplayConfig,
+ { type: "custom" }
+>;
+
+/** Alias kept for symmetry with the other `*Descriptor` names. */
+export type DisplayDescriptor = SerializableDisplayConfig;
+
+/** A checkbox option, stripped to its serializable fields. */
+export type OptionDescriptor = {
+ label: string;
+ value: string | number | boolean;
+};
+
+/**
+ * A timerange preset with its bounds as ISO 8601 instants.
+ *
+ * Known residual loss: presets are usually *relative* ("last hour") and computed
+ * at construction, so a schema saved on Monday and loaded on Friday round-trips
+ * byte-exactly but yields a stale range. A relative descriptor
+ * (`{ duration: "PT1H" }`) is the correct long-term model; the point of storing
+ * them here is that the loss stops being silent.
+ */
+export type DatePresetDescriptor = {
+ label: string;
+ shortcut: string;
+ /** ISO 8601 instant. */
+ from: string;
+ /** ISO 8601 instant. */
+ to: string;
+};
+
+export type FilterDescriptor = {
+ type: FilterType;
+ defaultOpen: boolean;
+ commandDisabled: boolean;
+ options?: OptionDescriptor[];
+ keepEmptyOptions?: boolean;
+ min?: number;
+ max?: number;
+ unit?: string;
+ presets?: DatePresetDescriptor[];
+};
+
+export type SheetDescriptor = {
+ label?: string;
+ className?: string;
+ skeletonClassName?: string;
+};
+
+/**
+ * How the column came to be. Recorded at construction so `schemaToTypeScript`
+ * can read it instead of reverse-engineering the shape of the descriptor.
+ */
+export type Provenance =
+ | { source: "manual" }
+ | { source: "preset"; preset: string; args: readonly JsonValue[] }
+ | { source: "inferred"; rule: string };
+
+export type ColumnDescriptorCommon = {
+ label: string;
+ description?: string;
+ optional: boolean;
+ display: DisplayDescriptor;
+ size?: number;
+ hidden: boolean;
+ enableHiding: boolean;
+ hideHeader: boolean;
+ resizable: boolean;
+ sortable: boolean;
+ filter: FilterDescriptor | null;
+ sheet: SheetDescriptor | null;
+ provenance: Provenance;
+};
+
+/**
+ * Everything about a column that survives JSON.
+ *
+ * `arrayItem` and `enumValues` are **required** on their respective kinds — an
+ * `array` column can no longer exist without a described item type, which is
+ * what stopped `string[]` columns from silently degrading to `string`.
+ */
+export type ColumnDescriptor = ColumnDescriptorCommon &
+ (
+ | { kind: "array"; arrayItem: ColumnDescriptor }
+ | { kind: "enum"; enumValues: readonly string[] }
+ | { kind: Exclude<ColKind, "array" | "enum"> }
+ );
+
+/** Everything that CANNOT survive JSON. Disjoint from `ColumnDescriptor`. */
+export type ColRenderers = {
+ cell?: (value: unknown, row: unknown) => JSX.Element | null;
+ filterComponent?: (props: Option) => JSX.Element | null;
+ sheetComponent?: (row: unknown) => JSX.Element | null | string;
+ sheetCondition?: (row: unknown) => boolean;
+};
+
+/** The public read model: one column's complete state, both halves. */
+export type ResolvedColumn = ColumnDescriptor & {
+ readonly renderers: ColRenderers;
+};
+
+/** `ResolvedColumn` plus the key it is registered under in the definition. */
+export type ResolvedColumnEntry = ResolvedColumn & { readonly key: string };
+
+/**
+ * The current `SchemaJSON` version. Bump when the descriptor shape changes and
+ * add a step to `migrateSchemaJSON`. The runtime constant lives in
+ * `serialize.ts` — this module stays type-only so it can keep shipping in the
+ * `data-table` block.
+ */
+export type SchemaJSONVersion = 1;
+
+export type SchemaJSON = {
+ version: SchemaJSONVersion;
+ columns: Array<ColumnDescriptor & { key: string }>;
+};
diff --git a/packages/ui/src/lib/data-table-filters/table-schema/validate.ts b/packages/ui/src/lib/data-table-filters/table-schema/validate.ts
new file mode 100644
index 000000000..00ebe0508
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/table-schema/validate.ts
@@ -0,0 +1,114 @@
+import { resolveColumns } from "./col";
+import type { TableSchemaDefinition } from "./types";
+
+/**
+ * Validates a table schema definition and throws a descriptive error on the
+ * first violation found.
+ *
+ * Called automatically by `createTableSchema()` — no need to call manually.
+ *
+ * Catches errors that the TypeScript type system cannot prevent:
+ * - Missing label (`.label()` was never called)
+ * - Checkbox options that are not an array
+ * - Slider bounds that are missing, non-finite, or with `min` greater than `max`
+ *
+ * These checks run for both the TypeScript-authored path (`createTableSchema({...})`)
+ * and the AI-generated path (`createTableSchema.fromJSON(json)`).
+ */
+export function validateSchema(definition: TableSchemaDefinition): void {
+ for (const c of resolveColumns(definition)) {
+ const { key } = c;
+
+ // 1. Label is required — col.* factories default to label: ""
+ if (!c.label) {
+ throw new Error(
+ `[createTableSchema] Column "${key}" is missing a label.\n` +
+ ` Fix: .label("${key[0]!.toUpperCase()}${key.slice(1)}")`,
+ );
+ }
+
+ // 2. Checkbox options must be an actual array — `migrateSchemaJSON` carries
+ // the filter descriptor through wholesale, so any JSON value can land
+ // here, and the checkbox filter calls `.filter` on it.
+ if (
+ c.filter?.type === "checkbox" &&
+ c.filter.options !== undefined &&
+ !Array.isArray(c.filter.options)
+ ) {
+ throw new Error(
+ `[createTableSchema] Column "${key}": checkbox filter options must be an array (got ${typeof c.filter.options}).\n` +
+ ` Fix: .filterable("checkbox", { options: [{ label: "200", value: 200 }, ...] })`,
+ );
+ }
+
+ // 3. Every option has to be an object carrying a value. `generateAIOutputSchema`
+ // and the option generators read `option.value` unguarded, so a `[null]`
+ // from JSON throws a TypeError downstream — past the caller's try/catch —
+ // instead of being rejected as an invalid schema here.
+ if (c.filter?.type === "checkbox" && Array.isArray(c.filter.options)) {
+ const invalid = c.filter.options.findIndex(
+ (option) =>
+ typeof option !== "object" ||
+ option === null ||
+ (option as { value?: unknown }).value === undefined,
+ );
+ if (invalid !== -1) {
+ throw new Error(
+ `[createTableSchema] Column "${key}": checkbox option at index ${invalid} is not a { label, value } object.\n` +
+ ` Fix: .filterable("checkbox", { options: [{ label: "200", value: 200 }, ...] })`,
+ );
+ }
+ }
+
+ // 4. Number checkbox filter requires explicit options — the number factory
+ // has no value list to auto-derive from, so an empty options list would
+ // render a filter with no checkboxes (a silent no-op in the UI).
+ if (
+ c.kind === "number" &&
+ c.filter?.type === "checkbox" &&
+ (!c.filter.options || c.filter.options.length === 0)
+ ) {
+ throw new Error(
+ `[createTableSchema] Column "${key}": checkbox filter on a number column requires explicit options.\n` +
+ ` Fix: .filterable("checkbox", { options: [{ label: "200", value: 200 }, ...] })`,
+ );
+ }
+
+ // 5. Slider bounds must be valid — type system requires { min, max } to be
+ // passed but cannot enforce min < max, and JSON input is not typed at all
+ if (c.filter?.type === "slider") {
+ const { min, max } = c.filter;
+ if (min === undefined || max === undefined) {
+ throw new Error(
+ `[createTableSchema] Column "${key}": slider filter is missing min/max bounds.\n` +
+ ` Fix: .filterable("slider", { min: 0, max: 100 })`,
+ );
+ }
+ // NaN and a string bound both slip past `>` silently.
+ if (!Number.isFinite(min) || !Number.isFinite(max)) {
+ throw new Error(
+ `[createTableSchema] Column "${key}": slider min/max must be finite numbers (got ${typeof min} ${String(min)} / ${typeof max} ${String(max)}).\n` +
+ ` Fix: .filterable("slider", { min: 0, max: 100 })`,
+ );
+ }
+ if (min > max) {
+ throw new Error(
+ `[createTableSchema] Column "${key}": slider min (${min}) must be less than max (${max}).\n` +
+ ` Fix: swap the values — .filterable("slider", { min: ${max}, max: ${min} })`,
+ );
+ }
+ }
+
+ // 6. A sheet-only column cannot carry a filter. `.sheetOnly()` is the only
+ // chain step that sets `enableHiding: false` on a hideable column, and
+ // it clears the filter, so no builder can produce this combination —
+ // only hand-written or AI-generated JSON can. It has no chain form,
+ // which means `schemaToTypeScript` would have to drop one half of it.
+ if (c.enableHiding === false && c.hidden && c.filter !== null) {
+ throw new Error(
+ `[createTableSchema] Column "${key}": a sheet-only column cannot have a filter.\n` +
+ ` Fix: drop the filter (.sheetOnly() implies it), or make the column filterable and hidden instead.`,
+ );
+ }
+ }
+}
diff --git a/packages/ui/src/lib/data-table-filters/tokenize.ts b/packages/ui/src/lib/data-table-filters/tokenize.ts
new file mode 100644
index 000000000..6920a19a7
--- /dev/null
+++ b/packages/ui/src/lib/data-table-filters/tokenize.ts
@@ -0,0 +1,137 @@
+export interface TokenizeOptions {
+ /** delimiter between `key:value` pairs (default: `" "`) */
+ fieldDelimiter?: string;
+ /** delimiter between key and value (default: `":"`) */
+ keyValueDelimiter?: string;
+}
+
+/**
+ * Tokenize a `key:value` filter string, respecting quoted values.
+ *
+ * Values are quoted with `"` or `'`; inside quotes, `\\` and `\<quote>` are
+ * escapes. Keep in sync with {@link serializeFilterValue}.
+ *
+ * @example
+ * tokenizeFilterInput('name:john regions:ams') // [["name", "john"], ["regions", "ams"]]
+ * tokenizeFilterInput('name:"john doe"') // [["name", "john doe"]]
+ * tokenizeFilterInput('url:https://example.com/a?b=c') // [["url", "https://example.com/a?b=c"]]
+ */
+export function tokenizeFilterInput(
+ input: string,
+ options: TokenizeOptions = {},
+): Array<[string, string]> {
+ // `|| ` (not a destructuring default): an empty delimiter would match at every
+ // index and stall the scanner.
+ const fieldDelimiter = options.fieldDelimiter || " ";
+ const keyValueDelimiter = options.keyValueDelimiter || ":";
+ const delimiterIsWhitespace = /^\s+$/.test(fieldDelimiter);
+ const trimmed = input.trim();
+ const tokens: Array<[string, string]> = [];
+
+ const isBoundary = (index: number) =>
+ delimiterIsWhitespace
+ ? /\s/.test(trimmed[index])
+ : trimmed.startsWith(fieldDelimiter, index);
+
+ const skipToBoundary = (index: number) => {
+ let i = index;
+ while (i < trimmed.length && !isBoundary(i)) i++;
+ return i;
+ };
+
+ // Hand-rolled scanner instead of a `/(\w+):(?:"([^"]*)"|(\S+))/g` regex: that
+ // pattern restarts inside every word run, so a long unmatched run costs
+ // O(n^2) (CodeQL: polynomial ReDoS).
+ let i = 0;
+ while (i < trimmed.length) {
+ if (isBoundary(i)) {
+ i += delimiterIsWhitespace ? 1 : fieldDelimiter.length;
+ continue;
+ }
+
+ // `a:1; b:2` with a non-whitespace delimiter: the space after it is not a
+ // boundary, so without this the key reads as " b" and the field is dropped.
+ // Keys never contain whitespace, and values are scanned separately.
+ if (!delimiterIsWhitespace && /\s/.test(trimmed[i])) {
+ i++;
+ continue;
+ }
+
+ const keyStart = i;
+ while (
+ i < trimmed.length &&
+ !isBoundary(i) &&
+ !trimmed.startsWith(keyValueDelimiter, i)
+ ) {
+ i++;
+ }
+
+ // No `key:` prefix before the next field boundary — drop the whole token.
+ if (i >= trimmed.length || isBoundary(i) || i === keyStart) {
+ i = skipToBoundary(i === keyStart ? i + 1 : i);
+ continue;
+ }
+
+ const key = trimmed.slice(keyStart, i);
+ i += keyValueDelimiter.length;
+
+ const quote = trimmed[i];
+ if (quote === '"' || quote === "'") {
+ const quoted = readQuoted(trimmed, i, quote);
+ if (quoted) {
+ tokens.push([key, quoted.value]);
+ i = skipToBoundary(quoted.end);
+ continue;
+ }
+ }
+
+ const valueStart = i;
+ i = skipToBoundary(i);
+ const value = trimmed.slice(valueStart, i).trim();
+ if (value) tokens.push([key, value]);
+ }
+
+ return tokens;
+}
+
+/** Returns `null` when the quote is never closed. */
+function readQuoted(
+ input: string,
+ start: number,
+ quote: string,
+): { value: string; end: number } | null {
+ let value = "";
+ let i = start + 1;
+ while (i < input.length) {
+ const char = input[i];
+ if (char === "\\" && (input[i + 1] === quote || input[i + 1] === "\\")) {
+ value += input[i + 1];
+ i += 2;
+ continue;
+ }
+ if (char === quote) return { value, end: i + 1 };
+ value += char;
+ i++;
+ }
+ return null;
+}
+
+/**
+ * Quote/escape a value so it survives {@link tokenizeFilterInput}.
+ */
+export function serializeFilterValue(
+ value: string,
+ options: TokenizeOptions = {},
+): string {
+ const fieldDelimiter = options.fieldDelimiter || " ";
+ const needsQuotes =
+ /\s/.test(value) ||
+ value.includes(fieldDelimiter) ||
+ value.includes('"') ||
+ value.includes("\\") ||
+ value.startsWith("'");
+
+ if (!needsQuotes) return value;
+
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
+}
diff --git a/packages/ui/src/lib/date-preset.ts b/packages/ui/src/lib/date-preset.ts
new file mode 100644
index 000000000..8cb6aa1b8
--- /dev/null
+++ b/packages/ui/src/lib/date-preset.ts
@@ -0,0 +1,41 @@
+import { DatePreset } from "@openstatus/ui/components/data-table-filters/types";
+import { addDays, addHours, endOfDay, startOfDay } from "date-fns";
+
+export const presets = [
+ {
+ label: "Today",
+ from: startOfDay(new Date()),
+ to: endOfDay(new Date()),
+ shortcut: "d", // day
+ },
+ {
+ label: "Yesterday",
+ from: startOfDay(addDays(new Date(), -1)),
+ to: endOfDay(addDays(new Date(), -1)),
+ shortcut: "y",
+ },
+ {
+ label: "Last hour",
+ from: addHours(new Date(), -1),
+ to: new Date(),
+ shortcut: "h",
+ },
+ {
+ label: "Last 7 days",
+ from: startOfDay(addDays(new Date(), -7)),
+ to: endOfDay(new Date()),
+ shortcut: "w",
+ },
+ {
+ label: "Last 14 days",
+ from: startOfDay(addDays(new Date(), -14)),
+ to: endOfDay(new Date()),
+ shortcut: "b", // bi-weekly
+ },
+ {
+ label: "Last 30 days",
+ from: startOfDay(addDays(new Date(), -30)),
+ to: endOfDay(new Date()),
+ shortcut: "m",
+ },
+] satisfies DatePreset[];
diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.ts
new file mode 100644
index 000000000..fee39a133
--- /dev/null
+++ b/packages/ui/src/lib/format.ts
@@ -0,0 +1,39 @@
+import { format } from "date-fns";
+
+export function formatLatency(ms: number): string {
+ if (ms >= 1000) {
+ return (
+ new Intl.NumberFormat("en-US", {
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1,
+ }).format(ms / 1000) + "s"
+ );
+ }
+
+ return (
+ new Intl.NumberFormat("en-US", { maximumFractionDigits: 3 }).format(ms) +
+ "ms"
+ );
+}
+
+export function formatMilliseconds(value: number) {
+ return new Intl.NumberFormat("en-US", { maximumFractionDigits: 3 }).format(
+ value,
+ );
+}
+
+export function formatDate(value: Date | string) {
+ return format(new Date(`${value}`), "LLL dd, y HH:mm");
+}
+
+export function formatCompactNumber(value: number) {
+ if (value >= 100 && value < 1000) {
+ return value.toString(); // Keep the number as is if it's in the hundreds
+ } else if (value >= 1000 && value < 1000000) {
+ return (value / 1000).toFixed(1) + "k"; // Convert to 'k' for thousands
+ } else if (value >= 1000000) {
+ return (value / 1000000).toFixed(1) + "M"; // Convert to 'M' for millions
+ } else {
+ return value.toString(); // Optionally handle numbers less than 100 if needed
+ }
+}
diff --git a/packages/ui/src/react-table.d.ts b/packages/ui/src/react-table.d.ts
new file mode 100644
index 000000000..6fd1ac4fb
--- /dev/null
+++ b/packages/ui/src/react-table.d.ts
@@ -0,0 +1,25 @@
+import "@tanstack/react-table";
+
+declare module "@tanstack/react-table" {
+ // https://github.com/TanStack/table/issues/44#issuecomment-1377024296
+ interface TableMeta<TData extends unknown> {
+ getRowClassName?: (row: Row<TData>) => string;
+ }
+
+ interface ColumnMeta {
+ headerClassName?: string;
+ cellClassName?: string;
+ label?: string;
+ kind?: string;
+ }
+
+ interface FilterFns {
+ inDateRange?: FilterFn<any>;
+ arrSome?: FilterFn<any>;
+ }
+
+ // https://github.com/TanStack/table/discussions/4554
+ interface ColumnFiltersOptions<TData extends RowData> {
+ filterFns?: Record<string, FilterFn<TData>>;
+ }
+}
diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json
index b1b076b69..683550116 100644
--- a/packages/ui/tsconfig.json
+++ b/packages/ui/tsconfig.json
@@ -3,6 +3,7 @@
"include": ["."],
"exclude": ["dist", "build", "node_modules"],
"compilerOptions": {
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
"paths": {
"@openstatus/ui/*": ["./src/*"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e1339ea40..297a246bd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -192,6 +192,9 @@ catalogs:
'@radix-ui/react-tooltip':
specifier: 1.2.8
version: 1.2.8
+ '@radix-ui/react-visually-hidden':
+ specifier: 1.2.3
+ version: 1.2.3
'@react-email/ui':
specifier: 6.1.5
version: 6.1.5
@@ -237,6 +240,9 @@ catalogs:
'@tanstack/react-table':
specifier: 8.21.3
version: 8.21.3
+ '@tanstack/react-virtual':
+ specifier: 3.14.10
+ version: 3.14.10
'@trpc/client':
specifier: 11.17.0
version: 11.17.0
@@ -2887,6 +2893,9 @@ importers:
packages/ui:
dependencies:
+ '@ai-sdk/react':
+ specifier: 'catalog:'
'@date-fns/utc':
specifier: 'catalog:'
version: 2.1.1
@@ -2974,6 +2983,21 @@ importers:
'@radix-ui/react-tooltip':
specifier: 'catalog:'
+ '@radix-ui/react-visually-hidden':
+ specifier: 'catalog:'
+ '@tanstack/react-query':
+ specifier: 'catalog:'
+ version: 5.100.11([email protected])
+ '@tanstack/react-table':
+ specifier: 'catalog:'
+ '@tanstack/react-virtual':
+ specifier: 'catalog:'
+ ai:
+ specifier: 'catalog:'
+ version: 6.0.188([email protected])
class-variance-authority:
specifier: 'catalog:'
version: 0.7.1
@@ -2995,6 +3019,9 @@ importers:
next-themes:
specifier: 'catalog:'
+ nuqs:
+ specifier: 'catalog:'
qr-code-styling:
specifier: 'catalog:'
version: 1.9.2
@@ -7253,10 +7280,19 @@ packages:
react: '>=16.8'
react-dom: '>=16.8'
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-SRyoUbdFMRHuYXMijV5H4ZarQWpXkj3iANq8OFre+pybeVap8ZJjZ3Nz9bVjx4d8PfobVUQUdKyyyHYk3E+djw==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}
engines: {node: '>=12'}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-BfEvehNpOT75r5Ksc5xW6NZuXujTfb7nlSEyVu4XHG3gdxNg1KqXruWbDewXOUaUYIo4oRbSfkjIajz4MAT8tA==}
+
'@tootallnate/[email protected]':
resolution: {integrity: sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==}
@@ -15751,8 +15787,16 @@ snapshots:
react: 19.2.6
react-dom: 19.2.6([email protected])
+ dependencies:
+ '@tanstack/virtual-core': 3.17.8
+ react: 19.2.6
+ react-dom: 19.2.6([email protected])
+
'@tanstack/[email protected]': {}
+ '@tanstack/[email protected]': {}
+
'@tootallnate/[email protected]': {}
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index cc969f6cf..7b1844ce9 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -90,6 +90,7 @@ catalog:
"@radix-ui/react-separator": 1.1.8
"@radix-ui/react-slider": 1.3.6
"@radix-ui/react-slot": 1.2.4
+ "@radix-ui/react-visually-hidden": 1.2.3
"@radix-ui/react-switch": 1.2.6
"@radix-ui/react-tabs": 1.1.13
"@radix-ui/react-toggle": 1.1.10
@@ -111,6 +112,7 @@ catalog:
"@tanstack/react-query": 5.100.11
"@tanstack/react-query-devtools": 5.100.11
"@tanstack/react-table": 8.21.3
+ "@tanstack/react-virtual": 3.14.10
"@trpc/client": 11.17.0
"@trpc/next": 11.17.0
"@trpc/react-query": 11.17.0