A fast, sandboxed matching engine with serializable rules.
Using Hypermatch, you can define streams of traffic, audiences, or just a partition of objects using simple logical rules. A collection of rules like "Browser is Firefox" and "Browser is Chrome or query string matches 'mobile'" form such audiences. Each rule definition is already a fully compatible JSON object, so that the rules are serializable by default.
The rules are lisp-ish. They are recursive by default, and you can mix and match any constructs you like. The engine runs against a target object and ends with a boolean result value.
High level constructs, expr
can be another high level constructs or a terminal.
[ and, [expr] ]
[ or, [expr] ]
[ not, [expr] ]
Examples:
Verify that age
needs to be within the range 18..25
or email
can be .*test-user.*
.
['or',
['range',
'age',
[18, 25]],
['regex',
'email',
'.*test-user.*']]
For this rule { age: 84, email: 'test-user@acme.org'}
matches while { age: 84, email: 'bob@gmail.com'}
doesn't.
Terminals, dealing with collections.
[ excludes, key, ary ]
[ includes, key, ary ]
[ subset, key, ary ]
- verify that the collection behindkey
is a subset ofary
defined in the rules.[ intersects, key, ary]
- verify that the collection behindkey
intersects withary
[ range, key, [start, end] ]
- verify that the value behindkey
is betweenstart
andend
.
Examples:
Verify that the whitelist ['a']
contains the value under name
.
['includes',
'name',
['a']],
For this rule { name: 'a' }
validates while { name: 'foo' }
doesn't.
Terminals, dealing with individual values.
[ equals, key, val ]
- performs deep equal.[ regex, key, regexp ]
[ exists, key ]
Examples:
Verify that '.*Android.*'
matches the user agent under ua
.
['regex',
'ua',
'.*Android.*']
For this rule { ua: 'Mozilla/5.0 (Linux; U; Android 4.0.3; ko...'}
validates while { ua: 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'}
doesn't.
This library includes a minimal conditions construct that uses Hypermatch. It will go over the rules, run them and execute the related effect for the rule that succeeds (and stop there).
Here's how to use it:
import { cond, trap, fallback } from 'rules/cond'
const match = cond(
trap(['exists', 'name'], obj => obj.name),
trap(['range', 'age', [17, 34]], obj => obj.age),
fallback(() => 99)
)
match({age: 30}) // -> 30
match({age: 80}) // -> 99
match({user: 'bob'}) // -> 99