@inixiative/json-rules 3.21.0 → 3.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +77 -35
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -4
- package/dist/index.d.ts +9 -4
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
A serializable rules engine for TypeScript. You write a rule once, as JSON, and the same rule AST runs in three places:
|
|
6
6
|
|
|
7
|
-
- `check()` evaluates it against in-memory data and returns `true` or the rule's
|
|
7
|
+
- `check()` evaluates it against in-memory data and returns `true` or a failure message: the rule's `error` when it sets one, otherwise a generated one (`age must be greater than or equal to 18`).
|
|
8
8
|
- `toPrisma()` compiles it into a Prisma query plan.
|
|
9
9
|
- `toSql()` compiles it into a PostgreSQL `WHERE` clause. `toWhereSql()` and `toLensWhereSql()` write inline predicates for PostgreSQL or MySQL.
|
|
10
10
|
|
|
@@ -96,7 +96,7 @@ Used in `aggregate.mode`:
|
|
|
96
96
|
- `sum`
|
|
97
97
|
- `avg`
|
|
98
98
|
|
|
99
|
-
Supported comparison operators for aggregate rules: `equals`, `notEquals`, `lessThan`, `lessThanEquals`, `greaterThan`, `greaterThanEquals`, `between`, `notBetween`.
|
|
99
|
+
Supported comparison operators for aggregate rules: `equals`, `notEquals`, `lessThan`, `lessThanEquals`, `greaterThan`, `greaterThanEquals`, `between`, `notBetween`, `exists`, `notExists`.
|
|
100
100
|
|
|
101
101
|
### Date Operators
|
|
102
102
|
|
|
@@ -210,9 +210,13 @@ Computes `sum` or `avg` of an array and compares the result to a value.
|
|
|
210
210
|
Empty-array semantics: `sum([]) = 0`, and `avg([])` is NULL, as SQL's `AVG` is: nothing has no
|
|
211
211
|
average. An average over no values is compared as a NULL column is — a positive operator
|
|
212
212
|
(`lessThan`, `equals`, `between`, …) doesn't hold, a negated one (`notEquals`, `notBetween`) does —
|
|
213
|
-
and
|
|
214
|
-
to a field's. Ask for it directly with `operator: 'exists'` / `'notExists'
|
|
215
|
-
|
|
213
|
+
and the compilers' internal complement adds the "no values" arm, the aggregate's own `notExists`, as it adds `notExists`
|
|
214
|
+
to a field's. Ask for it directly with `operator: 'exists'` / `'notExists'` (or, as on a field,
|
|
215
|
+
`equals` / `notEquals` `null`); a sum always exists. An aggregate rule's `coerceType` (a numeric
|
|
216
|
+
kind) parses each item before it is added (`'3'` → 3), as `coerceType` does on a field; without
|
|
217
|
+
it the items must be numbers. To count no values as
|
|
218
|
+
low, say so: `any: [{ field, arrayOperator: 'empty' }, { field, aggregate: { mode: 'avg' }, operator: 'lessThan', value: 3 }]`
|
|
219
|
+
(or `operator: 'notExists'` on the aggregate for the first arm). A NULL or absent array is empty, and NULL items are
|
|
216
220
|
skipped, as SQL's `SUM` / `AVG` skip them.
|
|
217
221
|
|
|
218
222
|
### Value Expressions
|
|
@@ -242,7 +246,8 @@ runs first (filter → order → skip → take), then `condition`. An aggregate
|
|
|
242
246
|
|
|
243
247
|
Values compare as stored, kind by kind: `distinct` keeps `1`, `Decimal('1')`, `1n` and `'1'` as
|
|
244
248
|
four values, which shows mixed data rather than hiding it. To read them as one kind, give
|
|
245
|
-
`distinct`, `min` or `max` a `coerceType` (as on a field rule
|
|
249
|
+
`distinct`, `min` or `max` a `coerceType` (as on a field rule; on `sum` / `avg` it parses each
|
|
250
|
+
item before adding it, as on an aggregate rule): `coerceType: 'Decimal'` reads all four
|
|
246
251
|
as 1, `'Int'` lets `min` / `max` order a string column of numbers (`'9'` before `'10'`), and
|
|
247
252
|
`'DateTime'` reads date strings as dates (a zoneless one in the evaluation's `timeZone`). A coercion
|
|
248
253
|
must be one the column can become, checked at save: a string reads as anything it parses to, a
|
|
@@ -274,6 +279,7 @@ evaluateValue(asksLast90Days, advocate, { now }); // 2
|
|
|
274
279
|
const lastAskAt = {
|
|
275
280
|
field: 'brandReferenceRequestFanUsers',
|
|
276
281
|
aggregate: { mode: 'max', field: 'activatedAt' },
|
|
282
|
+
coerceType: 'DateTime', // ISO strings: without it `max` throws on non-numbers
|
|
277
283
|
filter: { field: 'activatedAt', operator: Operator.exists },
|
|
278
284
|
};
|
|
279
285
|
|
|
@@ -370,11 +376,13 @@ toSql(rule, { now });
|
|
|
370
376
|
| Option | Default | Governs |
|
|
371
377
|
| --- | --- | --- |
|
|
372
378
|
| `now` | none (required when a relative/period expression is present) | the anchor instant |
|
|
373
|
-
| `timeZone` | `'UTC'` | how `now` and period boundaries localize: a zone name
|
|
379
|
+
| `timeZone` | `'UTC'` | how `now` and period boundaries localize: a zone name; `check()` and `evaluateValue` also take a `{ bind }` read from the bindings (the compilers need a zone name: bind first) |
|
|
374
380
|
| `weekStart` | `'monday'` (ISO / isoWeek) | start of `week` for `this`/`last`/`next` |
|
|
375
381
|
|
|
376
|
-
Compilers resolve expressions
|
|
377
|
-
`check()`, `toPrisma()`, and `toSql()` all
|
|
382
|
+
Compilers resolve literal and bound expressions at compile time (a `Date` in the Prisma
|
|
383
|
+
plan, an ISO-string parameter in `toSql()`), so `check()`, `toPrisma()`, and `toSql()` all
|
|
384
|
+
compare the same instant. An amount read from the row (`{ days: { path } }`) compiles in
|
|
385
|
+
`toSql()` to interval arithmetic on the column.
|
|
378
386
|
|
|
379
387
|
### Windowing: first/last with `orderBy` / `take` / `skip`
|
|
380
388
|
|
|
@@ -395,7 +403,7 @@ predicate. Pipeline: filter → order → skip → take. Direction comes from `o
|
|
|
395
403
|
```
|
|
396
404
|
|
|
397
405
|
`filter` is a condition each element must pass to enter the window (`narrowRule` puts a lens
|
|
398
|
-
clamp there under `all`). `orderBy` is
|
|
406
|
+
clamp there under `all`). `orderBy` is an array of `{ field, dir: 'asc' | 'desc' }` (multi-key; an empty one orders nothing);
|
|
399
407
|
`take`/`skip` are non-negative integers. **Empty-window semantics are author-driven**:
|
|
400
408
|
`all` is vacuously true on an empty window, `atLeast: 1` (or `any`) is false. To require
|
|
401
409
|
"the windowed element matches **and** one exists," combine `all` with `notEmpty` / `atLeast: 1`.
|
|
@@ -408,7 +416,7 @@ clamp there under `all`). `orderBy` is a non-empty array of `{ field, dir: 'asc'
|
|
|
408
416
|
> { some: {} } }, { fanMissions: { none: { completedAt: { gte: <now-30d> } } } }] }] }`. A `filter`
|
|
409
417
|
> alone (no `orderBy` / `take` / `skip`) folds into the rule: `all` through the exact complement
|
|
410
418
|
> of its condition, the rest as `filter AND condition`. Any other windowed rule (`take > 1`,
|
|
411
|
-
> `skip`, multi-key `orderBy`, a different/non-monotonic condition, a misaligned direction, or a
|
|
419
|
+
> a non-zero `skip`, multi-key `orderBy`, a different/non-monotonic condition, a misaligned direction, or a
|
|
412
420
|
> `filter` beside an ordered window) throws a clear "unsupported" error. `toSql()` does not
|
|
413
421
|
> compile windowing at all (no relation subqueries in a `WHERE` fragment). Evaluate the
|
|
414
422
|
> unsupported cases in memory with `check()`.
|
|
@@ -712,9 +720,12 @@ optional peer dependency), so there is nothing to configure; set `prismaOptions.
|
|
|
712
720
|
use a different client's. Without `@prisma/client`, a Json null check throws.
|
|
713
721
|
|
|
714
722
|
Prisma filters follow the column kind the map
|
|
715
|
-
declares: on Json, `contains`
|
|
716
|
-
|
|
717
|
-
|
|
723
|
+
declares: on Json, `contains` becomes an OR of `string_contains` and `array_contains`,
|
|
724
|
+
`startsWith` / `endsWith` become `string_starts_with` / `string_ends_with`, and `in`
|
|
725
|
+
becomes one `equals` per value (`notContains`, `notStartsWith`, `notEndsWith` and a case-insensitive `contains` throw on Json; `notEquals` and `notIn` compile, keeping the null rows); on a scalar list, `contains` becomes `has` and emptiness
|
|
726
|
+
`isEmpty`; `caseInsensitive` adds `mode: 'insensitive'` when a string meets a text, Json or
|
|
727
|
+
undeclared field, on a provider that takes it (PostgreSQL, CockroachDB, MongoDB; MySQL and
|
|
728
|
+
SQLite are case-insensitive by collation).
|
|
718
729
|
|
|
719
730
|
### A value the row doesn't carry
|
|
720
731
|
|
|
@@ -744,7 +755,7 @@ null`.
|
|
|
744
755
|
| `clock.finestUnit` | `'second'` | The finest unit a date rule may name: one of `CLOCK_UNITS`, or its plural (`'hours'` reads as `'hour'`); anything else throws when a date rule is evaluated. Every unit a date rule names counts, in its value (a relative date, either end of a range) and in its offset, whatever it compares against: a relative date, an absolute one or another column. A finer one fails: `check`, `toPrisma` and `toSql` throw and `validateRule` reports `clock_unit_below_floor`. The rule decides as written, so an amount read from the row or a binding (`{ minutes: { path } }`, a null one too) fails the same, and a bound whole expression is held to it once bound. Under `'hour'`, `{ ago: { minutes: 30 } }`, `{ this: 'minute' }`, and any compare offset by `{ ago: { minutes: 5 } }` fail. A caller whose finest tick is an hour sets it once at boot. |
|
|
745
756
|
|
|
746
757
|
```ts
|
|
747
|
-
import { engineGlobals } from '@inixiative/json-rules';
|
|
758
|
+
import { check, engineGlobals, SqlDialect } from '@inixiative/json-rules';
|
|
748
759
|
|
|
749
760
|
engineGlobals.set('string.caseInsensitive', true);
|
|
750
761
|
engineGlobals.get('string.caseInsensitive'); // true
|
|
@@ -832,7 +843,9 @@ toSql(rule, { map: lens, mapName: 'prisma', model: 'Post' });
|
|
|
832
843
|
Two small helpers write a condition, or a lens's row filters, as a SQL predicate for a caller
|
|
833
844
|
that names its own columns and writes its own joins (an Omni topic, for one). They write the
|
|
834
845
|
engine's `sql.dialect` (`SqlDialect.postgres` by default, `SqlDialect.mysql` the other) and
|
|
835
|
-
are not a second `toSql
|
|
846
|
+
are not a second `toSql`.
|
|
847
|
+
|
|
848
|
+
### `toWhereSql`: a condition as a predicate
|
|
836
849
|
|
|
837
850
|
```ts
|
|
838
851
|
import { ArrayOperator, engineGlobals, Operator, SqlDialect, toLensWhereSql, toWhereSql } from '@inixiative/json-rules';
|
|
@@ -887,8 +900,8 @@ toLensWhereSql(lens, { columns, tables });
|
|
|
887
900
|
relation of the related rows nests (`tables['<relation>.<relation>']`). A relation behind
|
|
888
901
|
another one (`profile.affiliations`), a relation missing from `tables`, `atLeast` / `atMost` /
|
|
889
902
|
`exactly`, a window (`filter` / `orderBy` / `take` / `skip`) and a fieldless array rule throw.
|
|
890
|
-
- **Map:** `map`
|
|
891
|
-
kind (
|
|
903
|
+
- **Map:** `map` and `model` are required, and `mapName` too when `map` is a `FieldMapSet`. A value is checked against its column's
|
|
904
|
+
kind (as `validateNarrowing` checks it) and an undeclared path is refused, because
|
|
892
905
|
MySQL casts a mistyped literal instead of erroring, so `score = TRUE` would match 1 where
|
|
893
906
|
`check()` matches nothing. The map also finds a to-one relation's key for its `exists`
|
|
894
907
|
(`columns['<relation>.<key>']`: the related row's key, NULL when there is none), and says which
|
|
@@ -906,6 +919,8 @@ toLensWhereSql(lens, { columns, tables });
|
|
|
906
919
|
exactly, so a `_ci` column (MySQL's default) also matches `'Advocate'` for `'advocate'`; compare a
|
|
907
920
|
binary-collated column where that matters.
|
|
908
921
|
|
|
922
|
+
### `toLensWhereSql`: a lens's row filters
|
|
923
|
+
|
|
909
924
|
`toLensWhereSql(lens, { columns, tables?, toMany? })` mirrors the lens: the root path's `where`s under `root` (null
|
|
910
925
|
when it has none), each relation path's own under `relations`, keyed by the path, and each model
|
|
911
926
|
default's (`mapDefaults[map].models[model].where`) under `mapDefaults`, keyed the same way: one
|
|
@@ -932,7 +947,9 @@ the lens hides throws, and its condition's fields are checked from the relation,
|
|
|
932
947
|
model it sits on. A model default compiles to one predicate for every path that reaches its
|
|
933
948
|
model, so it throws when a to-many relation it reads carries different clamps on two of them.
|
|
934
949
|
|
|
935
|
-
|
|
950
|
+
### Join mode: `toMany: 'join'`
|
|
951
|
+
|
|
952
|
+
For a caller that can't run a correlated subquery (an Omni
|
|
936
953
|
topic rebuilds one as its own query and loses the correlation), the root's `where` reads a to-many
|
|
937
954
|
relation on the row the caller's join brings instead. Nothing about the join is a new option: the
|
|
938
955
|
caller LEFT JOINs each to-many relation the root's `where` reads (a relation the lens declares),
|
|
@@ -1037,7 +1054,7 @@ and `in [null, …]` carry the same hop arms: a user with no profile has a NULL
|
|
|
1037
1054
|
an `equals: null` on a NOT NULL column is a Prisma validation error. Nullability
|
|
1038
1055
|
comes from the field map: `FieldMapEntry.isRequired: false` (prisma-map emits it).
|
|
1039
1056
|
Without `{ map, model }`, or on an entry that doesn't declare it, the bare
|
|
1040
|
-
`not` / `notIn` is emitted and NULL rows fall out
|
|
1057
|
+
`not` / `notIn` is emitted and NULL rows fall out.
|
|
1041
1058
|
|
|
1042
1059
|
Date rules follow the same split. The positive operators answer non-match on both
|
|
1043
1060
|
rails: a bare boundary is not something a NULL column satisfies, so `check()`
|
|
@@ -1054,26 +1071,29 @@ positive operator, ask for them:
|
|
|
1054
1071
|
| `notAfter X` / `notBefore X` | matches | `(col <= $1 OR col IS NULL)` / `(col >= $1 OR col IS NULL)` | `{ OR: [{ col: { lte } }, { col: { equals: null } }] }` (nullable column) |
|
|
1055
1072
|
| `notWithin { ago: { days: 30 } }` | matches | `(col NOT BETWEEN $1 AND $2 OR col IS NULL)` | `{ OR: [{ NOT: { col: { gte, lte } } }, { col: { equals: null } }] }` (nullable column) |
|
|
1056
1073
|
| `notBetween` | matches | `(col NOT BETWEEN $1 AND $2 OR col IS NULL)` | `{ OR: [{ NOT: { col: … } }, { col: { equals: null } }] }` (nullable column, same field-map licensing as above) |
|
|
1057
|
-
| `dayNotIn` | matches | `(EXTRACT(DOW FROM col) <> ALL($
|
|
1074
|
+
| `dayNotIn` | matches | `(EXTRACT(DOW FROM (… col AT TIME ZONE $1)) <> ALL($2) OR col IS NULL)` (`$1` the zone, `$2` the days) | none (no Prisma output) |
|
|
1058
1075
|
| `notExists` OR `before` | matches via the first arm | `(col IS NULL OR col < $1)` | `{ OR: [{ col: { equals: null } }, { col: { lt: … } }] }` |
|
|
1059
1076
|
|
|
1060
|
-
`0` is an instant (1970-01-01) and compares; `''` is malformed data
|
|
1061
|
-
`"is not a valid date"
|
|
1077
|
+
`0` is an instant (1970-01-01) and compares, on every rail; `''` is malformed: as row data it
|
|
1078
|
+
raises `"is not a valid date"` in `check()`, and as a rule value it throws on every rail
|
|
1079
|
+
(`"Invalid comparison date"` in `check()`, `"Invalid date value"` in the compilers).
|
|
1062
1080
|
|
|
1063
1081
|
### Prisma Limitations
|
|
1064
1082
|
|
|
1065
1083
|
- `matches` and `notMatches` are not supported by Prisma output
|
|
1066
1084
|
- `dayIn` and `dayNotIn` are not supported by Prisma output
|
|
1067
|
-
- `path: '$.field'` column-to-column comparisons
|
|
1085
|
+
- `path: '$.field'` column-to-column comparisons compile only between columns of the same model and visit, with `{ map, model }`; a `$$.` scope ref, or a read of the root from inside a relation filter, doesn't compile
|
|
1068
1086
|
- count-based and aggregate relation operators require `{ map, model }`
|
|
1069
1087
|
- aggregate rules on JSON/native stored arrays are not supported by Prisma; use `toSql()` or `check()` for those
|
|
1088
|
+
- an aggregate rule compared against a column (`path`) is refused: Prisma computes the aggregate in a `groupBy`, whose `having` can't read the parent row
|
|
1070
1089
|
- element conditions (`all` / `any` / `none` / counts) over a scalar list or a Json array are not supported by Prisma; test a list's membership with `contains`
|
|
1071
1090
|
- a field path through a to-many relation (`posts.title`) is an error on both compilers; compare its rows with an array rule on `posts`
|
|
1072
1091
|
- Prisma loads a NULL scalar-list column as `[]`, so `check()` over Prisma-loaded rows reads it as an empty list while the compilers read NULL; a list Prisma writes is never NULL, so this only matters for rows written outside Prisma
|
|
1073
1092
|
|
|
1074
1093
|
### SQL Limitations
|
|
1075
1094
|
|
|
1076
|
-
- complex array element operators are not supported in
|
|
1095
|
+
- complex array element operators are not supported in `toSql()` output (`toWhereSql()`
|
|
1096
|
+
compiles `any` / `all` / `none` over a to-many relation as `EXISTS` / `NOT EXISTS`):
|
|
1077
1097
|
- `all`
|
|
1078
1098
|
- `any`
|
|
1079
1099
|
- `none`
|
|
@@ -1093,7 +1113,20 @@ engines themselves differ:
|
|
|
1093
1113
|
`check()` compares UTF-16 code units, Postgres the column's collation.
|
|
1094
1114
|
- An array or aggregate rule on a Json value that isn't an array is a data error. `check()`
|
|
1095
1115
|
throws on it; SQL can't raise per row, so it reads the value as an empty array, for an
|
|
1096
|
-
aggregate and for `empty` / `notEmpty` alike.
|
|
1116
|
+
aggregate and for `empty` / `notEmpty` alike. Prisma's `notEmpty` holds on an array only, as
|
|
1117
|
+
SQL's does, but Prisma has no filter for "not an array", so its `empty` doesn't match one: on
|
|
1118
|
+
Prisma a non-array value satisfies neither `notEmpty` nor its negation, and an `all` whose
|
|
1119
|
+
condition is a `notEmpty` (compiled as no item where it fails) carries that through.
|
|
1120
|
+
- A Json-array `sum` / `avg` over numbers stored as strings (`["1", "2"]`): without
|
|
1121
|
+
`coerceType`, `check()` throws on them, and SQL casts them with `::numeric`. Give the aggregate
|
|
1122
|
+
rule `coerceType: 'Float'` (or `'Int'` / `'Decimal'`) and `check()` parses each item as SQL does.
|
|
1123
|
+
Postgres's `numeric` also parses text JavaScript doesn't (`'1_000'`, `'Infinity'`, `'NaN'`,
|
|
1124
|
+
`'1e400'`); `check()` keeps its error on those.
|
|
1125
|
+
- `check()` adds JavaScript doubles; SQL adds exact `numeric`. A Json array `[0.1, 0.2]` sums to
|
|
1126
|
+
`0.30000000000000004` in `check()` and `0.3` in SQL, so `sum equals 0.3` holds on SQL only.
|
|
1127
|
+
Compare a computed sum with a tolerance (`between`) rather than `equals`.
|
|
1128
|
+
- Under `coerceType: 'Decimal'`, an item past 15 significant digits — a Decimal object or a
|
|
1129
|
+
numeric string — throws in `check()` rather than round; SQL's `numeric` reads it exactly.
|
|
1097
1130
|
|
|
1098
1131
|
## TypeScript Types
|
|
1099
1132
|
|
|
@@ -1221,6 +1254,11 @@ readScopeRef('$$$.x', [rootRow, order]);
|
|
|
1221
1254
|
`readScopeRef` returns the scope a ref names and the path left to read in it. It never throws:
|
|
1222
1255
|
a ref deeper than the stack comes back as `{ outOfBounds }` with the message.
|
|
1223
1256
|
|
|
1257
|
+
`pathSegments(path)` is the list of keys a path reads, as `check()` reads it: dotted names,
|
|
1258
|
+
bracket indices and quoted keys (`messages[0].authorId` and `["messages"][0]["authorId"]` are
|
|
1259
|
+
both `['messages', '0', 'authorId']`). Use it, never `split('.')`, to walk a path of your own:
|
|
1260
|
+
a dotted split misses every bracket spelling `check()` accepts.
|
|
1261
|
+
|
|
1224
1262
|
## Error Handling
|
|
1225
1263
|
|
|
1226
1264
|
The library throws when a rule is structurally invalid, for example:
|
|
@@ -1265,6 +1303,10 @@ try {
|
|
|
1265
1303
|
}
|
|
1266
1304
|
```
|
|
1267
1305
|
|
|
1306
|
+
A rule that reaches past the lens is neither: `toPrisma` / `toSql` under `{ lens }` throw a
|
|
1307
|
+
plain `Error` (`"<rail>: the rule leaves the lens — …"`), which `validateRuleInLens` reports
|
|
1308
|
+
first.
|
|
1309
|
+
|
|
1268
1310
|
## Root-Array Rules in `check()`
|
|
1269
1311
|
|
|
1270
1312
|
When `data` is an array, the rule must be a tree of `all` / `any` whose leaves are **fieldless** `ArrayRule`s (no `field`, `arrayOperator` operates on the array itself).
|
|
@@ -1324,7 +1366,7 @@ and visibility model.
|
|
|
1324
1366
|
|
|
1325
1367
|
### How it's built
|
|
1326
1368
|
|
|
1327
|
-
The `Lens` primitive is a schema-aware view layer over one or more `FieldMap`s. It enables rule authoring against multi-source data (e.g. Prisma + an external CRM), with declarative cross-source `Bridge`s and recursive `
|
|
1369
|
+
The `Lens` primitive is a schema-aware view layer over one or more `FieldMap`s. It enables rule authoring against multi-source data (e.g. Prisma + an external CRM), with declarative cross-source `Bridge`s and recursive `LensNarrowing`s for both schema (picks/omits/enumPicks/enumOmits) and data (`where`).
|
|
1328
1370
|
|
|
1329
1371
|
### FieldMap & FieldMapSet
|
|
1330
1372
|
|
|
@@ -1354,7 +1396,7 @@ const set = stitchFieldMaps({
|
|
|
1354
1396
|
});
|
|
1355
1397
|
```
|
|
1356
1398
|
|
|
1357
|
-
`stitchFieldMaps()` injects bridge entries as `kind: 'bridge'` fields on each endpoint model, addressable in rules via `<fieldMap>:<Model>` notation (e.g. `salesforce:Contact.industry`). Each endpoint's `on` is the symmetric join field
|
|
1399
|
+
`stitchFieldMaps()` injects bridge entries as `kind: 'bridge'` fields on each endpoint model, addressable in rules via `<fieldMap>:<Model>` notation (e.g. `salesforce:Contact.industry`). Each endpoint's `on` is the symmetric join field; `indexBridges` and `toSourceQueries` read it to join the two sides (`check()` never does: it reads the rows it is given). Bridge cardinality controls list-vs-single on each side.
|
|
1358
1400
|
|
|
1359
1401
|
### Lens
|
|
1360
1402
|
|
|
@@ -1384,7 +1426,7 @@ const narrowing: LensNarrowing = {
|
|
|
1384
1426
|
parent: lens,
|
|
1385
1427
|
root: { relations: { org: { relations: { parent: {} } } } }, // along the path
|
|
1386
1428
|
mapDefaults: {
|
|
1387
|
-
prisma: { models: { Org: { relations: { users: {} } } } }, // wherever Org is visited
|
|
1429
|
+
prisma: { models: { Org: { relations: { users: {} } } } }, // wherever Org is visited, unless User is already on the path
|
|
1388
1430
|
},
|
|
1389
1431
|
};
|
|
1390
1432
|
validateRuleInLens({ field: 'org.parent.name', operator: Operator.equals, value: 'Acme' }, narrowing); // ok
|
|
@@ -1409,11 +1451,11 @@ validateRuleInLens({ field: 'posts', arrayOperator: ArrayOperator.any, condition
|
|
|
1409
1451
|
turn-ons are followed breadth-first, each model once, at its nearest reach (ties: the earlier
|
|
1410
1452
|
parent, then the relation declared first). Anything else is reached by spelling it under
|
|
1411
1453
|
`root.relations`; a spelled node grows its own tree. Every posture walks the same tree, so they
|
|
1412
|
-
agree and stay small. `lensVisit(lens, 'org.
|
|
1454
|
+
agree and stay small. `lensVisit(lens, 'org.parent')` resolves one visit on demand, as
|
|
1413
1455
|
`projectLens` would give it, or `null`.
|
|
1414
1456
|
- **Clamps.** The first narrowing's `where`s (and source eligibility `where`s) may read any
|
|
1415
1457
|
relation on the schema; a later layer's may read only what its parent shows, so a delegate can't
|
|
1416
|
-
probe a relation it can't see (`validateNarrowing` reports it; every posture throws). A bare
|
|
1458
|
+
probe a relation it can't see (`validateNarrowing` reports it; the gate refuses it and every other posture throws). A bare
|
|
1417
1459
|
value `path` reads the root row, so only `root.where` may hold one. `toLensSelect` fetches exactly the columns clamps read, and
|
|
1418
1460
|
`projectRows({ keepClampColumns: true })` keeps them for a re-check.
|
|
1419
1461
|
|
|
@@ -1446,7 +1488,7 @@ Composition across chained narrowings is pure intersection: relations are turned
|
|
|
1446
1488
|
|
|
1447
1489
|
| Function | Purpose |
|
|
1448
1490
|
| --- | --- |
|
|
1449
|
-
| `validateNarrowing(narrowing)` | Returns `{ ok, errors: { path, message, code }[] }` for structural or chain problems, one code each: `not_in_lens`, `not_visible` (an item an ancestor hid, or a relation the parent doesn't show), `conflicting_selection` (picks beside an omitted column), `wrong_kind` (a relation named in `picks`, among others), `value_not_allowed`, `invalid_source` (a source label / axis crossing a relation that is off, among others), `invalid_binding`, plus the lens gate's codes for a `where`. `assertValidNarrowing` throws instead. Call at narrowing construction. |
|
|
1491
|
+
| `validateNarrowing(narrowing)` | Returns `{ ok, errors: { path, message, code }[] }` for structural or chain problems, one code each: `not_in_lens`, `not_visible` (an item an ancestor hid, or a relation the parent doesn't show), `conflicting_selection` (picks beside an omitted column), `wrong_kind` (a relation named in `picks`, among others), `value_not_allowed`, `invalid_source` (a source label / axis crossing a relation that is off, among others), `invalid_binding`, `invalid_value_source`, `scope_out_of_bounds`, the codes of the `LensRefusal`s it folds in (`unsupported_clamp`, among others), plus the lens gate's codes for a `where`. `assertValidNarrowing` throws instead. Call at narrowing construction. |
|
|
1450
1492
|
| `assertValidFieldMaps(set)` | Throws when a field name in any map holds `.` or `:` (a path step and a bridge marker). `validateFieldMaps(set)` returns `{ ok, errors }` with code `invalid_field_name`. To check a single map, wrap it: `assertValidFieldMaps({ maps: { prisma: map } })`. |
|
|
1451
1493
|
| `projectLens(lens)` | Returns `Record<dottedPath, ProjectedVisit>`: each path the relations turned on reach keys its own resolved narrowing (path picks/omits/enums chain-intersected ∩ `mapDefaults` for the target model); a relation field appears only where it is on. Sibling paths to the same model stay independent. Use for SDK-contract / OpenAPI emission, search-field enumeration, validation whitelists. See [docs/LENS.md §10](./docs/LENS.md). |
|
|
1452
1494
|
| `describeRuleSources(rule, lens)` | The values a rule names at each source the lens declares, keyed like `projectLens` (`path` + `field`, with the source's `mapName` / `model`). Resolved through the lens like `walkLensPath`, so `mapDefaults` sources answer wherever a relation turned on reaches their model. `dynamic: true` when the set can't be enumerated: a `path` / `bind` leaf, an offset or a read amount that moves the value, a substring / pattern / range / window operator, or an operator the catalog doesn't know; callers fail closed on it. The reverse question for a reference registry ("which rows does this rule name"): join `model` + `values`. |
|
|
@@ -1546,7 +1588,7 @@ const projection = projectLens(narrowing, { sourceValues: [values] });
|
|
|
1546
1588
|
| Function | Purpose |
|
|
1547
1589
|
| --- | --- |
|
|
1548
1590
|
| `toSourceQueries(lensOrNarrowing, options?)` | `SourceQuery[]`, one per sourced field: `{ path, mapName, model, field, label?, groupBy?, composedWhere, prisma, sql, recheck? }`. `options` is the clock (`now`, `timeZone`, `weekStart`) a relative date in the where compiles with: required for one, a plain usage error without it; bind a lens's binds with `bindLens` first. `prisma.steps` is present when the where needs `executePrismaPlan` (a count step, or a column reference to resolve): query with the where it returns. `sql.sql` is `null` with an `error` when SQL can't express the where. A source that reads across a bridge gets an over-fetching query and a `recheck`: its rows are candidates, not options (see "Sources across a bridge"). `distinct` is the value and a sibling label column; a grouped source or a dotted label drops it, so every label comes back and the least one is picked. |
|
|
1549
|
-
| `materializeSourceQuery(query, rows, { rowShape?, lens?, now?, … })` | One query's fetched rows as `SourceValues`. `rowShape` is `'prisma'` (default: a dotted `label` and each `groupBy` axis come nested) or `'sql'` (they come flat as `__label` / `__group_i`). Options are deduplicated and
|
|
1591
|
+
| `materializeSourceQuery(query, rows, { rowShape?, lens?, now?, … })` | One query's fetched rows as `SourceValues`. `rowShape` is `'prisma'` (default: a dotted `label` and each `groupBy` axis come nested) or `'sql'` (they come flat as `__label` / `__group_i`). Options are deduplicated and ordered by value, or in the query's own order with `order: SourceOptionOrder.query`. A query with `recheck` needs `lens` and rows holding the far side: it re-checks each candidate (`check`, with the clock and bindings given) and reads a bridged label or axis from the far side; a missing far side is a `UsageError`. |
|
|
1550
1592
|
| `materializeSources(lensOrNarrowing, rows, options?)` | `SourceValues[]` for every sourced field, from the rows the lens fetches: `toLensSelect`'s rows as fetched, or as `projectRows(…, { keepClampColumns: true })` keeps them. A viewer's projection drops what sources read: a row lacking any key a read walks (through each relation and list element to the column) that a source or a clamp on its path reads throws a `UsageError` (a fetch returns every key it selects, NULL as `null`). The path is walked down the rows (the tree is its link), each level's clamps met, and each row it reaches must meet, through `check()` with `options`, its visit's clamps, its source `where` narrowed as a rule is, the guards of the relations its label and axes cross and the values the lens allows, so it offers what `toSourceQueries` does. A scalar-list field gives one option per element; a value takes its least label. A `from: 'mapDefaults'` source throws (see below). |
|
|
1551
1593
|
|
|
1552
1594
|
Options never offer a value the lens disallows: `projectLens` drops fetched values outside a
|
|
@@ -1558,7 +1600,7 @@ couldn't carry there (one narrowRule can't re-root, a to-many relation read flat
|
|
|
1558
1600
|
it is for a rule; so is a source whose query has a window toPrisma can't compile (by its shape,
|
|
1559
1601
|
before anything compiles; `materializeSources` refuses it too, so the two never disagree).
|
|
1560
1602
|
|
|
1561
|
-
|
|
1603
|
+
### Two kinds of source
|
|
1562
1604
|
|
|
1563
1605
|
A source declared down a relation path offers the rows **reachable** from there: the path is
|
|
1564
1606
|
carried down through each relation's inverse (where the map declares one), and every clamp above
|
|
@@ -1609,7 +1651,7 @@ over-fetches and re-checks (see "Sources across a bridge"). A clamp a path can't
|
|
|
1609
1651
|
map declares no inverse) is a `LensRefusal`, never an empty list. `materializeSources` refuses a pointer, because a fetched collection can't hold unlinked
|
|
1610
1652
|
rows; query it with `toSourceQueries` and `materializeSourceQuery`.
|
|
1611
1653
|
|
|
1612
|
-
|
|
1654
|
+
### Sources across a bridge
|
|
1613
1655
|
|
|
1614
1656
|
A source whose path, `where`, `label` or an axis reads across a bridge can't be decided by one
|
|
1615
1657
|
database: each holds one side. `toSourceQueries` still returns a real query for the side it can
|