Skip to content

@xtandard/lib/pagination

Cursor/offset pagination and keyset helpers (createPaginator, cursor codecs). Zero dependencies.

import { … } from "@xtandard/lib/pagination";
Name Summary
assertSqlIdentifier Validate a SQL column identifier. Throws on unsafe input — identifiers must come from your schema map, never from request data.
createCursorCodec Create an opaque-cursor codec. Defaults to JSON + base64url, every stage replaceable — swap the encoder/decoder pair for encryption or signing, or the serializer/parser pair for superjson/msgpack-style formats.
createKeysetSpec Build a portable keyset pagination spec from sort columns. Returns a structured WHERE AST and ORDER BY keys that ORM adapters (Drizzle, Kysely, Prisma, Knex, raw SQL) translate into native queries.
createPaginator Create a source-agnostic paginator. You provide fetchers for the capabilities your source supports; the paginator normalizes inputs, over-fetches one row to compute hasNextPage without a count query, handles backward (scroll-up) pagination, and emits a uniform Paginated<T> envelope.
decodeBase64Url Decode a base64url (or plain base64) string back to UTF-8. Missing = padding is fine. The default decoder of createCursorCodec; throws on input that isn’t base64.
encodeBase64Url Encode a UTF-8 string as base64url (no padding). Unlike btoa, handles non-Latin1 input; unlike Buffer, works in browsers and edge runtimes. The default encoder of createCursorCodec; reverse with decodeBase64Url.
fromRelayArgs Convert Relay connection args into a CursorPagination input: last/before paginate backward, first/after paginate forward.
generateSubArrays Return every non-empty prefix of an array.
infinitePaginationOptions Build the cursor-walking config fragment for TanStack Query’s useInfiniteQuery (v5). Plain object factory — no dependency on @tanstack/react-query, so it lives in the zero-dep core and works with the React, Vue, Solid and Svelte adapters alike.
isIsoDateString Check whether a value is an ISO-8601 date or datetime string (YYYY-MM-DD, optionally with time and Z/offset) that the host engine can actually parse. createCursorCodec uses it to revive dates on decode.
keysetSqlExpression Mark a server-owned SQL expression as safe for raw keyset SQL rendering.
parsePaginationParams Parse untrusted transport params (query string, parsed body…) into a PaginationInput, with sane defaults and clamping.
toKeysetOrderBySql Render KeysetSpec.orderBy output as an SQL ORDER BY fragment.
toKeysetWhereSql Render a KeysetWhere AST as a parameterized SQL WHERE clause. Returns { sql: "", params: [] } for first page (where is null).
toOffsetWindow Convert page or offset input into a { limit, offset } window (page is 1-based). Cursor input is intentionally not convertible.
toRelayConnection Shape a Paginated<T> result as a Relay connection. Pass the paginator’s cursorFor so every edge gets its own cursor; without it only pageInfo.startCursor/endCursor are populated.
toRestEnvelope Shape a Paginated<T> result as a REST envelope.
Name Summary
CreateKeysetSpecOptions Options for createKeysetSpec.
CreatePaginatorOptions Possibly-async fetchers with a sync codec — the common case.
CreatePaginatorOptionsMaybeAsync Loosest configuration: fetchers and codec stages may all be async.
CreatePaginatorOptionsSync All-sync configuration: sync fetchers and a sync codec.
CursorCodec An opaque-cursor codec: turns cursor data (a plain object) into a string token safe to hand to clients, and back. Fully synchronous variant.
CursorCodecMaybeAsync Cursor codec whose stages may be asynchronous (e.g. WebCrypto encryption), so encode/decode may return Promises.
CursorCodecOptions Codec options where any stage may return a Promise (e.g. an encrypting encoder backed by crypto.subtle).
CursorCodecOptionsSync The codec pipeline is two independently pluggable stages (signature-compatible with drizzle-cursor’s options, so the same overrides can be shared between both libraries):
CursorDirection forward walks the natural order of the source (older items in a feed); backward walks against it (newer items — “scroll up”).
CursorPagination Opaque-cursor style: cursor is absent on the first request.
CursorWindow Normalized window handed to fetchCursor. limit already includes the one-row lookahead. cursor is the decoded cursor data (null for the first page). When direction is "backward" the fetcher must flip its sort order; the paginator restores natural order afterwards.
InfinitePaginationOptions
KeysetCompareOp Portable comparison operation used by keyset predicates.
KeysetOrder Sort direction for one keyset cursor column.
KeysetPredicate One portable keyset comparison, e.g. createdAt > $1.
KeysetSortColumn One sort column in the keyset — last column must be unique (tiebreaker).
KeysetSortKey Normalized keyset sort column with order defaulted.
KeysetSpec Portable keyset pagination description.
KeysetSqlColumns Logical key → SQL identifier or explicit server-owned SQL expression.
KeysetSqlExpression Trusted server-owned SQL expression used as a keyset column target.
KeysetSqlFragment Parameterized SQL fragment — values are never interpolated into the string.
KeysetWhere Lexicographic seek predicate: (a > x) OR (a = x AND b > y) OR .... null means first page (no cursor position).
KeysetWhereClause Conjunction of column comparisons — one branch of the lexicographic OR.
OffsetPagination limit/offset style, as in SQL LIMIT 20 OFFSET 40.
OffsetWindow Normalized window handed to fetchOffset. limit already includes the one-row lookahead — fetch up to limit rows starting at offset.
PageInfo
PagePagination page/pageSize style (1-based), as in ?page=3&page_size=20.
Paginated Uniform pagination envelope, whatever the input style or data source.
PaginationFetchResult What fetchers return. totalItems is optional — provide it if cheap.
PaginationInput Any supported pagination request, discriminated by type.
PaginationParamsSource Loose param bag: URLSearchParams or a parsed query/body object.
Paginator Paginator with possibly-async fetchers and a sync codec: paginate may return a Promise, but cursor tokens are always synchronous.
PaginatorCursorOptions
PaginatorCursorOptionsSync
PaginatorIteration Auto-walking iteration, shared by every paginator tier.
PaginatorMaybeAsync Paginator whose codec has async stages: cursor tokens may be Promises.
PaginatorSync Paginator from an all-sync configuration: results are plain values.
ParsePaginationParamsOptions
RelayArgs GraphQL connection arguments, per the Relay Cursor Connections spec.
RelayConnection A GraphQL connection, per the Relay Cursor Connections spec.
RestEnvelope A typical REST list response: items under data, pagination under meta.
ToKeysetSqlOptions Options for raw SQL keyset rendering helpers.