@uniqu/url
v0.2.2
Published
URL query string parser producing the Uniqu canonical query format
Readme
@uniqu/url
URL query string parser and builder for the Uniqu canonical query format. Human-readable URL syntax with full filter expressions, sorting, pagination, projection, and aggregation.
Install
pnpm add @uniqu/urlUsage
import { parseUrl } from '@uniqu/url'
const { filter, controls, insights } = parseUrl(
'age>=18&status!=DELETED&name~=/^Jo/i&$select=name,email&$limit=20'
)Result:
filter = {
age: { $gte: 18 },
status: { $ne: 'DELETED' },
name: { $regex: '/^Jo/i' },
}
controls = {
$select: ['name', 'email'],
$limit: 20,
}
insights = Map {
'age' => Set { '$gte' },
'status' => Set { '$ne' },
'name' => Set { '$regex', '$select' },
'email' => Set { '$select' },
}Query Syntax
Comparison Operators
| Syntax | Operator | Example | Result |
|--------|----------|---------|--------|
| = | $eq | status=ACTIVE | { status: 'ACTIVE' } |
| != | $ne | status!=DELETED | { status: { $ne: 'DELETED' } } |
| > | $gt | age>25 | { age: { $gt: 25 } } |
| >= | $gte | age>=18 | { age: { $gte: 18 } } |
| < | $lt | price<100 | { price: { $lt: 100 } } |
| <= | $lte | price<=99.99 | { price: { $lte: 99.99 } } |
| ~= | $regex | name~=/^Jo/i | { name: { $regex: '/^Jo/i' } } |
Lists (IN / NOT IN)
role{Admin,Editor} → { role: { $in: ['Admin', 'Editor'] } }
status!{Draft,Deleted} → { status: { $nin: ['Draft', 'Deleted'] } }
role{} → { role: { $in: [] } } (matches nothing)
role!{} → { role: { $nin: [] } } (excludes nothing)An empty list is kept as written, never rewritten to "no constraint": !(role{}) matches every row, and role{}&role{a} stays two $and members. {,}, {a,} and {,a} are still a SyntaxError. Up to 0.1.12 role{} (which buildUrl emits for an empty $in) threw on parse.
Between
25<age<35 → { age: { $gt: 25, $lt: 35 } }
25<=age<=35 → { age: { $gte: 25, $lte: 35 } }Exists
$exists=phone,email → { phone: { $exists: true }, email: { $exists: true } }
$!exists=deletedAt → { deletedAt: { $exists: false } }Negation (NOT)
!(...) negates a grouped expression:
!(status=DELETED)
→ { $not: { status: 'DELETED' } }
!(age>18&status=active)
→ { $not: { age: { $gt: 18 }, status: 'active' } }
!(status=DELETED^status=ARCHIVED)
→ { $not: { $or: [{ status: 'DELETED' }, { status: 'ARCHIVED' }] } }$not can be combined with other operators via & and ^:
!(role{Guest,Anonymous})&age>=18
→ { $and: [{ $not: { role: { $in: ['Guest', 'Anonymous'] } } }, { age: { $gte: 18 } }] }Relational Predicates ($some / $none)
<navField>=$some(<expr>) / <navField>=$none(<expr>) filters by the existence of related rows. The body is a full filter expression on the related entity (any operators, &, ^, groups, !( ), nested predicates); an empty body means "has any" / "has none":
ticket=$some(teamId{t1,t2}&status=open)
→ { ticket: { $some: { teamId: { $in: ['t1', 't2'] }, status: 'open' } } }
ticket=$none()
→ { ticket: { $none: {} } }
ticket=$some(team=$none(name=Ops))
→ { ticket: { $some: { team: { $none: { name: 'Ops' } } } } }
ticket=$some(a=1)&ticket=$none(b=2)
→ { ticket: { $some: { a: 1 }, $none: { b: 2 } } }- Only
=introduces a predicate. Negate with$none(…)or!(…);ticket!=$some(…)is aSyntaxError. - An
&inside the parentheses does not split the query string, so predicates combine freely with other filters and controls:ticket=$some(status=open)&title~=/crash/i&$limit=20. - Predicates are valid inside
$withbodies too:$with=tickets(issues=$some(title=x)). - Insights record the navigation field with
$some/$noneand the body's fields with the field prefix (ticket.teamId,ticket.status). - Nesting is capped at 32 levels (
SyntaxErrorbeyond); an unterminated body (ticket=$some() is aSyntaxError. buildUrlthrows aTypeErrorfor an operand that is not a filter object (null, an array, a string) and for one that matches no row ({ $or: [] },{ $not: {} }): such an operand would serialize to the empty body, which means "any related row".- The same holds for the whole filter: a filter that matches no row (
{ $or: [] }, or any AND with such a member, e.g.{ status: 'open', $or: [] }) throws, because an empty query string means "every row". An empty member is never dropped when that would change the result: a never-matching member makes its AND match nothing, an every-row member ({}) makes its OR match everything. - Hand-written URLs: a quoted value may hold a raw
(,)or&(title='a)b', see Percent Encoding); an unquoted one must percent-encode it (title=a%29b).buildUrlalways encodes them.
Logical Operators
& is AND (higher precedence), ^ is OR (lower precedence). Parentheses override precedence:
age>25^score>550&status=VIP
→ { $or: [{ age: { $gt: 25 } }, { score: { $gt: 550 }, status: 'VIP' }] }
(age>25^score>550)&status=VIP
→ { $and: [{ $or: [{ age: { $gt: 25 } }, { score: { $gt: 550 } }] }, { status: 'VIP' }] }Comparison fields and a logical operator in the same filter object are ANDed
together (see the @uniqu/core README),
so buildUrl emits them &-joined and parenthesizes an $or that has
siblings: { id: 101, $or: [{ s: 'a' }, { s: 'b' }] } → id=101&(s=a^s=b).
Conversely, a multi-part AND inside an $or is always parenthesized, whether
it is an explicit $and or an implicit one:
{ $or: [{ $and: [{ a: 1 }, { b: 2 }] }, { c: 3 }] } → (a=1&b=2)^c=3.
Adjacent AND conditions on the same field are merged when safe:
age>=18&age<=30 → { age: { $gte: 18, $lte: 30 } }Literal Types
| Syntax | Type | Examples |
|--------|------|---------|
| Bare number | number | 42, -3.14, 0 |
| Leading zero | string | 007, 00, 01 |
| true / false | boolean | flag=true |
| null | null | deleted=null |
| 'quoted' | string | name='John Doe' |
| Bare word | string | status=ACTIVE, type=nullable |
| Bare word with interior - | string | status=in-progress, date>=2026-01-01, id=a1b2-c3d4 |
| Bare local date-time | string | hour=2026-03-29T14:00, at>=2026-03-29T14:00:30 |
| /pattern/flags | string | name~=/^Jo/i |
A bare value is a number, boolean or null only when the whole word is one (nullable, 1.5.3, 5-3 and 2026-01-01 are strings). A leading - is a negative number (a>-5); a value starting or ending with - (-x, x-) and a hyphenated field name are a SyntaxError — quote the value ('-x'). There is no date type: a bare date is the string '2026-01-01', and a bare YYYY-MM-DDTHH:MM[:SS] (an 'hour' bucket label) the string '2026-03-29T14:00'. Any other value with : (Z, fractions, offsets: '2026-03-29T14:00:00.000Z') must be quoted.
Percent Encoding
All parts are decoded with decodeURIComponent() before parsing. Encode special characters in URLs:
name=%27John%20Doe%27 → name: 'John Doe'
name~=%2F%5EJo%2Fi → name: { $regex: '/^Jo/i' }
$search=Maison%20%26%20O%27Brien%20%231 → $search: "Maison & O'Brien #1"A $with relation body is itself a query string, so it is decoded once more when parsed: a value inside a body needs one more level of encoding than at the top ($with=posts(name='50%2525') → '50%'). Building a $with value with URLSearchParams or encodeURIComponent produces exactly that. A body segment that is not valid percent-encoding at that second decode is kept as written, so a hand-written $with=posts(name='50%25') also yields '50%'.
A single-quoted value is kept whole when the query string is split, at every level, so it may hold raw (, ) and & (name=')'&x=1, $having=n=')', count(*|name='(a&b'):n). A ' starts a quoted value only at the start of a token (after =, an operator, (, ,, |, ^, &, {, + or any whitespace the parser skips — space, tab, line break, no-break space — or the percent-encoded form of one, such as %3D, %20, %09 or %C2%A0, as encodeURIComponent leaves ' raw; %2B is not one) and only when it is closed, so an apostrophe inside a word stays an ordinary character ($search=it's, $with=posts($search=o'neil)). buildUrl percent-encodes these characters anyway.
Control Keywords
Control keywords start with $ and are separated from filter expressions:
| Keyword | Aliases | Example | Result |
|---------|---------|---------|--------|
| $select | — | $select=name,email | { $select: ['name', 'email'] } |
| $order | $sort | $order=-createdAt,score | { $sort: { createdAt: -1, score: 1 } } |
| $limit | $top | $limit=20 | { $limit: 20 } |
| $skip | — | $skip=40 | { $skip: 40 } |
| $count | — | $count | { $count: true } |
| $groupBy | — | $groupBy=currency,region | { $groupBy: ['currency', 'region'] } |
| $having | — | $having=total>1000 | { $having: { total: { $gt: 1000 } } } |
| $with | — | $with=posts,author | { $with: [{ name: 'posts', filter: {}, controls: {} }, ...] } |
| $from | — | $from=($groupBy=userId&$select=count(*):n) | { $from: { $groupBy: ['userId'], $select: [...] } } (two-level aggregate) |
| $<custom> | — | $search=term | { $search: 'term' } |
Prefix a field with - in $select to exclude it. When any exclusion is present, $select produces an object ({ name: 1, password: 0 }); otherwise it produces an array (['name', 'email']). Prefix with - in $order for descending sort.
NULL placement in $sort
Suffix a sort key with :first or :last to put NULL (and missing) values before or after every other value, whatever the direction. Keys without a suffix keep the backend's default placement:
$sort=-amount:last,name:first,id → { $sort: { amount: -1, name: 1, id: 1 }, $nulls: { amount: 'last', name: 'first' } }
$rowOrder=raisedAt:first,-id → { $rowOrder: { raisedAt: 1, id: -1 }, $nulls: { raisedAt: 'first' } }- Works on
$sort, its alias$order, and$rowOrder, including inside$withbodies.$sortvalues stay1 | -1; the placement lands in the sibling$nullscontrol, shared by$sortand$rowOrder. - The suffix follows the last
:(author.name:last→ fieldauthor.name). - Throws
SyntaxError: a suffix other than exactlyfirst/last(a:middle,a:,a:LAST), a suffix with no field (:first), two different placements for one field ($sort=a:first&$rowOrder=a:last), and a$nulls=…segment ($nullshas no URL form of its own). A sort key containing:without a valid suffix ($sort=a:b) is therefore an error; before 0.1.15 it parsed as the fielda:b. - Whether a backend supports the placement, and whether to reject it, is up to the consumer.
Aggregate Functions in $select
$select supports aggregate function calls using fn(field) syntax. An optional alias can be specified with :alias:
$select=sum(amount) → [{ $fn: 'sum', $field: 'amount', $as: 'sum_amount' }]
$select=sum(amount):total → [{ $fn: 'sum', $field: 'amount', $as: 'total' }]
$select=count(*) → [{ $fn: 'count', $field: '*', $as: 'count_star' }]
$select=countDistinct(customerId) → [{ $fn: 'countDistinct', $field: 'customerId', $as: 'countDistinct_customerId' }]
$select=countDistinct(customerId):n → [{ $fn: 'countDistinct', $field: 'customerId', $as: 'n' }]
$select=sum(amount),currency → [{ $fn: 'sum', $field: 'amount', $as: 'sum_amount' }, 'currency']When no alias is given, one is auto-generated as {fn}_{field} (with * becoming star, and a field list joined with _).
countDistinct over several fields
$select=countDistinct(userId,day) → [{ $fn: 'countDistinct', $field: ['userId', 'day'], $as: 'countDistinct_userId_day' }]
$select=countDistinct(userId,day):n → [{ $fn: 'countDistinct', $field: ['userId', 'day'], $as: 'n' }]
$select=countDistinct(userId) → [{ $fn: 'countDistinct', $field: 'userId', $as: 'countDistinct_userId' }]It counts distinct combinations; a row where any listed field is NULL is not counted. Only countDistinct takes several fields: sum(a,b) or any other function with a list is a SyntaxError.
Conditional aggregates: fn(field|<filter>):alias
Text after a | inside the call parentheses is a filter: the aggregate's $where. Only rows matching it are counted or summed. The filter uses the full query grammar (&, ^, !(…), groups, lists, quoted values, $exists=), the same way $having does, and the alias is required:
count(*|status=ESTIMATED):estimated → { $fn: 'count', $field: '*', $as: 'estimated', $where: { status: 'ESTIMATED' } }
sum(hours|billable=true^kind=support):bill → { $fn: 'sum', $field: 'hours', $as: 'bill', $where: { $or: [...] } }
countDistinct(userId,day|status{open,new}):n → { $fn: 'countDistinct', $field: ['userId', 'day'], $as: 'n', $where: { status: { $in: [...] } } }
sum(price*qty|paid=true):revenue → { $fn: 'sum', $expr: …, $as: 'revenue', $where: { paid: true } }
count(*|(a=1^b=2)&!(c=3)):x → nested groups work as in a filter- The condition starts at the first
|. A field list and an expression never contain one, so a|inside a quoted value of the condition (name='a|b') needs no escaping. - An
&inside the parentheses does not split the query string, and,inside{…}lists does not split$select. Values follow the usual quoting and percent-encoding rules (buildUrlencodes% & ( ) #inside quoted values). - Throws
SyntaxError: a condition without an:alias(count(*|a=1)), an empty condition (count(*|):n), a malformed one (the message names the item), and a condition onexpr(…)orbucket(…)("a condition applies to aggregates only"). - A quoted value inside the condition may hold raw
(,),&or|(count(*|name=')'):n): the query string is split with quoted values kept whole (see Percent Encoding). - The fields of a condition are reported in insights like filter fields (
status→$eq), so a server that gates filterable fields gates conditions too.
Supported functions: sum, count, countDistinct, avg, min, max, first, last, plus any custom function name — consumers validate supported functions. See the core README for their semantics and for validateAggregateExpr. The parser checks syntax only: any fn(*) parses, although only count(*) is valid.
Arithmetic over fields and first / last have their own forms, below.
When aggregates are present, $select always uses the array form (even if - prefixed fields are mixed in). Entries keep their URL order.
Arithmetic and first / last in $select
An aggregate over a per-row expression, and arithmetic over other $select aliases:
$select=sum(price*qty):rev → [{ $fn: 'sum', $expr: { $op: '*', $args: ['price', 'qty'] }, $as: 'rev' }]
$select=expr(est/open):avgEst → [{ $expr: { $op: '/', $args: ['est', 'open'] }, $as: 'avgEst' }]
$select=expr(open*10%2BsevMax):rank → [{ $expr: { $op: '+', $args: [{ $op: '*', $args: ['open', 10] }, 'sevMax'] }, $as: 'rank' }]
$select=first(raisedAt):oldestAt,last(raisedAt):newestAt&$rowOrder=raisedAt,-id
→ { $fn: 'first', $field: 'raisedAt', $as: 'oldestAt' }, …, $rowOrder: { raisedAt: 1, id: -1 }fn(<arith>):alias(sum,avg,min,max) andexpr(<arith>):aliastake an arithmetic expression. The alias is required.expris a reserved name, likebucket. Onlysum,avg,min,maxandexprtake an expression; any other name (count(a*b):x) is aSyntaxErrornaming the item.- Grammar (shared with core's
parseArith): names, number literals,+ - * /, unary-, parentheses andcoalesce(a,b,…).-5after an operator is a negative literal. Size limits are checked by core'svalidateArith. - Write
+as%2B(buildUrldoes). A raw+is also read as plus, because the parser is given the raw query string. A+that a framework already turned into a space (open 1) is aSyntaxError(missing operator); a real space (%20) is skipped. first(field)/last(field)use the plain aggregate form (alias defaults tofirst_field) and read a representative row per group, ordered by$rowOrder(same syntax as$sort).- A bare name in a
fn(…)call is a field aggregate:sum(a):sparses as{ $fn: 'sum', $field: 'a' }, sobuildUrlof{ $fn: 'sum', $expr: 'a', $as: 's' }reads back as the field form. - A
$selectitem with a function call that matches no form throws (including an unknown function over an expression)SyntaxError('Malformed $select item "…"'). Up to 0.1.12 it was silently dropped, which changed the shape of the result.
Calendar Buckets in $select
bucket(field,unit[,tz][,weekStart])[:alias] groups a timestamp field by local hour, calendar day, week, month, quarter or year — see calendar buckets for units, zones and the YYYY-MM-DD (hour: YYYY-MM-DDTHH:00) label the server returns. Group, sort and filter by its alias:
$select=bucket(openedAt,week,'Europe/Berlin',sun):week,status,count(*):n
&$groupBy=week,status&$having=week>='2026-03-01'&$sort=weekbucket(openedAt,day) → { $bucket: 'day', $field: 'openedAt', $as: 'day_openedAt' }
bucket(openedAt,day,'Europe/Berlin'):day → { $bucket: 'day', $field: 'openedAt', $tz: 'Europe/Berlin', $as: 'day' }
bucket(openedAt,week,'America/New_York',sun):wk → { $bucket: 'week', …, $tz: 'America/New_York', $weekStart: 'sun', $as: 'wk' }
bucket(openedAt,week,,sun) → default zone (UTC), Sunday weeks
bucket(openedAt,hour,'Asia/Kolkata'):h → { $bucket: 'hour', …, $tz: 'Asia/Kolkata', $as: 'h' } — labels like '2026-03-01T14:00'- The zone is quoted when it contains
/(UTCmay be bare); an empty slot means the default zone. - Without an alias it is
{unit}_{field}; a dotted field (stats.firstSeenAt) needs an explicit:alias. bucketis a reserved name:bucket(…)always parses as a bucket, never as a custom aggregate, and a one-argumentbucket(x)is malformed (SyntaxError).- Parsing is syntactic only: an unknown unit, week start or zone passes through for the server to reject with a precise message. Malformed syntax — unbalanced parens, a missing field or unit, more than four arguments — throws.
Grouping ($groupBy)
$groupBy declares which fields to group by. Comma-separated:
$groupBy=currency → ['currency']
$groupBy=currency,region → ['currency', 'region']Aggregation Example
$select=sum(amount):total,count(*),currency&$groupBy=currency&$sort=-total&$limit=10Produces:
{
controls: {
$select: [
'currency',
{ $fn: 'sum', $field: 'amount', $as: 'total' },
{ $fn: 'count', $field: '*', $as: 'count_star' },
],
$groupBy: ['currency'],
$sort: { total: -1 },
$limit: 10,
},
insights: Map {
'amount' => Set { 'sum' },
'*' => Set { 'count' },
'currency' => Set { '$select', '$groupBy' },
'total' => Set { '$order' },
},
}Insights track aggregate functions with bare names ('sum', 'count'), distinct from $-prefixed control ops ('$select', '$groupBy').
Aggregates and $groupBy work inside $with sub-queries too:
$with=orders($select=sum(total):revenue&$groupBy=status)Post-Aggregation Filter ($having)
$having filters groups after aggregation (SQL HAVING). It accepts the same filter expression syntax as the main query:
$having=total>1000 → { $having: { total: { $gt: 1000 } } }
$having=total>1000&$having=count_star>=5 → { $having: { $and: [...] } } (AND-merged)
$having=total>1000^avg_price<50 → { $having: { $or: [...] } } (OR via ^)
$having=!(total<100) → { $having: { $not: {...} } } (NOT via !())For multi-condition $having with AND, either use multiple $having params (AND-merged automatically) or wrap in parentheses:
$having=(total>1000&count_star>=5)$having works inside $with sub-queries:
$with=orders($select=sum(total):revenue&$groupBy=status&$having=revenue>500)Insights track $having fields with the '$having' op.
Two-level aggregates ($from)
$from=( … ) is the inner level of a two-level aggregate (see the core README for the rules). The root controls aggregate its rows: every name they read is an inner column (an inner $groupBy key or $select alias), and the query filter applies to the rows the inner level groups.
projectId=7
&$from=($groupBy=userId,day&$select=bucket(createdAt,day):day,count(*):n,count(*|status=open):open&$having=n>0)
&$groupBy=userId&$select=userId,avg(n):avgPerDay,count(*|open>3):busyDays&$sort=-avgPerDay&$limit=10{
filter: { projectId: 7 },
controls: {
$from: {
$groupBy: ['userId', 'day'],
$select: [
{ $bucket: 'day', $field: 'createdAt', $as: 'day' },
{ $fn: 'count', $field: '*', $as: 'n' },
{ $fn: 'count', $field: '*', $as: 'open', $where: { status: 'open' } },
],
$having: { n: { $gt: 0 } },
},
$groupBy: ['userId'],
$select: ['userId', { $fn: 'avg', $field: 'n', $as: 'avgPerDay' }, { $fn: 'count', $field: '*', $as: 'busyDays', $where: { open: { $gt: 3 } } }],
$sort: { avgPerDay: -1 },
$limit: 10,
},
}- The body holds
$groupBy,$select,$rowOrder(with:first/:last, which land in the inner$nulls) and$having, joined by&. Write a$havingwith&in parentheses, as at the top level:$having=(n>1&n<9). - The body is read like a
$withbody: each of its segments is percent-decoded once more than the$from=…segment, sobuildUrlescapes its%once more. A whole value encoded byURLSearchParamsorencodeURIComponentparses too. - Throws
SyntaxError: a filter term inside the body ($from=($groupBy=g&status=open): put the filter on the query itself), any other control inside ($sort,$limit,$skip,$count,$with,$search, …), a$frominside$from(depth is fixed at two), a second$fromin the query, a$frominside a$withrelation body (top level only), and a value that is not one parenthesized body ($from=$groupBy=a,$from=(…)x). - Insights report the filter, the inner level, and every root name that is not an inner or outer alias (fail closed, see the core README).
- Shape validation (inner
$groupByrequired, outer names resolve against inner columns, …) isresolveNestedin@uniqu/core. A server MUST run it whenevercontrols.$from !== undefined, and MUST reject$fromwhere it does not support it.
Relation Loading ($with)
$with declares which relations to populate alongside the primary query. Relations are comma-separated:
$with=posts,comments,authorPer-Relation Sub-Queries
Each relation can include an inline sub-query in parentheses. Inside the parens, the full query syntax applies — filters, controls, and nested $with:
$with=posts($sort=-createdAt&$limit=5&status=published)This parses to:
controls.$with = [
{
name: 'posts',
filter: { status: 'published' },
controls: { $sort: { createdAt: -1 }, $limit: 5 },
},
]Each relation is a full Uniquery sub-query with its own filter, controls, and insights. All controls are supported inside parens: $sort, $limit, $skip, $select, $count, and nested $with.
Nested Relations
$with is recursive — relations can load their own sub-relations to any depth:
$with=posts($sort=-createdAt&$limit=5&$with=comments($limit=10&$with=author),tags)This produces a tree:
controls.$with = [
{
name: 'posts',
filter: {},
controls: {
$sort: { createdAt: -1 },
$limit: 5,
$with: [
{
name: 'comments',
filter: {},
controls: {
$limit: 10,
$with: [{ name: 'author', filter: {}, controls: {} }],
},
},
{ name: 'tags', filter: {}, controls: {} },
],
},
},
]Inside each level of parens, & separates parameters and , separates sibling relations within $with=. The parser handles balanced parentheses correctly across nesting levels.
Combined Example
status=active&$with=posts($sort=-createdAt&$limit=5&$select=title,body&status=published),authorProduces:
{
filter: { status: 'active' },
controls: {
$with: [
{
name: 'posts',
filter: { status: 'published' },
controls: {
$sort: { createdAt: -1 },
$limit: 5,
$select: ['title', 'body'],
},
insights: Map { 'status' => Set { '$eq' }, ... },
},
{ name: 'author', filter: {}, controls: {} },
],
},
insights: Map {
'status' => Set { '$eq' },
'posts' => Set { '$with' },
'posts.status' => Set { '$eq' },
'author' => Set { '$with' },
},
}Each $with relation carries its own scoped insights, and nested insights bubble up to the root with dot-notation prefixed field names.
Edge Cases
| Case | Behavior |
|------|----------|
| $with=posts,posts | Deduplicated — one entry |
| $with= or $with | No relations (empty/omitted) |
| $with=posts() | Empty parens — same as $with=posts |
| Unknown relation names | Recorded as-is — consumer validates against its schema |
Consumer Responsibility
Uniqu parses and types the $with declaration. The consumer (e.g. a database adapter) is responsible for:
- Execution strategy — JOINs, subqueries, or separate queries
- Relation validation — checking that relation names exist on the entity
- Circular reference detection — preventing infinite
$withchains - Depth limits — restricting nesting depth for performance
Insights
Insights are computed eagerly during URL parsing — a Map<string, Set<InsightOp>> recording which fields are used and with which operators. This includes filter operators, control usage ($select, $order, $groupBy), and aggregate functions (sum, avg, etc. — bare names without $ prefix).
Fields inside a relational predicate body are recorded with the navigation-field prefix: ticket=$some(status=open) → ticket ($some), ticket.status ($eq).
For queries constructed as JSON objects (not parsed from URL), use computeInsights() from @uniqu/core for lazy computation.
Full Example
$select=firstName,-client.ssn
&$order=-createdAt,score
&$limit=50&$skip=10
&$count
&$with=posts($sort=-date&$limit=5&status=published),profile
&$exists=client.phone
&$!exists=deletedAt
&age>=18&age<=30
&status!=DELETED
&name~=/^Jo/i
&role{Admin,Editor}
&25<height<35
^score>550&price>50&price<100Produces:
{
filter: {
$or: [
{
'client.phone': { $exists: true },
deletedAt: { $exists: false },
age: { $gte: 18, $lte: 30 },
status: { $ne: 'DELETED' },
name: { $regex: '/^Jo/i' },
role: { $in: ['Admin', 'Editor'] },
height: { $gt: 25, $lt: 35 },
},
{
score: { $gt: 550 },
price: { $gt: 50, $lt: 100 },
},
],
},
controls: {
$select: { firstName: 1, 'client.ssn': 0 },
$sort: { createdAt: -1, score: 1 },
$limit: 50,
$skip: 10,
$count: true,
$with: [
{
name: 'posts',
filter: { status: 'published' },
controls: { $sort: { date: -1 }, $limit: 5 },
},
{ name: 'profile', filter: {}, controls: {} },
],
},
}Splitting a query into segments
splitUrlSegments(raw) returns the top-level & segments of a query string exactly as parseUrl sees them. A group such as (a=1&b=2)^c=3 stays one segment. Segments are raw (not decoded), and empty ones are kept. Use it when you rewrite a URL key by key, for example to replace the segments a table owns while keeping the page's other keys:
import { splitUrlSegments } from '@uniqu/url'
splitUrlSegments('page=2&(status=A&total>5)^status=B')
// ['page=2', '(status=A&total>5)^status=B']URL Builder
Build URL query strings from Uniquery objects — the inverse of parseUrl. Available as a separate entry point for optimal bundle size:
import { buildUrl } from '@uniqu/url/builder'Usage
const url = buildUrl({
filter: { status: 'active', age: { $gte: 18 } },
controls: {
$select: ['name', 'email'],
$sort: { createdAt: -1 },
$limit: 20,
},
})
// → "status=active&age>=18&$select=name,email&$sort=-createdAt&$limit=20"buildUrl(query: Uniquery): string
Accepts a Uniquery object and returns a URL query string (without leading ?).
All features are supported:
- Filter expressions (comparisons,
$and/$or/$not,$in/$nin,$exists,$regex) - Controls (
$select,$sort/$rowOrderwith$nulls,$limit,$skip,$count,$groupBy,$having,$with) - Aggregates in
$select(sum(amount):total) - Nested
$withsub-queries - Pass-through custom
$-prefixed controls
Value serialization
- Strings that look like numbers, booleans, or
nullare automatically quoted ('25','true','null') - Strings with special characters (
&,^,=, spaces, quotes) are quoted and escaped; inside quotes%,&,(,),#, tab and line breaks are percent-encoded, so no value can end a segment or unbalance a paren group - Custom control values (
$search,$relevance, any$<custom>) are percent-encoded for the same characters plus'—"Maison & O'Brien #1"becomes$search=Maison %26 O%27Brien %231. Up to 0.1.8 they were written raw, so a search term containing&,%or'broke the URL - A
$withbody gets one extra level of%encoding, matching the extra decode on parse; so does a$frombody, which is written first among the controls ($from=( … )). A$fromholding a control the URL cannot carry inside it ($sort,$limit, a nested$from, …), and a$frominside a$withrelation, throw aTypeError - A
countDistinctfield list is writtencountDistinct(a,b). A$whereis written inside the call after a|(count(*|status=open):open,sum(price*qty|paid=true):rev). A condition needs a$as(without one it throws aTypeError), an always-true condition ({}) is dropped, and one that matches no row ({ $or: [] }) throws aTypeError - Numbers are written as plain decimals: a finite number whose
String(n)is in exponent form (1e21,1.5e-7) is expanded digit by digit (1000000000000000000000,0.00000015), so it parses back as the same number.NaN,Infinityand-Infinitythrow aTypeError(Filter value for "price" is not a finite number (NaN); it cannot be expressed in a URL) instead of turning into the strings"NaN"/"Infinity" - An empty
$in/$ninis writtenfield{}/field!{} - Arithmetic is written
fn(<arith>):aliasandexpr(<arith>):alias(alias required: an expression without$asthrows aTypeError;+is written%2B, see above);$rowOrderis written like$sort $nullsis written as a:first/:lastsuffix on each$sort/$rowOrderkey it names ($sort=-amount:last); an entry for a key that is not ordered by has no effect and is dropped. A placement other than'first'/'last', or an ordered field containing:without a placement, throws aTypeError- Calendar buckets are written as
bucket(field,unit[,tz][,weekStart]):alias, always with the alias - Leading-zero numbers (
007) stay as bare strings - Hyphenated strings and date-times are quoted (
'in-progress','2026-03-29T14:00'), althoughparseUrlalso accepts them bare Datevalues are serialized as quoted ISO stringsRegExpvalues are serialized as/pattern/flags
Round-tripping
buildUrl produces output compatible with parseUrl:
import { parseUrl } from '@uniqu/url'
import { buildUrl } from '@uniqu/url/builder'
const query = { filter: { age: { $gte: 18 } }, controls: { $limit: 10 } }
const url = buildUrl(query)
const parsed = parseUrl(url)
// parsed.filter → { age: { $gte: 18 } }
// parsed.controls.$limit → 10Round-trips are semantic, not structural: parseUrl returns the canonical
explicit-$and form, with logical branches first and the merged comparison
fields last, so { id: 101, $or: [...] } comes back as
{ $and: [{ $or: [...] }, { id: 101 }] }. Likewise an explicit $and inside
an $or is emitted parenthesized ((a=1&b=2)^c=3), which parses to the same
tree as the unparenthesized form.
Bundle optimization
The builder is a separate entry point (@uniqu/url/builder) so that apps using only buildUrl don't pull in the lexer and parser code, and vice versa.
API Reference
parseUrl(raw: string): UrlQuery
Parse a URL query string (without the leading ?) into the uniqu format.
buildUrl(query: Uniquery): string
Build a URL query string from a Uniquery object. Imported from @uniqu/url/builder.
UrlQuery
interface UrlQuery extends Uniquery {
insights: UniqueryInsights
}Narrows the optional insights field from Uniquery to required — insights are eagerly computed during URL parsing. Use getInsights() from @uniqu/core to transparently handle both URL-parsed queries (pre-computed) and manually constructed queries (lazy).
