Filters
Narrow the collection by conditions on fields: from a simple equality to arbitrary and/or trees.
| URL key | filter |
| AST nodes | Filters (compound and/or) / Filter { operator, field, value } |
| Schema options | allowed, arrays, default, mapping, relations, validate |
Operators
Every dialect maps onto the same operator set (FilterFieldOperator):
| Operator | Meaning | Build key | Helper | Simple wire |
|---|---|---|---|---|
EQUAL | equals | $eq / bare scalar | eq | admin, 1, null |
NOT_EQUAL | not equals | $ne | ne | !admin |
LESS_THAN | < | $lt | lt | <18 |
LESS_THAN_EQUAL | <= | $lte | lte | <=18 |
GREATER_THAN | > | $gt | gt | >18 |
GREATER_THAN_EQUAL | >= | $gte | gte | >=18 |
IN | in list | $in / bare array | inArray | 1,2,3 |
NOT_IN | not in list | $nin | nin | !1,2,3 |
STARTS_WITH | prefix | $startsWith | startsWith | jo~ |
NOT_STARTS_WITH | not prefix | $notStartsWith | notStartsWith | !jo~ |
ENDS_WITH | suffix | $endsWith | endsWith | ~jo |
NOT_ENDS_WITH | not suffix | $notEndsWith | notEndsWith | !~jo |
CONTAINS | substring | $contains | contains | ~jo~ |
NOT_CONTAINS | not substring | $notContains | notContains | !~jo~ |
REGEX | pattern | $regex | regex | (none) |
MOD | divisible remainder | $mod | mod | (none) |
SIZE | array length | $size | size | (none) |
EXISTS | is not null | $exists | exists | (none) |
ELEM_MATCH | array element match | $elemMatch | elemMatch | (none) |
REGEX, MOD and EXISTS have no representation in the URL dialects; they work in code and via the MongoDB-style parser. ELEM_MATCH and SIZE travel in the expression dialect only.
Backend support varies per adapter. EXISTS works everywhere. REGEX and MOD evaluate in @rapiq/adapter-memory and render through @rapiq/adapter-sql / @rapiq/adapter-typeorm, each gated by a per-dialect callback (regex needs a regex-capable dialect, so the mssql and sqlite presets throw a typed error instead; mod needs a modulo spelling, which every shipped preset has, pg/mysql/sqlite/oracle via MOD() and mssql via the % operator, with one caveat for SQLite builds). @rapiq/adapter-prisma and @rapiq/adapter-drizzle raise a typed AdapterError (FEATURE_UNSUPPORTED) for regex, mod, size, the ITSELF marker and elemMatch on a to-one relation instead of approximating; see the limitations section of each package page. Before accepting regex from untrusted input, read the trust model below.
SIZE matches arrays with exactly the given number of elements (a non-negative integer); missing or non-array values never match, and there is no negated leaf twin (not(size(…)) stays a negated group). It evaluates in @rapiq/adapter-memory only: the SQL adapters throw a typed featureUnsupported until dialect-level JSON-array support lands, and the prisma/drizzle serializers have no array-length filter to target.
Inside an elemMatch interior, the reserved ITSELF marker (wire spelling $this) may take the field position of a condition to address the array element itself: elemMatch('scores', gt(ITSELF, 5)) matches when some score is greater than five. @rapiq/adapter-memory evaluates it element-wise; every other adapter throws a typed featureUnsupported (for the SQL adapters a joined relation row is not a scalar column, and prisma/drizzle cannot address the element itself). Anywhere outside an elemMatch interior the marker is a typed error.
On the wire (expression dialect)
The URL codec writes one expression by default, preserving compound structure and repeated fields:
codec=url-expression&filter=and(gte(age,'18'),or(eq(status,'active'),eq(status,'pending')))Most function names match the condition helpers in the table above; in keeps its wire spelling (inArray is only the code helper name). The negated leaf operators are the exception: nin has its own keyword, but ne, notContains, notStartsWith and notEndsWith are not expression keywords. On the wire they are spelled not(...) around the positive form, e.g. not(eq(name,'John')) for ne; decoding normalizes such a single twin-able leaf back to its negated twin (see Negation). Values are single-quoted; quote characters escape by doubling ('it''s').
Legacy simple input
Keys are field names (or relation.field paths); the value string encodes the operator:
filter[id]=1 equal
filter[name]=~jo~ contains
filter[age]=>=18 greater than or equal
filter[realm.name]=master nested field
filter[id]=1,2,3 in list
filter[email]=!null not nullThe v2 codec continues to decode this shape for existing clients. Multiple keys combine with and. Scalar coercion applies on decode: '18' → 18, 'true' → true, 'null' → null. The deprecated simple codec rejects duplicate same-field conditions and compound filters; use the default expression codec whenever a query needs either shape.
Wire strings vs. code
The !/</~ prefixes are the wire format. In code, use typed operator objects ({ age: { $gte: 18 } }) or condition helpers, never magic strings.
Building in code
The full grammar is covered in Building Queries; the short version:
import { and, defineQuery, eq, gte, or } from '@rapiq/core';
defineQuery<User>({
filters: {
name: 'John', // scalar → eq
'realm.id': [1, null], // array → in (null is legal)
age: { $gte: 18, $lt: 65 }, // operator object
},
});
defineQuery<User>({
filters: or(gte('age', 18), eq('deleted_at', null)), // condition trees
});Requiring an equal value
A sub-resource listing such as GET /post-tags often demands filter[postId]=<slug>, authorizes the parent first, and then swaps the slug for the resolved id. @rapiq/core exports two helpers for that:
import { findRequiredEqualValue, replaceRequiredEqualValue } from '@rapiq/core';
const slug = findRequiredEqualValue(query.filters, 'postId'); // 'my-post' | undefined
if (slug === undefined) {
throw new Error('filter[postId] is required');
}
const post = await findPost(slug);
const filters = replaceRequiredEqualValue(query.filters, 'postId', slug, post.id);findRequiredEqualValue(condition, field)returns the value of the firsteqleaf onfieldreached through the root orandgroups. Anor, anotor a custom condition requires nothing and is not entered. The value can be of any type.replaceRequiredEqualValue(condition, field, from, to)returns the tree (same node kind, value types widened) with everyeqleaf onfieldwhose value strictly equalsfromset toto, insideand,orandnotgroups alike: the slug and the id name the same parent, soeq(postId, slug) AND (eq(postId, slug) OR eq(featured, true))becomeseq(postId, id) AND (eq(postId, id) OR eq(featured, true))instead of keeping a branch that compares the stored id against the slug. A leaf holding any other value is kept as it is, so ineq(postId, a) AND eq(postId, b)only thealeaf is rewritten; the result can still match whentoequalsb. Other operators (ne,in, ...) and custom conditions are left alone.preservedis kept, untouched nodes are shared by reference, and the input itself is returned when nothing changed.
eq is case-insensitive by default (see Case sensitivity), so for strings "every match equals the value" holds up to case.
OR & compound trees
The simple object/wire dialect only expresses flat and sets. For or, not and nested groups:
- in code: condition helpers
or(...),and(...),not(...), arbitrarily nested; - over a URL: the expression codec,
filter=or(gte(age,'18'),eq(status,'active')); - in a request body: the MongoDB-style parser,
{ $or: [...] }.
Negation
not(condition) matches exactly the records its interior does not match, the complement law extended from the negated leaf operators to arbitrary trees:
import { and, defineQuery, eq, gt, not } from '@rapiq/core';
defineQuery<User>({
filters: not(and(eq('status', 'active'), gt('age', 65))),
});Where a negated leaf operator exists, not is the same condition (not(eq(…)) ≡ ne(…)); its value is negating conditions without a negated twin: ordering comparisons (not(gt(…))), size, elemMatch and whole groups. Multiple arguments negate their conjunction: not(a, b) ≡ not(and(a, b)).
On the wire, the expression dialect carries it as filter=not(gt(age,'65')); the legacy simple dialect cannot express it (encoding throws a typed error). SQL adapters render the negation null-inclusively (a CASE wrapper collapses SQL's three-valued UNKNOWN to false), so a record with age = NULL matches not(gt('age', 65)) on every backend, the same verdict @rapiq/adapter-memory produces.
Key-value relations
filter[attributes.department]=sales filters on one key of a key-value relation. Everything after attributes. is the key, dots included, and the filters validate hook sees field: 'attributes.department' on the parent schema. Two key-value filters match independently, each on its own row.
Nested fields
relation.field keys filter on related records. The relation must be listed in the schema's filters.relations (which defaults to relations.allowed, the relations default folded in); it does not have to be requested via relations, and an include of another relation does not drop the filter. A relation outside the list is a keyPathNotAllowed violation (dropped, or thrown under throwOnFailure). Without any list (and no relations default, which on its own becomes the allow-list) every name the registry resolves (directly or through schemaMapping) is permitted, unless the schema is strict; declare relations.allowed (or filters.relations) to restrict traversal. A name the registry cannot resolve is a keyPathInvalid parse error. Array operators that target a relation directly ($size, $all, $elemMatch in mongo; size(), elemMatch() in the expression dialect) are checked against the same list. Their target counts as a relation when the registry resolves it or the schema declares it in schemaMapping, relations.allowed or filters.relations, unless it is listed in filters.arrays (see Array columns). The field validates against the related schema through schemaMapping.
Array columns
An array operator (size, elemMatch, all) on a field that is not a relation targets a JSON array column. filters.arrays declares those columns:
const postSchema = defineSchema<Post>({
name: 'post',
filters: {
allowed: ['id', 'slug', 'labels'],
relations: ['postTags'],
arrays: ['labels'],
},
});- Declared: an array operator may target a relation (checked against
filters.relations, as above) or a listed column. Any other target, e.g.elemMatch(id, …), is akeyNotAllowedviolation (dropped, or thrown underthrowOnFailure; the expression dialect always rejects).arrays: []refuses every non-relation target. - Undeclared: every non-relation target is permitted, unless the schema is strict.
- Collisions: a listed name is always an array column, never a relation, even when a registered schema shares its name. A JSON column named like a registered schema therefore belongs in
arrays. - Never a relation: a listed column is no relation, so its relation gating and the relations
validatehook would not apply to it. Listing a name the schema also declares a relation (inrelations.allowed,relations.default,relations.keyValue,filters.relationsorschemaMapping) throws aSchemaError(codekeyInvalid) when the schema is defined. With a typed schema,arraysadmits only keys holding an array of scalars, dates, nested arrays or index-signature records: an array of records with declared keys reads as a to-many relation, so type such a JSON column's element asRecord<string, any>to list it.assertSchemaMatchesEntityandassertSchemaMatchesModelreport an entry that is a relation or no column of the entity or model.
Where an array operator's interior resolves depends on its target:
- A registered relation: the interior is bound to the related schema, and every hop inside it is checked against that schema's policy, exactly like a dotted path.
- A JSON array column listed in
arrays: the interior is an element scope. A dotted key inside it, e.g.elemMatch(labels, eq(meta.kind, 'x')), is an opaque path into the array element, checked for identifier validity only (a reserved segment,__proto__,constructororprototype, is akeyInvalidviolation in every element scope); it is never resolved against a registered schema or relation, so an interior cannot reach a relation around the schema'sfilters.relations. - Any other target: a declared relation whose schema is not registered (in
relations.allowed,filters.relationsorschemaMapping), or a columnarraysdoes not list (permitted whilearraysis undeclared). Such a column may be a relation the schema never declared, and the SQL adapters join every dotted interior key from it, so it gets the conservative interior: a single-segment key inside the interior addresses a column of the related row; a dotted key would join on from it, so it is akeyPathInvalidviolation, the same verdict the dotted path gets at the top level. A nested array operator on a column of that row (elemMatch(author, size(company, '1'))) is akeyPathInvalidviolation too: the row's columns are unknown, so its target may be a relation the backend would join. List a JSON array column inarraysto address nested element paths such asmeta.kind.
A nested interior keeps these rules: an ITSELF target (elemMatch($this, …), or mongo's { $elemMatch: { $elemMatch: … } }) stays in the scope it is in, and an element interior never regains dotted access to relations. Without any schema (a schemaless parse) a target still descends into a registered schema by name.
Null semantics
null is a first-class filter value with SQL-consistent behavior across all adapters:
| Filter | Meaning |
|---|---|
eq(field, null) | field IS NULL |
ne(field, null) | field IS NOT NULL |
inArray(field, [a, null]) | field IN (…) OR field IS NULL |
exists(field) | field IS NOT NULL |
Negated operators (ne, nin, notContains, notStartsWith, notEndsWith) are exact complements of their positive twins: for values that don't name null themselves, they also match records where the field is NULL/absent, e.g. ne(field, a) → (field <> ? OR field IS NULL). When the negated value does name null, the complement excludes those records instead: nin(field, [a, null]) matches neither a nor NULL/absent, precisely because inArray(field, [a, null]) matches both.
The same complement law governs not(...) over whole trees: not(c) selects exactly the records c does not, on every backend.
Date values
The wire is untyped: a date crosses it as a string (filter[created_at]=>=2026-08-23T00:00:00.000Z), never as a Date. Each adapter reads that operand back into the form its backend compares against, so a date column can join a filters.allowed list and a time window is an ordinary range filter:
| Adapter | Binds |
|---|---|
@rapiq/adapter-typeorm | the column's own storage literal: a UTC wall-clock string for a zone-less datetime/timestamp column, the ISO instant for a timestamptz, YYYY-MM-DD for a date |
@rapiq/adapter-prisma, @rapiq/adapter-drizzle | a Date instance |
@rapiq/adapter-memory | reads the string as an instant whenever the record value is a Date |
Accepted operand forms are an ISO-8601 date (2026-08-23) or date-time (2026-08-23T10:16:44.000Z, a space in place of the T is fine too), an epoch timestamp in milliseconds, and a Date. The grammar is matched explicitly rather than handed to new Date(), which accepts implementation-defined forms (August 23, 2026 parses, 2026 silently means January 1st) and rolls a day the calendar does not have into the next month, so 2026-02-30 would quietly select March 2nd. A date-time carrying no offset is read as UTC, not in the server's zone, so one query selects the same rows on every machine.
A value that denotes no instant (filter[created_at]=yesterday, 2026-02-30) is refused with an AdapterError carrying ErrorCode.KEY_VALUE_INVALID instead of reaching the driver, which answers a malformed client value with a server error. Only the bindings that know the field is temporal can refuse: @rapiq/adapter-typeorm on a date column, and @rapiq/adapter-prisma/@rapiq/adapter-drizzle on a field their metadata marks as a date. @rapiq/adapter-memory has no such declaration and simply leaves the value unequal and incomparable, and @rapiq/adapter-sql's default bindValue passes every operand through untouched.
@rapiq/adapter-typeorm refuses the same way on a uuid column: an equality, ordering or in/nin operand that is not a uuid raises ErrorCode.KEY_VALUE_INVALID instead of failing the query on Postgres or matching nothing on SQLite and MySQL.
Zone-less columns are read as UTC
A datetime/timestamp column stores no offset, so the operand has to be spelled in the same zone the value was written in, and rapiq spells it in UTC.
Binding a Date instead is not an alternative: the Postgres and MySQL drivers serialize one in the host's local zone, and a zone-less column discards the offset marker, so the same query would select different rows on different machines.
The consequence is worth knowing: TypeORM's SQLite driver writes such a column in UTC unconditionally, but its Postgres and MySQL drivers hand the driver a Date, so on a host whose clock is not UTC they write local wall clock. Run the application (or the connection) in UTC, which is what a server normally does, or use a zone-aware column type (timestamptz). Rows written by a database default such as now() are unaffected.
Which fields are temporal comes from the adapter's own knowledge of the backend: TypeORM reads the entity metadata, @rapiq/adapter-prisma and @rapiq/adapter-drizzle ask their metadata (a DateTime field, or a column whose dataType is date), and @rapiq/adapter-memory sees the record value itself. @rapiq/adapter-sql emits placeholders and leaves binding to the caller, so it binds operands unchanged; override bindValue(field, value) on its filters adapter to hook in a column-type table of your own.
Only equality and ordering operands are read this way. A contains/startsWith pattern or a mod divisor is not a value of the column's domain and passes through untouched.
Literal text matching
contains, startsWith, endsWith and their negations match literal operands, including %, _, brackets and backslashes. The adapters escape each backend's pattern syntax. Prisma with SQLite refuses % and _ with a typed AdapterError because its filter API cannot express them literally.
Numeric anchored matching uses the column's text representation: contains('age', '1') matches 18. The TypeORM adapter casts known non-string PostgreSQL columns to text for these operators; equality retains numeric comparison. Text formatting for other types remains engine-dependent.
Case sensitivity
String matching is case-insensitive by default, uniformly across every adapter: the same query matches the same records whether it runs on Postgres, MySQL, in memory, or through TypeORM:
- The equality family (
eq,ne,in,nin) compares string values case-insensitively:eq('name', 'super hero')matchesSuper Hero. Non-string values (numbers, booleans, dates,null) are unaffected. - The anchored operators (
contains,startsWith,endsWithand their negations) match case-insensitively as well, and honour the same opt-out. - Range comparisons (
lt/lte/gt/gte) andsortsfollow the backend's collation; rapiq does not fold string ordering.
Opt out per field with the caseSensitive schema option where exactness matters (identifiers, tokens, enum-like codes):
const schema = defineSchema<User>({
filters: {
allowed: ['id', 'name'],
caseSensitive: ['id'],
},
});The receiving side forwards the list to its adapter:
// @rapiq/adapter-sql & @rapiq/adapter-typeorm
adapter.execute(query, { caseSensitive: schema.filters.caseSensitive });
// @rapiq/adapter-memory
applyQuery(query, data, { caseSensitive: schema.filters.caseSensitive });The key is the same on every backend: @rapiq/adapter-prisma and @rapiq/adapter-drizzle accept caseSensitive in their constructor options, and their execute() options take a per-call override of the adapter-level setting.
Passing caseSensitive: true instead of a list opts every field out of the fold at once: for condition trees whose field keys aren't known upfront, e.g. caller-supplied authorization policies. The collation caveat below applies unchanged: on the MySQL/MSSQL presets matching delegates to the column collation either way, so a *_ci collated column still matches case-insensitively.
Under the hood, @rapiq/adapter-sql folds both sides of the comparison: lower(field) = lower(?) for equality (only when the filter value is a string), and lower(field) like lower(?) escape '!' for the anchored operators, which render as LIKE on every dialect and stringify their value first. Dialects that already compare case-insensitively skip the fold, so plain indexes stay usable: MySQL and MSSQL for both families (their default *_ci collations), and SQLite for LIKE only (its LIKE is ASCII-case-insensitive, its = is not).
On folding dialects, index the shape you actually emit. On Postgres the two families need different indexes, because an operator class that serves = does not serve a prefix LIKE under a non-C collation:
-- serves lower(name) = lower($1) (eq / ne / in / nin)
CREATE INDEX ON "user" (lower(name));
-- serves lower(path) LIKE lower($1) (startsWith, folded)
CREATE INDEX ON "user" (lower(path) text_pattern_ops);
-- serves path LIKE $1 (startsWith, path listed in caseSensitive)
CREATE INDEX ON "user" (path text_pattern_ops);Measured on Postgres 18.4: a default en_US.utf8 btree serves none of the LIKE forms, and only startsWith can use a btree at all. For contains and endsWith on Postgres, index the folded expression with trigrams:
CREATE INDEX ON "user" USING gin (lower(name) gin_trgm_ops);A gin (name gin_trgm_ops) index without the lower() does not serve the folded comparison, so a column that relied on one for contains needs the index recreated or the column listed in caseSensitive.
The TypeORM adapter goes one step further: it resolves each filtered field against the entity metadata and folds only string-typed columns. Numeric, date, uuid or enum columns never pay the lower() cost, even when the value arrives as an untyped wire string like filter[age]=18.
Collation wins on MySQL/MSSQL, and on SQLite for LIKE
On the MySQL/MSSQL presets, matching delegates to the column collation: caseSensitive cannot force exactness onto a *_ci collated column. The same holds for the anchored operators on SQLite, whose LIKE is ASCII-case-insensitive whatever the option says (its =, and therefore the equality family, does honour the opt-out). Use a *_bin/*_cs collation for such columns, or override caseFold with a lower()-wrapping implementation (caseFoldLike, which governs the LIKE comparisons, inherits it unless the dialect sets its own).
MySQL's default utf8mb4_0900_ai_ci also folds accents for LIKE: 'APFEL' LIKE 'ä%' is 1. So startsWith('name', 'ä') matches APFEL on MySQL, and does not on Postgres. A *_as_cs collation is the fix where that matters.
Where an engine ignores the opt-out, @rapiq/adapter-memory does not, so an opted-out anchored filter can return different records in memory than on MySQL or SQLite. Note also that folding a character(n) column on Postgres drops its padding, so an endsWith on a blank-padded column matches where the unfolded comparison does not.
Schema options
defineSchema<User>({
filters: {
allowed: ['id', 'name', 'age'],
mapping: { aliasId: 'id' },
default: eq('status', 'active'),
// accept (return the filter), replace (return any condition,
// including a compound), or reject (return undefined); a hook
// that returns nothing rejects every filter.
validate: async (filter) => filter,
},
});| Option | Description |
|---|---|
allowed | Filterable field names. Omit to allow all; [] blocks the parameter. |
default | Condition applied when the client sends no filters. |
mapping | Alias → field translation applied before validation. |
relations | Relations a filter may traverse (relation.field keys and array operators on a relation). Defaults to relations.allowed (with the relations default folded in); see Nested fields. |
arrays | JSON array columns an array operator (size, elemMatch, all) may target. Undeclared: every non-relation target is permitted unless strict; [] refuses them all. See Array columns. |
validate | Sync or async per-filter hook: inspect a parsed Filter, replace it with any condition, or reject it. The root schema's hook judges every leaf under its full path; the hook of a related schema additionally judges the leaves whose field it owns (relation.field keys, elemMatch interiors). Receives the parse context as its second argument. |
caseSensitive | Fields whose equality comparisons stay exact instead of the case-insensitive default. |
indexed | Check the parsed tree against the schema indexes declaration: 'anchor' (or true) requires one index-leading conjunct per AND group, 'cover' full prefix coverage. See Indexes. |
validate runs after key resolution, mapping and value coercion, and receives the caller-supplied context (e.g. the authenticated actor) as its second argument. Return the original filter to accept it, another condition to replace it, or undefined to reject that leaf; an inspect-only hook must still return the filter, otherwise every leaf is rejected. The replacement may be any condition, including a compound: an authorization decision like "you may filter on realm_id, but only within your realms" stays attached to the leaf that triggered it, and(filter, preserve(inArray('realm_id', actor.realmIds))), instead of being injected separately after the parse. $elemMatch conditions are validated inside-out: every interior leaf passes its hook, then the elemMatch filter itself. The return value may also be a Promise of any of those results. On the server, schema-aware encoding re-runs the schema-bound decoder, so a validator that is not idempotent (e.g. one that appends to the value) transforms a filter twice between a schema-aware encode() and the receiving decode(): keep validators idempotent.
Each leaf is judged by up to two hooks, and must pass both:
- The hook of the schema that owns its field, with the field relative to that schema, the same target-schema authorization the key hooks follow.
filter[realm.secret]reaches the realm schema's hook assecret(resolved throughschemaMapping); a multi-hop key (items.realm.secret) reaches the hook of its last hop. A leaf insideelemMatch(realm, …)reaches the realm schema's hook under its interior name, and$thisinside such a relation interior (the related record) is judged by the realm schema's hook as$this. A leaf inside the element of a JSON array column reaches the hook of the schema that owns the column under the column-prefixed path:elemMatch(tags, eq(name, 'x'))is judged astags.name, the element itself ($this) astags. A key-value key stays with the parent schema's hook under the full name (attributes.department). - The root schema's hook, for every leaf the root does not own itself, under the leaf's full path from the query root:
realm.secretforfilter[realm.secret]and for asecretleaf insideelemMatch(realm, …)alike,realm.tags.namefor an element leaf of a column the realm owns.$thisinside an interior reaches it as the path of the interior (realm,realm.tags). A root hook that guards a dotted key therefore covers every way of reaching it.
The owner hook runs first; a rejection by either ends the judgement. The elemMatch (or size) leaf itself is judged the same way, by the hook owning its target (realm on the root) and the root hook under its full path.
A leaf on a JSON array column and an element condition arrive under the same field: eq(tags, 'x') and elemMatch(tags, eq($this, 'x')) both reach the hook as an eq leaf on tags. The element condition is always followed by the elemMatch leaf on tags itself (operator elemMatch), so a hook that gates the column by rejecting that leaf covers both; to tell them apart, gate on the elemMatch leaf rather than the inner one.
A replacement is placed back where the leaf was. Fields of an owner hook's replacement are relative to the owning schema, those of the root hook's to the query root, and the parser re-prefixes them: a realm hook returning and(filter, eq('tenant', 't1')) for filter[realm.secret] yields and(eq('realm.secret', …), eq('realm.tenant', 't1')), and inside an elemMatch(realm, …) the replacement stays relative to that interior. Inside an array element, return fields under the column path (tags.label) and spell the element itself $this: they are made relative to the element again. The root hook's replacement wraps the owner hook's: where the root hook returns the leaf, the owner's replacement takes its place.
A top-level conjunct of a replacement that addresses only fields outside an elemMatch interior is hoisted next to that elemMatch leaf, at the position it belongs to: a root hook returning and(filter, preserve(eq('tenant_id', …))) for a leaf inside elemMatch(tags, …) yields and(elemMatch(tags, …), tenant_id …). A replacement the parser cannot place rejects the leaf, as if the hook had returned undefined: a field on the column (or relation) path itself (it would silently turn into a condition on the element), a conjunct mixing fields inside and outside the interior, a replacement leaving nothing at the leaf's position, $this returned for a relation.field leaf, or a custom condition the parser cannot re-prefix. The client chooses between spellings such as realm.name and elemMatch(realm, eq(name, …)), so the spelling must not turn a request into a server error. A rejected leaf follows the failure policy of the schema whose hook rejected it; a call-time throwOnFailure still wins. A schema without a filters hook accepts the leaves it owns.
Return a fresh residual on every call: a hook returning one shared, module-level preserve(...) constant hands the same node to every request, and the parser tracks residuals by node identity.
All filter composition is ordered logical AND, so a later merge carries the complete replacement as a conjunct and never removes it. The deprecated simple URL dialect cannot express compounds: schema-aware encoding through it throws FEATURE_UNSUPPORTED for a query whose validator produced one; the default expression dialect encodes it.
Preserve the residual, not the whole group. preserve(and(filter, ...)) also keeps the client leaf from being pruned by a rejected relation. With and(filter, preserve(...)), the client leaf prunes normally and only a residual that itself needs a rejected relation raises SchemaError (ErrorCode.SCHEMA_PRESERVED_CONDITION_PRUNED). That is the genuine validator contradiction, for the residual of the root schema's hook. A residual the hook of a related schema returns sits under the relation the client traversed to reach it (filter[realm.name] with a realm hook returning and(filter, preserve(eq('tenant', …))) yields realm.tenant): when the relations hook rejects that relation, the request fails as a client error instead of a SchemaError: under a dropping policy the client leaf that brought the residual is refused with KEY_PATH_NOT_ALLOWED, under a throwing one the relation rejection itself is raised. Nothing is dropped silently, so the query never widens. preserve() exists for this relation-pruning policy, not filter composition.
Use the synchronous parse() / decode() / schema-aware encode() methods when every validator is synchronous. Use their Async counterparts when a validator may be asynchronous:
const query = await parser.parseAsync(input, { schema });
const decoded = await codec.decodeAsync(req.query, { schema });
const encoded = await codec.encodeAsync(query, { schema });The async path awaits validators sequentially in filter-tree order. Calling a synchronous method when a validator returns a Promise/thenable throws a SchemaError with SCHEMA_VALIDATOR_ASYNC_REQUIRES_ASYNC_PARSER. Compound and/or structure is preserved; if every submitted leaf is rejected, the schema default is applied.
Regex trust model
The regex operator's pattern is passed through to the consuming engine; rapiq does not analyze, rewrite or sandbox it:
@rapiq/adapter-sqland@rapiq/adapter-typeormhand the pattern to the database engine to interpret and validate: the engine's own syntax checks, limits and timeouts govern it.@rapiq/adapter-memorycompiles the pattern with JavaScript's backtrackingRegExpengine and evaluates it against every record; a crafted pattern (nested quantifiers such as(a+)+$) over long field values can burn CPU (ReDoS). Compilation rejects invalid syntax, not pathological patterns.
Whether a hostile pattern can reach an evaluator depends on the input dialect:
- The URL dialects cannot carry one:
regexhas no wire spelling, so queries decoded by@rapiq/codec-urlnever contain a regex condition. - The MongoDB-style parser accepts
$regex(a pattern string orRegExp) from client documents.
Gate $regex for untrusted clients
An application that parses untrusted mongo-style filter documents and evaluates them in-process with @rapiq/adapter-memory must gate the operator; the allowed list does not help, since $regex applies to allowed fields.
The validate hook sees every parsed leaf and can reject regex conditions:
import { FilterFieldOperator, defineSchema } from '@rapiq/core';
const schema = defineSchema<User>({
filters: {
allowed: ['id', 'name'],
validate: (filter) => {
// reject client-submitted regex conditions
if (filter.operator === FilterFieldOperator.REGEX) {
return undefined;
}
return filter;
},
},
});A root schema's hook sees every leaf under its full path (see Schema options), so a $regex gate on the root also covers realm.name; the realm schema's own hook judges it as well, so a gate declared there covers every root that reaches the realm.
A leaf rejected by validate follows the same drop-vs-throw policy as every other rejection: it is dropped by default, and raises KEY_VALIDATE_REJECTED under throwOnFailure, where it appears in the trace the error carries. A dropped leaf is not reported: the raised error is the only channel. To drop a leaf quietly under a throwing schema, return a replacement condition instead of undefined. Softer gates work the same way: cap the pattern's source length or match it against a vetted list, and return the filter when it passes.
On violation
Legacy simple and MongoDB field-key failures follow the schema's drop-vs-throw policy. Expression filters are precise: syntax and schema-key violations always fail the parse, recorded on the issue trace of the raised inputRejected error. See Error Handling.