List queries
Search, facets, sorting and pagination from one definition, safe from the URL to SQL.
Most apps have a lot of list pages that each hand-roll the same things: read
?q=&status=&page=, validate it, escape the search text, turn "no value" into
is null, and document the endpoint. defineListQuery does all of that once
per table.
import { defineListQuery } from "better-supabase/list";
import { betterSupabase } from "./supabase";
export const customerList = defineListQuery(betterSupabase, "customers", {
search: ["name", "kvk"],
facets: { status: "status", kvk: "kvk" },
sorts: {
name: [{ name: "asc" }, { id: "asc" }],
newest: [{ createdAt: "desc" }, { id: "asc" }],
},
defaultSort: "newest",
pageSize: 25, // default 50, capped by maxPageSize (default 200)
});Column names, sort keys and facet keys are all typed. search only accepts
text columns. defaultSort must be one of the sorts.
Parse and run
parse accepts URLSearchParams, a Next.js searchParams record, or typed
input. Facet values can be comma-separated or repeated
(?status=active,lead or ?status=active&status=lead).
export default async function Page({ searchParams }: PageProps<'/customers'>) {
const { db } = await bsb.context();
const query = customerList.parse(await searchParams);
if (!query.ok) return <InvalidFilters issues={query.issues} />;
const page = await customerList
.run(db, query.value, { select: ['id', 'name', 'status'], where: { archivedAt: null } })
.orThrow();
// page.items: { id: string; name: string; status: CustomerStatus }[]
}run calls page and ANDs your own where with the list filters. Plugins
such as tenant scoping and soft delete still apply. include takes the same
relation map as list. If you only want the arguments, use
customerList.args(query).
Pagination
A list pages by cursor: it takes after instead of a page number and
returns { items, nextCursor, hasMore }. A cursor page skips the count and
reads the same number of rows however deep it is, and rows inserted between
requests don't shift it (see
Pagination). End every sort with a
unique column, like id above, so rows that tie don't fall between pages.
const page = await customerList.run(db, query.value).orThrow();
// page: { items, nextCursor, hasMore }
customerList.toSearchParams({ ...query.value, after: page.nextCursor! });page in the input is rejected with an issue. size is still capped by
maxPageSize, and the OpenAPI parameters and JSON Schema describe after.
Page numbers
Set pagination: 'offset' when the UI shows page numbers or a total, or a
sort follows a relation, which a cursor can't continue after:
export const customerTable = defineListQuery(betterSupabase, "customers", {
sorts: { name: [{ name: "asc" }, { id: "asc" }] },
defaultSort: "name",
pagination: "offset",
});
// page: { items, page: { number, size, total, pages, hasMore } }The list then takes page, rejects after, and reads and skips every row
before the page, so late pages get slower as the table grows. The total uses
count: 'planned' by default: the planner's row estimate, which costs
nothing extra but can be off after bulk changes until the table is analyzed.
Set count: 'exact' in the config when the UI needs the precise total (a
"page 3 of 7" footer on a small table), 'estimated' for exact counts below
PostgREST's db-max-rows and the estimate above, or pass count to one
run; see Pagination for what each mode
costs.
Facet counts
Filter UIs usually show how many rows each facet value would match
("Active (12)"). Set facetCounts: true and run also returns
page.facetCounts:
export const customerList = defineListQuery(betterSupabase, "customers", {
facets: { status: "status", kvk: "kvk" },
sorts: { name: { name: "asc" } },
defaultSort: "name",
facetCounts: true,
});
const page = await customerList.run(db, query).orThrow();
page.facetCounts.status; // { active: 12, lead: 4, archived: 0 }
page.facetCounts.kvk; // { '1001': 3, __unset__: 13 }Each facet gets its own grouped aggregate, filtered by the search, your own
where and every other facet's selection but not its own, so picking active
doesn't turn lead into 0. Enum and CHECK values with no rows show up as 0.
Empty values are keyed UNSET.
Each aggregate counts at most facetLimit values (100 by default), the most
frequent first, with ties in column order. A facet with more values keeps the
facetLimit values that match the most rows, and its key is listed in
page.facetCountsTruncated, so the UI can say the list is cut:
page.facetCountsTruncated; // [] when every facet was counted in fullfacetCountMode: "capped" reads at most facetScanCap rows per facet (1000 by
default) and counts that sample, instead of grouping every matching row. When
the cap is reached, page.facetCountsCapped is true. Pass facetCountMode to
run or countFacets to override the config for one call: "exact" for a
dashboard number on a list that is capped by default, "capped" for a list that
counts exactly. On the 1,000,000-customer tenant an exact status count took
21 ms, so a list can stay exact until a measurement says otherwise:
const exact = await customerList
.countFacets(db, query, { facetCountMode: "exact" })
.orThrow();countFacets returns those counts without the page, and facetCacheKey stays
the same while the page, cursor and size change, so a cache can keep them:
const key = customerList.facetCacheKey(query);
const counts = await customerList.countFacets(db, query).orThrow();
const page = await customerList
.run(db, nextPage, { facetCounts: counts })
.orThrow();A later page then does not count again.
This needs PostgREST aggregates (pgrst.db_aggregates_enabled); doctor warns
with BS210 when they are off. The counts
sort by _count,
which PostgREST can't do on a table with a column named count. If an
aggregate fails, the whole run fails with its DbError.
Request budget
A list is one request, plus one per facet when facetCounts is on, and always
one wave: the page and the aggregates run in parallel. Assert it with
db.$stats():
await customerList.run(db, query);
expect(db.$stats()).toMatchObject({ calls: 3, waves: 1 });Filter trees
Facets cover "status is one of these". For nested and/or conditions, add
filters: an allow-list of fields that a filter tree may name, each with a
type and, optionally, the subset of its operators to allow. The tree is the
FilterQuery that ReUI Filters edits, typed structurally,
so better-supabase doesn't depend on ReUI.
A tree can also go straight into a repository where. The server installs
the converter. A bundle that builds no server calls enableFilterTrees() from
better-supabase/list once first, which ships the field checks with it; a read
with a tree before that fails with a message that names the call.
export const customerList = defineListQuery(betterSupabase, "customers", {
search: ["name"],
filters: {
name: { type: "text", label: "Name" },
status: { type: "select" }, // options come from the enum or CHECK values
createdAt: { type: "date", label: "Created" },
contact: { type: "relation", column: "primaryContactId" },
kvk: { type: "text", operators: ["is", "empty", "not_empty"] },
},
sorts: { newest: [{ createdAt: "desc" }, { id: "asc" }] },
defaultSort: "newest",
});| Type | Column | Operators |
|---|---|---|
text | any | contains, not_contains, starts_with, ends_with, is, is_not, empty, not_empty |
number | numeric | eq, neq, gt, gte, lt, lte, between, not_between, empty, not_empty |
date | date, timestamp, timestamptz | is, is_not, is_before, is_after, is_on_or_before, is_on_or_after, between, not_between, empty, not_empty |
select | any | is, is_not, is_any_of, is_none_of, empty, not_empty |
relation | any, usually a foreign key | the select operators, on the key's value |
multiselect | an array | has_any_of, has_all_of, has_none_of, empty, not_empty |
boolean | bool | is, is_not, empty, not_empty |
parse checks the tree and reports problems with a path such as
['filter', 'rules', 0, 'operator']:
- Every rule names a configured field, uses one of its operators, and has a value of the right shape for the operator (none, one, a list, or a range). Select values are checked against the enum or CHECK values.
- A tree has at most
maxFilterRulesrules (50) andmaxFilterDepthlevels of groups (4). - A rule with an empty operator is unfinished, as in ReUI's
flattenFilterConditions: it is dropped, and so is a group left empty. - Negative operators (
is_not,not_contains,is_none_ofand the others) andnegated: truealso match rows where a nullable column is null. starts_withandends_withare case-insensitive, likecontains.
Date values are { date: '2026-10-13' } or
{ relative: { unit: 'day', offset: -7 } }, with an optional
time: 'HH:mm'. Relative dates resolve when the query runs, not when it is
parsed, so a saved URL for "last 7 days" keeps meaning that. They resolve on
Temporal in the time zone you pass to parse, usually the user's:
const query = customerList.parse(await searchParams, {
timeZone: "Europe/Amsterdam",
});A timestamptz column compares instants at the zone's midnight, a
timestamp column local date-times, and a date column plain dates. The
compiled filter is ordinary repository where input, so it reaches PostgREST,
the Postgres executor and the SQLite compiler the same
way. customerList.filterWhere(query) returns it on its own.
customerList.filterFields(labels) returns the FilterField[] that ReUI
Filters takes. Pass translated labels for fields, operators and options;
English is the default:
"use client";
const fields = customerList.filterFields({
fields: { name: "Naam", createdAt: "Aangemaakt" },
options: { status: { lead: "Lead", active: "Actief" } },
});In the URL, the tree is one filter parameter holding base64url JSON, which
toSearchParams writes and parsers.filter and nuqs read. openapi
describes it as a query parameter, and jsonSchema describes the tree under
$defs.
Test a tree on one record
evaluateFilterQuery(query, record, fields, clock) from
better-supabase/list answers whether one record matches a tree, without a
query. It uses the same operators, case rules, relative dates and null
handling as the compiled filter, so a rule that selects a row also matches
that row in memory. Pass the list's checked fields (customerList.filters),
or your own FilterRecordField list, whose column may be dotted to read a
nested value such as submitter.seniority:
import { evaluateFilterQuery } from "better-supabase/list";
const { matched, results } = evaluateFilterQuery(
query.filter,
customer,
customerList.filters,
{ timeZone: "Europe/Amsterdam" },
);results holds every rule and group that took part, by node id: true,
false, or null when a comparison met a missing value (SQL's unknown,
which never matches). Unfinished rules, unknown fields and empty groups
take no part, and a tree with nothing left matches. The
rules block stores trees like this per organization
and runs them on events.
The operator table above was checked against the ReUI registry items
filters and c-filters-5 (date operators) as published on 2026-10-13, in a
fixture that the tests compare with FILTER_OPERATORS. ReUI publishes no
version number for registry items.
What it compiles to
| Input | Filter |
|---|---|
q=road | name ilike '%road%' or kvk ilike '%road%' |
status=active,lead | status in ('active', 'lead') |
kvk=__unset__ | kvk is null |
kvk=__unset__,1001 | kvk in ('1001') or kvk is null |
Search text is trimmed, capped at maxSearchLength (200) and escaped: %,
_ and \ match literally, and commas, parentheses and quotes can't break out
of a PostgREST or=(...) filter. The same query gives identical results
through PostgREST and the direct Postgres executor.
For full-text search, point search at a tsvector or text column:
search: { fts: 'searchVector', config: 'dutch' } // websearch_to_tsqueryValidation
Facet values are checked against enum and CHECK-constraint values from the
generated schema. __unset__ (exported as UNSET) is only allowed on
nullable columns. Every problem is reported with a path:
customerList.parse(new URLSearchParams("sort=oldest&page=0&status=bogus"))
.issues;
// [{ path: ['sort'], ... }, { path: ['page'], ... }, { path: ['facets', 'status'], ... }]customerList.schema is a Standard Schema, so it plugs into
any router or form library that accepts one. Pass it to bsb.action({ input })
or an oRPC procedure without writing a validator.
URLs and nuqs
toSearchParams writes a query back to the URL, leaving out defaults, so
links stay short and round-trip exactly:
customerList.toSearchParams({ ...query, page: 2 }).toString(); // 'q=road&page=2'For client-side state with nuqs, pass its createParser.
better-supabase does not depend on nuqs:
"use client";
import { createParser, useQueryStates } from "nuqs";
const parsers = customerList.nuqs(createParser);
const [state, setState] = useQueryStates(parsers);customerList.parsers exposes the same { parse, serialize } pairs for
other routers.
Filter on a related table
A facet can name a column of a related table: { relation, column } instead of a column name. The
relation and the column are checked against the schema's types.
const customerList = defineListQuery(betterSupabase, "customers", {
facets: { status: "status", noteKind: { relation: "notes", column: "kind" } },
sorts: { newest: [{ createdAt: "desc" }, { id: "asc" }] },
defaultSort: "newest",
});
// ?noteKind=call,meeting: customers with at least one call or meeting noteA to-many relation matches rows with at least one related row in the values (some). A to-one relation
matches rows whose related row has the value. The values follow the related column's enum. A relation
facet filters but has no counts: with facetCounts: true its facetCounts entry is an empty object.
facets lists it with relation: { name, many }.
Sort by several columns
freeSort from better-supabase/list/order lets the caller pick up to three columns and a direction
each, next to the named sorts. It lives in its own entry, so a list that does not use it does not
carry its code.
import { freeSort } from "better-supabase/list/order";
const customerList = defineListQuery(betterSupabase, "customers", {
sorts: { newest: [{ createdAt: "desc" }, { id: "asc" }] },
defaultSort: "newest",
freeSort: freeSort(betterSupabase, "customers", {
sortable: ["name", "status", "createdAt"],
}),
});
// ?order=status:desc,name (direction defaults to asc)
customerList.parse({ order: [{ column: "name", direction: "asc" }] });order replaces sort while it is set and ends in the tiebreak column (the primary key, or tiebreak)
so cursor pages stay stable. A column outside sortable, a repeated column, more than three columns
and a direction other than asc or desc are issues at ["order"]. order is also a URL parser
(list.parsers.order, list.nuqs), an OpenAPI parameter and a JSON Schema property. Without freeSort
the key is not reserved and order input is an issue.
Count rows per date bucket
The buckets tag renders a function that counts rows per
day, week, month, quarter or year, in a time zone. listDateBuckets from better-supabase/list/buckets
calls it and narrows the count by the facet values of a list query. A grouped date count cannot be
written with PostgREST aggregates, which is why it is a function.
import { listDateBuckets } from "better-supabase/list/buckets";
const buckets = await listDateBuckets({
rpc: (args) => db.$rpc("customers_date_buckets", args),
unit: "month",
list: { facets: customerList.facets, query },
}).orThrow();OpenAPI, MCP and filter UIs
The definition describes itself:
customerList.openapi: OpenAPI 3.1 query parameters, with facets asstyle: form, explode: falsestring arrays that list their enum values.customerList.jsonSchema: JSON Schema for the typed input. Use it for MCP tool arguments or JSON APIs.customerList.facets:{ key, column, nullable, values?, relation? }for rendering filter menus.
Download a list as CSV
exportListCsv turns a cursor list into a CSV download. It reads the list one page at a time and
streams the file, so a large list is never held in memory. The first page is read before the response
starts, so a failed read is an ordinary error response with the error's status, not a broken file.
import { exportListCsv } from "better-supabase/list/export";
export async function GET(request: Request) {
const parsed = customerList.parse(new URL(request.url).searchParams);
if (!parsed.ok) {
return Response.json({ issues: parsed.issues }, { status: 400 });
}
return exportListCsv({
page: (after, size) =>
customerList.run(db, { ...parsed.value, after, size }),
columns: [
{ header: "Name", value: (row) => row.name },
{ header: "Created", value: (row) => row.createdAt },
],
filename: "customers.csv",
});
}| Option | Meaning |
|---|---|
pageSize | Rows per page, 1 to 1,000. Default 500. |
maxRows | The most rows in the file; the file ends there. Default 100,000. |
filename | The download's file name. Default export.csv. |
bom | Start the file with a byte order mark, for Excel. |
A text cell that starts with =, +, -, @ or a control character gets a leading ', so a
spreadsheet does not run it as a formula. Dates become ISO strings and objects become JSON.
Load the rows of a page by id
pageFromIds builds a cursor page from two sources: a page of ids in display order (a search, a
ranking, a queue) and a function that loads rows by id, such as the get_<table>_by_ids function the
rpc tag renders. Rows come back in the order of the ids, and an id
whose row is missing or hidden by row security is left out, so a page can hold fewer rows than ids.
import { pageFromIds } from "better-supabase/list/export";
const page = await pageFromIds({
ids: searchIds(query), // PromiseLike<Result<{ ids, nextCursor, hasMore }>>
rows: (ids) => db.$rpc("get_customers_by_ids", { ids }),
idOf: (row) => row.id,
}).orThrow();Entity pages
A block entity already declares its sorts, facets, filters and search in its manifest, and
its client has a page and facets read. defineEntityPage names the entity once, and
gen writes the list query, its route, the indexes and a scale test
from it. The descriptor sits in gen.entityPages.pages in the config:
import { defineConfig } from "better-supabase/config";
import { defineEntityPage } from "better-supabase/list";
export default defineConfig({
gen: {
entityPages: {
pages: [defineEntityPage({ entity: "risks.risk", route: "/risks" })],
},
},
});| Field | Meaning |
|---|---|
entity | The block entity as <block>.<entity>. The block manifest supplies the surface. |
route | The page's route in the app. The last segment names the generated files unless name is set. |
name | The file stem of the generated files. Defaults to the last segment of route. |
reads | The expression under db that holds the reads. Defaults to the block name. |
methods | The page and facets method names on reads. Default page and facets. |
list | pageSize and maxPageSize of the generated list query. |
columns | The logical columns of the list, in order. gen writes pages/<name>.columns.ts from them. |
sections | The sections of the detail page, in order. gen writes pages/<name>.detail.ts from them. |
area | The nav area of the page. gen writes pages/<name>.navigation.ts when it is set. |
seed | The seed rows: demo, tiers, fields, rows, table and tenant. gen writes pages/<name>.seed.ts. |
export | filename, columns and maxRows of a CSV download. gen writes /api/<name>/export. |
tenantOption | The per-call option a block takes for the organization (organizationId). The routes pass the request's tenant under that name. |
app | The surface, table and reads of an entity no block owns (app.<entity>). See below. |
The generated module calls defineEntityListQuery with the entity's surface. It has no database
access of its own: parse checks the URL, schema checks typed input as a Standard Schema, and run
reads the page and the count of every facet in one wave, under the same filters.
import { risksList } from "@/lib/supabase/pages/risks.list";
const query = risksList.parse(searchParams);
if (!query.ok) {
return Response.json({ issues: query.issues }, { status: 400 });
}
const { page, facets } = await risksList
.run(
{
page: (options) => db.risks.page(options),
facets: (options) => db.risks.facets(options),
},
query.value,
)
.orThrow();The URL form reads q, sort (key or key:asc or key:desc), limit, repeated after values
and one parameter per declared filter (status=open,closed). A sort, filter or q the entity does
not declare comes back as an issue with its path, never as a database error.
Sort by several columns
sort is one { by, direction? } or a list of up to three, each a column from the entity's sorts
and no column twice. In the URL a list is comma separated (sort=status:asc,dueDate:desc) or a
repeated parameter, and one term stays the single form, so code that reads sort.by keeps working.
toSearchParams writes the same text back, and parse reads it.
const parsed = risksList.parse(
new URLSearchParams("sort=status:asc,dueDate:desc"),
);
// { ok: true, value: { sort: [{ by: "status", direction: "asc" }, { by: "dueDate", direction: "desc" }] } }The list form is additive: apiVersion stays 1. A block's SQL list function reads one named sort, so
the block's page orders by the first term and says so. The page it returns has sorted, with the
terms it ordered by in applied and the rest in ignored. Nothing is dropped silently, and the keyset
cursor stays the cursor of the applied term, so after pages the same rows with a list as with the
first term alone.
The entity's page | A list of sorts |
|---|---|
A block entity built with entityList (every block today) | Orders by the first term; sorted.ignored holds the other terms |
An app reads module (app.reads) | Reads options.sort itself and may order by every term |
A page that sets no sorted | Does not report; read its own docs |
Declare the lists the page offers in sortLists ([["status", "dueDate"]]). gen writes one btree
index on (tenant, status, due_date, id) for each, and doctor rule
BS636 reports a list without it. Mixed directions seek into the index only
for the leading column, as for a named sort with keys that sort both ways.
A ReUI filter tree works too. parse reads the filter parameter (encodeFilterQuery), and
fromFilterTree maps an and group of is, is any of and has any of rules, one per declared
filter, to the same filters. An or group, a nested group, a negated rule, another operator or a
field that appears twice comes back as an issue, because the entity's page filters by lists of
values only.
Blocks that take the organization per call
A block whose page, facets and count take organizationId on every call (a
RequiredTenantOption, such as incidents) needs the tenant in the generated route. Set
tenantOption: "organizationId" and the list and export routes read tenant from the route context
and pass { organizationId: tenant } to page and facets.
An app table or a list the app reads itself
An entity no block owns has no manifest. Name it app.<entity> and give defineEntityPage the app
descriptor: the surface (sorts, facets, filters, search), the table when gen should
write its indexes and scale test, and the reads module.
defineEntityPage({
entity: "app.customer",
route: "/customers",
columns: ["name", "status"],
app: {
surface: {
sorts: ["name", "newest"],
facets: ["status"],
search: ["name"],
},
table: {
name: "customers",
tenant: "tenant_id",
columns: { name: "name", status: "status" },
},
reads: { module: "@/lib/customer-reads", export: "customerReads" },
},
});The reads export is a function that takes the route's db and returns { page, facets }
(EntityListReads). The generated list and export routes call it in place of db.<reads>.page.
An app entity has no input schema, so it writes no form file, and it writes a seed file only when seed.rows declares its rows. It belongs to no block, so it
writes a coverage entry only when app.blocks names the blocks whose screen the page is (blocks: ["deals", "pipelines"]):
pageCoverage then lists its route under each.
Columns, detail and forms
columns lists logical columns of the entity's table (number, nextReviewOn). gen stops with
config_invalid and names the table's columns when one is not a column. Each entry of the generated
<name>Columns has the row key, the database column, a readable label, a kind (text,
number, boolean, date, datetime, uuid, enum or json, from the block's input schema or the
name) and, when the entity declares one, the sort and filter with the same name. A header click
therefore maps to a named sort, and a facet to a column, without a list of your own.
import { risksColumns } from "@/lib/supabase/pages/risks.columns";
const sortable = risksColumns.filter((column) => "sort" in column);sections lists the parts of the record's page as lowercase words joined by -. <name>Detail
holds the route (/risks/:id), the sections with their labels and href(id).
A page whose block exports an input schema also gets pages/<name>.form.ts, with
<name>CreateForm and, when the block exports a change schema, <name>EditForm. Each is a
defineEntityForm over the fields of the schema the action validates, so the form and the action
cannot drift. parse reads FormData or a record into the action's input: numbers and booleans are
converted, an empty optional field is left out, an empty nullable field is null, and each problem
comes back as an issue with the field's path. The action's own schema stays the authority.
import { risksCreateForm } from "@/lib/supabase/pages/risks.form";
export async function createRisk(data: FormData) {
const input = risksCreateForm.parse(data);
if (!input.ok) {
return { issues: input.issues };
}
return db.risks.create(input.value).orThrow();
}The Next.js example declares columns and sections on its periods page, so
src/lib/supabase/pages/periods.columns.ts and periods.detail.ts are generated output.
Seed, navigation and the route manifest
seed writes <name>Seed: the table, the tenant column the app fills, the tiers and demo rows
keyed by database column, so they insert without a rename. The rows come from the required fields of
the block's input schema that are columns of the table, filled from each field's kind and bounds
(enum values in turn, dates counting forward from a fixed day). The same descriptor gives the same
rows. A larger load stays with pnpm db:seed:scale.
Three more keys of seed cover what a generated value cannot know (ADR 1032):
fieldssets the value of an input field by its name. A scalar is the value of every row and a list gives rowithe value atimodulo its length, so a risk'scategorycan take the block's configured categories in turn (fields: { category: ["quality", "safety"] }). A field it names is seeded even when it is optional. A name that is not an input field and a column of the table, or an empty list, stopsgenwithconfig_invalid.rowsdeclares the rows by hand for a page whose block exports no input schema that fits, such as an accrual that takessource: { type, id }. They replace the generated rows, sodemoandfieldsstay unset. A key is what the app's insert call reads, usually a database column.table(schema.table) andtenantname the table when the block declares none for the entity, as the organizations block does for its invitations. Aseedwith no table stopsgen.
A value in rows can be nested JSON (a jsonb argument such as a segment's conditions), and two
helpers from better-supabase/list cover what a static file cannot hold (ADR 1035):
seedRef(entity, name)is the id of a row that another page seeds, found by its name (the first identity column the runner names for that page).genlists the entity in the seed'sdependsOn, and stops withconfig_invalidwhen that page has noseedor a row refers to its own page. A runner inserts the page first:orderSeeds(seeds)sorts bydependsOnand throws on a cycle, andresolveSeedValue(value, resolver)replaces the markers once the runner has the ids.seedDate(days)is a day counted from the day the seed runs, so a deal's close date or a contract's end date does not age.resolveSeedValuewrites it asYYYY-MM-DD.
seed: {
rows: [
{
name: "Hooli pilot",
pipelineId: seedRef("app.pipelines", "Sales"),
closeOn: seedDate(40),
},
],
},area writes <name>Nav: the area, a label, the list href, recordHref (the generated
<name>Detail.href, when the page has sections) and titleKey (the first entry of <name>Columns).
pages/routes.manifest.ts holds entityRoutes, one entry per page with its list route, its API route,
its detail route and the message keys of its title, columns, facets, sections and form fields. A
translation file can be checked against messageKeys, so an empty or missing string fails in your own
check instead of at runtime. The empty-translation check is not part of gen; the example runs its own.
import { entityRoutes } from "@/lib/supabase/pages/routes.manifest";
import { periodsNav } from "@/lib/supabase/pages/periods.navigation";
const keys = entityRoutes.flatMap((entry) => entry.messageKeys);
const href = periodsNav.recordHref?.("p1");CSV export route
A page that sets export gets GET /api/<name>/export. The route reads the list query's q, sort
and filters from the URL, then streams exportResponse over the entity's page, so the file holds
the rows the list shows under the same filters, one page at a time. columns defaults to the page's
columns (the keys of the rows), filename to <name>.csv and maxRows to EXPORT_ROW_CAP
(100000); an export that reaches the cap ends with the EXPORT_ROW_CAP error. The manifest entry of
the page lists the route as export. A page without export writes no route and no export key.
const csv = entityRoutes.find((entry) => entry.name === "periods")?.export;
// "/api/periods/export?status=open&sort=startsOn:desc"The route covers entities whose page returns the rows to download. A block whose export is not CSV
over page (OSCAL, SEPA, iCalendar, payroll files, promptfoo, the audit log's NDJSON, OCSF or
cursor-paged CSV, and the data export) keeps its own method.
The Next.js example declares periods, risks, commissions, referrals and work orders, each with an area,
so their <name>.navigation.ts files and routes.manifest.ts are generated output (the periods page also sets export, which writes api/periods/export/route.ts), and its side
navigation reads href and area from them. Thirteen pages set seed, and pnpm db:seed:pages inserts
their rows through the block's own functions, once per row: work orders, incidents, risks (with fields),
periods (with fields, from the periods block's input schema), commissions, referrals, invitations,
pipelines, deals, segments, assignment queues, scores, contracts, customers and inbox conversations (with rows). Commissions refer to
their deals and deals to their pipeline with seedRef, so the script inserts pipelines first. pnpm supabase:reset runs it after the reset (ADR 1033). The page names the identity columns of each call, so
a second run adds nothing.
gen stops with config_invalid when a page sets seed and its block exports no input schema that fits
the table and the page sets no rows. The customers and inbox pages seed only what the pgTAP suite does
not need: seed.sql keeps the fixed-id customers and the Help conversation, because the library reset
runs no page seeds. The inbox target calls record_inbound and moves a conversation back by the row's
age_days in its after statement (ADR 1036).
The example checks the manifest in two places. pnpm check:example-coverage fails when a declared page's
route is missing under its block in the coverage map, and pnpm check:empty-translations fails on an empty
msgstr for a page's message keys and for the messages under its name as namespace.
Last updated on