@sahitono/cql2-builder
v0.2.0
Published
Type-safe CQL2 JSON builder
Readme
CQL2 Builder
A lightweight, type-safe TypeScript builder for OGC CQL2 JSON.
Build CQL2 expressions with type-safe property references, operators, and values. The output is plain JSON, ready to use with compatible OGC APIs. The JSON entry point is independent of the optional text adapter.
- Type-only GeoJSON dependency; no runtime service dependencies
- Type-safe, schema-aware API
- Supports spatial, temporal, and array predicates
- Extensible with custom functions and operators
Development
Built using conventions from antfu/starter-ts, with tsdown, Vitest, and ESLint.
corepack enable
pnpm install
pnpm typecheck
pnpm test
pnpm run ciUsage
import { cql } from "@sahitono/cql2-builder"
import { toText } from "@sahitono/cql2-builder/text"
interface Feature {
name: string | null
areaHa: number
}
const q = cql<Feature>()
const filter = q.and(
q("name", "like", "Jati%"),
q.between(q.prop("areaHa"), 10, 50),
)
console.log(q.stringify(filter))
console.log(toText(filter))The JSON output is:
{"op":"and","args":[{"op":"like","args":[{"property":"name"},"Jati%"]},{"op":"between","args":[{"property":"areaHa"},10,50]}]}The text adapter renders:
name LIKE 'Jati%' AND areaHa BETWEEN 10 AND 50The builder returns a JSON-serializable CQL2 expression. No additional transformation is required for JSON APIs.
Imports and migration
The JSON builder is available from the package root. The text adapter is a separate subpath so the root module graph stays free of parser code.
import { cql } from "@sahitono/cql2-builder"
import { toText } from "@sahitono/cql2-builder/text"If you previously imported toText from the package root, move that import:
// Before
import { toText } from "@sahitono/cql2-builder"
// After
import { toText } from "@sahitono/cql2-builder/text"cql remains at the package root. Removing the old root export is an intentional breaking change.
Optional request inputs
q.optional(value, build) skips null and undefined inputs and calls build once for other values, including 0, false, and the empty string. q.andOptional(...terms) omits absent terms and returns undefined when none remain.
function requestParams(minArea: number | null, name: string | undefined) {
const q = cql<{ areaHa: number, name: string }>()
const filter = q.andOptional(
q.optional(minArea, n => q("areaHa", ">=", n)),
q.optional(name, s => q("name", "like", s)),
)
const params: Record<string, string> = {}
if (filter !== undefined) {
params["filter-lang"] = "cql2-json"
params.filter = q.stringify(filter)
}
return params
}An omitted input removes its condition. To search explicitly for null property values, use q.isNull(q.prop("name")). Optional composition adds no CQL2 operator.
API
| Category | API |
|---|---|
| Comparison | =, <>, >, >=, <, <= |
| Advanced comparison | like, between, in, isNull, not |
| Logical | and, or, not |
| Optional composition | optional, andOptional |
| String modifiers | casei, accenti |
| Arithmetic | arithmetic, add, subtract, multiply, divide, modulo, integerDivide, power |
| Spatial | s_intersects, s_within, s_contains, etc. |
| Temporal | t_before, t_after, t_intersects, etc. |
| Array | a_equals, a_contains, a_containedBy, a_overlaps |
| References | prop, rawProp |
| Literals | bbox, date, timestamp, interval |
| Extensions | fun, expr |
| JSON serialization | toJSON, stringify |
| Text serialization | toText from @sahitono/cql2-builder/text |
Supported operands
| API | Accepted operands |
|---|---|
| q(field, "like", pattern) | String queryables, including nullable and literal-union strings; pattern is a string or a casei/accenti expression |
| q(field, "in", values) | Non-empty list of values matching the field type |
| q.isNull(value) | Property reference or expression |
| q.between(value, lower, upper) | Numeric property or expression with numeric bounds |
| q.casei, q.accenti | String literal, string reference, or string expression |
| q.arithmetic and arithmetic helpers | Numeric literal, numeric reference, or numeric expression |
| Spatial predicates | GeoJSON geometry, q.bbox(...), geometry reference, or expression |
| Temporal predicates | q.date, q.timestamp, q.interval, temporal reference, or expression |
| Array predicates | Primitive array elements; use q.expr for richer elements |
| q.optional, q.andOptional | Nullable/undefined inputs and predicates |
Operator coverage
JSON coverage is provided by the builder. Text coverage is provided by toText from @sahitono/cql2-builder/text, which uses the pinned cql2-filters-parser.
| Family | JSON coverage | Text coverage |
|---|---|---|
| Comparison | =, <>, <, <=, >, >= | Verified |
| Logical | and, or, not | Verified |
| Null | isNull | Verified; not(isNull(...)) renders IS NOT NULL |
| Advanced comparison | like, between, in | Verified; quoted and empty string literals are escaped |
| String modifiers | casei, accenti | Verified; text keywords are case-insensitive |
| Arithmetic | +, -, *, /, %, div, ^ | Verified; nested expressions retain parentheses |
| Spatial | s_contains, s_crosses, s_disjoint, s_equals, s_intersects, s_overlaps, s_touches, s_within | Verified for GeoJSON geometries and BBOX literals |
| Temporal | t_after, t_before, t_contains, t_disjoint, t_during, t_equals, t_finishedBy, t_finishes, t_intersects, t_meets, t_metBy, t_overlappedBy, t_overlaps, t_startedBy, t_starts | Verified for date/timestamp intervals; interval endpoints must be strings or .. |
| Array | a_equals, a_contains, a_containedBy, a_overlaps | Verified for primitive elements; use q.expr for richer elements |
Text conversion gaps
- Interval endpoints that are property references or expressions are valid CQL2 JSON and supported by the builder, but the pinned parser cannot convert them.
toTextthrows a descriptive error for this case. - The typed array predicate API covers primitive elements. Nested arrays, property references, functions and arithmetic elements can be represented with
q.exprand are converted by the parser, but are not type-checked. - Temporal function names are emitted with a lowercase
t_prefix, for examplet_duringandt_finishedBy. CQL2 keywords are case-insensitive, so this does not change meaning.
The builder does not negotiate server capabilities. Optional operators still require server support.
Spatial and temporal predicates
q("geometry", "s_within", {
type: "Point",
coordinates: [110, -7],
})
q("createdAt", "t_before", q.timestamp("2026-10-18T00:00:00Z"))
q("createdAt", "t_intersects",
q.interval("2026-01-01", "2026-02-01"),
)Temporal examples assume createdAt is declared as a string queryable in the feature interface.
Custom functions and operators
// Server-defined function
q(q.fun<number>("AREA", q.prop("geometry")), ">", 1000)
// Custom predicate
q.expr<boolean>("custom_operator", q.prop("status"), "active")Custom expressions are not validated against server capabilities.
API integration
The resulting expression can be sent directly to an API that accepts CQL2 JSON.
await fetch("/api/features/search", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
filter,
"filter-lang": "cql2-json",
}),
})Scope
The builder provides compile-time type checking for property names, operators, and common value types. It does not perform runtime schema validation.
It does not parse CQL2 Text, evaluate filters, generate SQL, or verify server conformance. Text serialization is provided only by the optional subpath adapter.
Support for optional operators and custom functions depends on the receiving server.
