@inixiative/json-rules 3.15.1 → 3.17.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 CHANGED
@@ -1,14 +1,14 @@
1
1
  # @inixiative/json-rules
2
2
 
3
- A TypeScript-first JSON rules library for:
3
+ > One of the [inixiative](https://www.inixiative.com) building blocks. Stop rediscovering what you need to build. The [vocabulary](https://www.inixiative.com/vocabulary.html) defines every primitive (`Condition`, `FieldMap`, lens, sources, builders and the layers built on them); [all the projects](https://github.com/inixiative) are on GitHub.
4
4
 
5
- - runtime validation with custom error messages
6
- - Prisma query planning
7
- - PostgreSQL `WHERE` generation
5
+ A serializable rules engine for TypeScript. You write a rule once, as JSON, and the same rule AST runs in three places:
8
6
 
9
- The same rule AST can be evaluated against in-memory data with `check()`, converted into a Prisma query plan with `toPrisma()`, or compiled into SQL with `toSql()`.
7
+ - `check()` evaluates it against in-memory data and returns `true` or the rule's own error message.
8
+ - `toPrisma()` compiles it into a Prisma query plan.
9
+ - `toSql()` compiles it into a PostgreSQL `WHERE` clause. `toWhereSql()` and `toLensWhereSql()` write inline predicates for PostgreSQL or MySQL.
10
10
 
11
- > Part of the [inixiative ecosystem](https://github.com/inixiative). See the **[full vocabulary](https://www.inixiative.com/vocabulary.html)** for every primitive — `Condition`, `FieldMap`, lens, sources, builders, and the layers built on them — with what each solves and how it works.
11
+ So a rule that validates a form can also select the matching rows, without a second implementation that has to agree with the first. Because a rule is plain data, you can store it in your database, let a tenant edit it, and validate it before you save it. Operators are enums (`Operator`, `ArrayOperator`, `DateOperator`), the rule types are generic TypeScript types (`Condition`), and `{ bind }` placeholders are filled at check time or ahead of compiling with `bindRule`. Under a lens, a rule may read only the fields and relations the lens exposes, and the compilers throw on a rule that reaches past it.
12
12
 
13
13
  ## Installation
14
14
 
@@ -42,10 +42,10 @@ check(rule, { age: 16 }); // "Must be 18 or older"
42
42
  - nested logical conditions with `all` / `any`
43
43
  - `if` / `then` / `else`
44
44
  - array validation against nested object elements
45
- - array aggregates — `sum` and `avg` across numeric arrays or relation lists
46
- - ordered windowing — first/last `N` with `orderBy` / `take` / `skip` (`check()`; `toPrisma()` compiles the extremal case and a `filter` alone)
45
+ - array aggregates: `sum` and `avg` across numeric arrays or relation lists
46
+ - ordered windowing: first/last `N` with `orderBy` / `take` / `skip` (`check()`; `toPrisma()` compiles the extremal case and a `filter` alone)
47
47
  - date comparisons with timezone-aware runtime evaluation
48
- - relative & calendar date expressions — "last 30 days", "this month" — via `within` and `ago`/`ahead`/`this`/`last`/`next`
48
+ - relative & calendar date expressions ("last 30 days", "this month") via `within` and `ago`/`ahead`/`this`/`last`/`next`
49
49
  - relative value references via `path`, and `$$.` scope refs up through nested arrays
50
50
  - custom error messages on every rule
51
51
  - compilation to Prisma and PostgreSQL for supported subsets
@@ -222,12 +222,12 @@ NULL items are skipped, as SQL's `SUM` / `AVG` skip them.
222
222
  ### Relative & Calendar Date Expressions
223
223
 
224
224
  A date rule's `value` can be a structured, serializable expression instead of an
225
- absolute date. Magnitudes are always **positive** — direction lives in the keyword.
225
+ absolute date. Magnitudes are always **positive**; the keyword carries the direction.
226
226
  A period (`this` / `last` / `next`) names a dayjs unit: `day`, `week`, `isoWeek`, `month`,
227
227
  `quarter`, `year`, `hour`, `minute`, `second`. A rolling amount (`ago` / `ahead`) counts
228
228
  `years`, `quarters`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`.
229
229
 
230
- **Point expressions** — pair with `before` / `after` / `onOrBefore` / `onOrAfter` /
230
+ **Point expressions** pair with `before` / `after` / `onOrBefore` / `onOrAfter` /
231
231
  `notBefore` / `notAfter`,
232
232
  or as `between` endpoints:
233
233
 
@@ -246,7 +246,7 @@ or as `between` endpoints:
246
246
  { field: 'completedAt', dateOperator: DateOperator.before, value: { end: { last: 'month' } } }
247
247
  ```
248
248
 
249
- **Range expressions** — pair with `within` / `notWithin`:
249
+ **Range expressions** pair with `within` / `notWithin`:
250
250
 
251
251
  ```ts
252
252
  // "this month"
@@ -263,14 +263,14 @@ or as `between` endpoints:
263
263
  { field: 'lastLoginAt', dateOperator: DateOperator.notWithin, value: { ago: { days: 30 } } }
264
264
  ```
265
265
 
266
- A **bare period** with `before` / `after` resolves to the only sensible edge —
266
+ A **bare period** with `before` / `after` resolves to the only sensible edge:
267
267
  `before { last: 'month' }` is *before the start* of last month, `after { next: 'month' }`
268
268
  is *after the end* of next month. Use `{ start: … }` / `{ end: … }` for the other edge.
269
269
 
270
270
  #### The `now` contract and config
271
271
 
272
272
  Relative/calendar expressions need a reference instant. `now` is an **explicit
273
- evaluator input** — there is no implicit `Date.now()` inside the library. Pass it
273
+ evaluator input**: there is no implicit `Date.now()` inside the library. Pass it
274
274
  on the same options bag as everything else; `check`/`toPrisma`/`toSql` **throw** if
275
275
  a relative expression is used without it.
276
276
 
@@ -282,14 +282,14 @@ toSql(rule, { now });
282
282
 
283
283
  | Option | Default | Governs |
284
284
  | --- | --- | --- |
285
- | `now` | — (required when a relative/period expression is present) | the anchor instant |
286
- | `timeZone` | `'UTC'` | how `now` and period boundaries localize — a zone name, or a `{ bind }` read from the bindings |
285
+ | `now` | none (required when a relative/period expression is present) | the anchor instant |
286
+ | `timeZone` | `'UTC'` | how `now` and period boundaries localize: a zone name, or a `{ bind }` read from the bindings |
287
287
  | `weekStart` | `'monday'` (ISO / isoWeek) | start of `week` for `this`/`last`/`next` |
288
288
 
289
289
  Compilers resolve expressions to concrete `Date` bounds at compile time, so
290
290
  `check()`, `toPrisma()`, and `toSql()` all compare the same instant.
291
291
 
292
- ### Windowing — first/last with `orderBy` / `take` / `skip`
292
+ ### Windowing: first/last with `orderBy` / `take` / `skip`
293
293
 
294
294
  Array and aggregate rules accept an ordered-window selector that runs **before** the
295
295
  predicate. Pipeline: filter → order → skip → take. Direction comes from `orderBy.dir`, so
@@ -313,16 +313,16 @@ clamp there under `all`). `orderBy` is a non-empty array of `{ field, dir: 'asc'
313
313
  `all` is vacuously true on an empty window, `atLeast: 1` (or `any`) is false. To require
314
314
  "the windowed element matches **and** one exists," combine `all` with `notEmpty` / `atLeast: 1`.
315
315
 
316
- > **Compilation.** `toPrisma()` compiles the **extremal** case — `take: 1`, a single
316
+ > **Compilation.** `toPrisma()` compiles the **extremal** case: `take: 1`, a single
317
317
  > `orderBy`, and a monotonic condition on that same field, with the direction aligned so
318
318
  > the extremal element is binding (`all` + desc + `before`, `any` + desc + `after`, etc.).
319
319
  > It rewrites to relation filters: the rule above, with `completedAt` required, is "no missions,
320
- > or some and none since the bound" — `{ OR: [{ fanMissions: { none: {} } }, { AND: [{ fanMissions:
320
+ > or some and none since the bound": `{ OR: [{ fanMissions: { none: {} } }, { AND: [{ fanMissions:
321
321
  > { some: {} } }, { fanMissions: { none: { completedAt: { gte: <now-30d> } } } }] }] }`. A `filter`
322
322
  > alone (no `orderBy` / `take` / `skip`) folds into the rule: `all` through the exact complement
323
- > of its condition, the rest as `filter AND condition`. Any other windowed rule — `take > 1`,
323
+ > of its condition, the rest as `filter AND condition`. Any other windowed rule (`take > 1`,
324
324
  > `skip`, multi-key `orderBy`, a different/non-monotonic condition, a misaligned direction, or a
325
- > `filter` beside an ordered window — throws a clear "unsupported" error. `toSql()` does not
325
+ > `filter` beside an ordered window) throws a clear "unsupported" error. `toSql()` does not
326
326
  > compile windowing at all (no relation subqueries in a `WHERE` fragment). Evaluate the
327
327
  > unsupported cases in memory with `check()`.
328
328
 
@@ -333,7 +333,7 @@ through `{ bind }` (`check(rule, row, { bindings })`; `bindRule` before compilin
333
333
 
334
334
  ### Root Row Reference
335
335
 
336
- A bare path reads the root row — the record `check()` evaluates, the table a compiler compiles
336
+ A bare path reads the root row: the record `check()` evaluates, the table a compiler compiles
337
337
  against:
338
338
 
339
339
  ```ts
@@ -349,7 +349,7 @@ against:
349
349
  Inside an array operator's `condition` or `filter`, `$.` reads from the current element.
350
350
  Each additional `$` reaches one enclosing element further out: `$$.` is the element of the
351
351
  enclosing array operator, `$$$.` the one above that, up to the root row. Logical
352
- combinators (`all` / `any` / `if`) never add a level — only array and aggregate rules do.
352
+ combinators (`all` / `any` / `if`) never add a level; only array and aggregate rules do.
353
353
 
354
354
  Both `field` and `path` take the prefix. A bare `field` is always the current element; a
355
355
  bare `path` is always the root row.
@@ -386,7 +386,7 @@ same visit (a bare path at the root, `$.` inside a relation filter), of exactly
386
386
  no offset. The plan carries a `{ __field }` sentinel that `executePrismaPlan` resolves to
387
387
  `prisma.<model>.fields.<column>`; read a plan's where only through it. Anything else throws, and
388
388
  `validateRule(rule, { target: 'toPrisma', map, model })` / `describeRule` report it first. Every
389
- other scope ref — a `$$.` path or any prefixed `field` — is check-only; both compilers throw.
389
+ other scope ref (a `$$.` path or any prefixed `field`) is check-only; both compilers throw.
390
390
 
391
391
  ### Offsets and Unit Amounts
392
392
 
@@ -418,7 +418,7 @@ instead of `now`:
418
418
  `listBindings` lists it. A date offset read per row (a column holding
419
419
  `{ ago: … }`) is check-only; to size a shift from the row, read the amount instead.
420
420
 
421
- Any relative-date unit — in a `value` expression or an offset's rolling shift — is a number or a
421
+ Any relative-date unit, in a `value` expression or an offset's rolling shift, is a number or a
422
422
  value source: `{ path }` from the row, `{ bind }`, or `{ value }`. A relative
423
423
  window can take its size from the row it judges:
424
424
 
@@ -431,7 +431,7 @@ window can take its size from the row it judges:
431
431
  Offsets apply to the comparison operators (`equals` … `greaterThanEquals`, `before` …
432
432
  `notAfter`) and to both ends of `between` / `notBetween`. Units apply as Postgres applies an
433
433
  interval to a wall-clock time in the evaluation's `timeZone` (UTC by default): months (years,
434
- quarters, months), then days (weeks, days), then time — so every rail lands on the same instant
434
+ quarters, months), then days (weeks, days), then time, so every rail lands on the same instant
435
435
  at a month end and across a DST change. Calendar units (years … days) are whole numbers and every
436
436
  unit is non-negative: a literal that isn't fails validation, and a value read from data that
437
437
  isn't reads as null. A null comparison value, offset or magnitude, or a range missing an end,
@@ -451,22 +451,22 @@ field, a rolling shift on a DateTime.
451
451
 
452
452
  ## Rule Introspection
453
453
 
454
- Reading a stored rule's own content — which values it names, which bindings it needs — is
454
+ Reading a stored rule's own content (which values it names, which bindings it needs) is
455
455
  engine work, not caller work: a walk written outside the engine goes blind the day the rule
456
456
  format grows a node type, and it goes blind silently.
457
457
 
458
458
  | Function | Purpose |
459
459
  | --- | --- |
460
- | `listBindings(rule, { required: true })` | Names a bindings map must cover — every `{ bind }` token not marked `bindOptional`, sorted. A name optional at one leaf and required at another is required. |
461
- | `listBindings(rule)` | Every `{ bind }` name in the tree, optional or not, sorted — what a lens declares. |
460
+ | `listBindings(rule, { required: true })` | Names a bindings map must cover: every `{ bind }` token not marked `bindOptional`, sorted. A name optional at one leaf and required at another is required. |
461
+ | `listBindings(rule)` | Every `{ bind }` name in the tree, optional or not, sorted: what a lens declares. |
462
462
  | `bindRule(rule, bindings)` | Substitutes covered binds with their values, leaving uncovered tokens in place (partial resolution). |
463
463
  | `clockUnit(rule)` | The finest clock unit the rule's answer can change by while its data stays the same: the smallest unit any relative date in the tree names (`{ ago: { hours: 2 } }` → `hour`, `{ this: 'week' }` → `week`, `isoWeek` → `week`), one of `CLOCK_UNITS` (`second` … `year`); throws on a unit finer than the engine's `clock.finestUnit`, as evaluating the rule does. `null` when it reads no clock: absolute dates, column compares and their offsets, weekday lists. A caller re-evaluates a stored rule on that tick instead of guessing from its JSON. |
464
464
 
465
465
  A leaf may mark its bind optional: `{ field, operator, bind: 'region', bindOptional: true }`. An
466
- unsupplied required bind is a caller bug — `check()` throws, and both compilers refuse a
466
+ unsupplied required bind is a caller bug: `check()` throws, and both compilers refuse a
467
467
  surviving token. An unsupplied *optional* bind is `null` wherever absence is final: `check()`
468
468
  compares against `null`, `toPrisma` / `toSql` compile the token as `null`. The rule is evaluated
469
- as written — the leaf is never pruned, so `in {{bind}}` with nothing bound matches nothing rather
469
+ as written. The leaf is never pruned, so `in {{bind}}` with nothing bound matches nothing rather
470
470
  than everything.
471
471
 
472
472
 
@@ -618,7 +618,7 @@ const where = await executePrismaPlan(plan, prisma);
618
618
 
619
619
  ### Json null checks
620
620
 
621
- A Json column holds a DB NULL or a JSON `null`, and a path inside it can be absent — `check()`
621
+ A Json column holds a DB NULL or a JSON `null`, and a path inside it can be absent. `check()`
622
622
  reads all three as null, and Prisma matches them together only with its `AnyNull` instance,
623
623
  which it knows by identity. `toPrisma()` takes it from your installed `@prisma/client` (an
624
624
  optional peer dependency), so there is nothing to configure; set `prismaOptions.anyNull` only to
@@ -639,8 +639,8 @@ null` and `in [null]` included, except the ones that hold on a missing value (`i
639
639
  for real rows (a pseudo record a grant is checked against), so a rule passes only on what the row
640
640
  pins. `check()` only; the compilers read real columns.
641
641
 
642
- `validateRule(rule, { positive: true })` refuses every shape that can hold on a missing value —
643
- `if`/`then`/`else`, array and aggregate rules, the negations, `isEmpty` and `notExists` — so a rule
642
+ `validateRule(rule, { positive: true })` refuses every shape that can hold on a missing value
643
+ (`if`/`then`/`else`, array and aggregate rules, the negations, `isEmpty` and `notExists`), so a rule
644
644
  checked that way passes only on what the row carries. A rule that means "no value" says `equals
645
645
  null`.
646
646
 
@@ -664,16 +664,43 @@ engineGlobals.get('string.caseInsensitive'); // true
664
664
  engineGlobals.set('prismaOptions.datasource.provider', 'mysql');
665
665
  engineGlobals.set('sql.dialect', SqlDialect.mysql); // what toWhereSql / toLensWhereSql write
666
666
  engineGlobals.set('clock.finestUnit', 'hour'); // a rule reading minutes or seconds fails to evaluate
667
- engineGlobals.reset(); // back to the defaults
667
+ engineGlobals.reset(); // back to the defaults, registered namespaces' included
668
668
 
669
669
  // A scoped override: merged over the current state for the duration of a synchronous callback.
670
- const result = engineGlobals.with({ string: { caseInsensitive: true } }, () => check(rule, data));
670
+ // Flat paths or the nested shape.
671
+ const result = engineGlobals.with({ 'string.caseInsensitive': true }, () => check(rule, data));
671
672
  ```
672
673
 
673
674
  `with()` restores the previous state when the callback returns or throws. The callback must be
674
675
  synchronous: one that returns a Promise throws. `set()` copies plain data and keeps a class
675
676
  instance (like `AnyNull`) as given, since Prisma recognizes it by identity.
676
677
 
678
+ ### One engine interaction point for the libraries built on it
679
+
680
+ `engineGlobals` is the settings store for every engine built on json-rules (permissions,
681
+ transitions, rules-builder). A library registers its own namespace, once, at the top of the module
682
+ that reads it, and adds its paths to the types by augmentation:
683
+
684
+ ```ts
685
+ import { engineGlobals, registerEngineGlobals } from '@inixiative/json-rules';
686
+
687
+ declare module '@inixiative/json-rules' {
688
+ interface EngineGlobalValues { 'permissions.idField': string }
689
+ }
690
+ registerEngineGlobals('permissions', { idField: 'id' });
691
+
692
+ engineGlobals.set('permissions.idField', 'uuid'); // the app, at boot
693
+ ```
694
+
695
+ - A namespace is one segment and never one of json-rules' own roots (`string`, `prismaOptions`,
696
+ `sql`, `clock`). A library registers only its own, and reads its own and those of the engines
697
+ below it.
698
+ - Defaults go in under a value already set, so an app may configure a library before importing it.
699
+ Registering the same defaults again is a no-op; different ones throw.
700
+ - The store lives on `globalThis` under `Symbol.for('@inixiative/json-rules/engineGlobals@3')`:
701
+ every 3.x copy in the process (a nested install, an ESM and a CJS build) reads and writes the same
702
+ settings.
703
+
677
704
  ## PostgreSQL SQL Generation
678
705
 
679
706
  `toSql()` converts a rule into a parameterized PostgreSQL `WHERE` clause.
@@ -713,11 +740,11 @@ as `toPrisma()` takes it. A set without `mapName` throws.
713
740
  toSql(rule, { map: lens, mapName: 'prisma', model: 'Post' });
714
741
  ```
715
742
 
716
- ## Inline Predicates — `toWhereSql`, `toLensWhereSql`
743
+ ## Inline Predicates: `toWhereSql`, `toLensWhereSql`
717
744
 
718
745
  Two small helpers write a condition, or a lens's row filters, as a SQL predicate for a caller
719
746
  that names its own columns and writes its own joins (an Omni topic, for one). They write the
720
- engine's `sql.dialect` — `SqlDialect.postgres` by default, `SqlDialect.mysql` the other — and
747
+ engine's `sql.dialect` (`SqlDialect.postgres` by default, `SqlDialect.mysql` the other) and
721
748
  are not a second `toSql`: `toSql` and `toPrisma` are unchanged.
722
749
 
723
750
  ```ts
@@ -757,15 +784,15 @@ toLensWhereSql(lens, { columns, tables });
757
784
 
758
785
  - **Operators:** `equals`, `notEquals`, `in`, `notIn`, `exists`, `notExists`, inside `all` / `any`
759
786
  (and `true` / `false`), and `any` / `all` / `none` / `empty` / `notEmpty` over a to-many relation
760
- (below). Anything else — another operator, a date rule, a count or windowed array rule, an
761
- aggregate, `if` / `then` / `else` — throws, naming it. So do binds, `path` (column-to-column),
787
+ (below). Anything else (another operator, a date rule, a count or windowed array rule, an
788
+ aggregate, `if` / `then` / `else`) throws, naming it. So do binds, `path` (column-to-column),
762
789
  offsets, `coerceType`, case-insensitivity, a path across a bridge, a field rule through a to-many
763
790
  relation, anything Json (a stored JSON null is a value to SQL and null to `check()`), and a
764
791
  DateTime or list *value*. A DateTime's or list's existence compiles: `deletedAt notExists`, a
765
792
  lens's soft-delete `where`, is `… IS NULL`. A rule with no `value` throws, as on every rail.
766
793
  - **To-many relations:** an array rule on a to-many relation of the model is one subquery on the
767
794
  relation's table, keyed to the row: `any` / `notEmpty` is `EXISTS`, `none` / `empty` is
768
- `NOT EXISTS`, and `all` is `NOT EXISTS` of a row whose condition `IS NOT TRUE` — a NULL result
795
+ `NOT EXISTS`, and `all` is `NOT EXISTS` of a row whose condition `IS NOT TRUE`, so a NULL result
769
796
  fails, as in `check()`. The map gives the keys (`relationKeys`; a composite key ANDs every pair):
770
797
  the row's side reads `columns['<key>']`, the related side `columns['<relation>.<key>']`.
771
798
  `tables['<relation>']` is the table, written after `FROM` as given, with the alias its columns
@@ -774,15 +801,15 @@ toLensWhereSql(lens, { columns, tables });
774
801
  another one (`profile.affiliations`), a relation missing from `tables`, `atLeast` / `atMost` /
775
802
  `exactly`, a window (`filter` / `orderBy` / `take` / `skip`) and a fieldless array rule throw.
776
803
  - **Map:** `map` / `mapName` / `model` are required. A value is checked against its column's
777
- kind (`leafFitViolations`, as `validateNarrowing` checks it) and an undeclared path is refused —
804
+ kind (`leafFitViolations`, as `validateNarrowing` checks it) and an undeclared path is refused, because
778
805
  MySQL casts a mistyped literal instead of erroring, so `score = TRUE` would match 1 where
779
806
  `check()` matches nothing. The map also finds a to-one relation's key for its `exists`
780
807
  (`columns['<relation>.<key>']`: the related row's key, NULL when there is none), and says which
781
808
  values have no form here.
782
809
  - **Columns:** `columns` maps a field path to the caller's SQL, used as written; the engine writes
783
- no joins and no identifiers. A path missing from it throws, naming the path — it never falls back
810
+ no joins and no identifiers. A path missing from it throws, naming the path; it never falls back
784
811
  to a quoted name, which MySQL's default mode reads as a string literal.
785
- - **Values** are written inline — there are no placeholders to fill. A string doubles `'`; on
812
+ - **Values** are written inline; there are no placeholders to fill. A string doubles `'`; on
786
813
  MySQL it doubles `\` too (MySQL's default mode reads a backslash as an escape;
787
814
  `NO_BACKSLASH_ESCAPES` is not supported). `in` is `IN (…)`; an enum compares as written, with no
788
815
  cast.
@@ -792,12 +819,12 @@ toLensWhereSql(lens, { columns, tables });
792
819
  exactly, so a `_ci` column (MySQL's default) also matches `'Advocate'` for `'advocate'`; compare a
793
820
  binary-collated column where that matters.
794
821
 
795
- `toLensWhereSql(lens, { columns, tables? })` mirrors the lens: the root path's `where`s under `root` (null
822
+ `toLensWhereSql(lens, { columns, tables?, toMany? })` mirrors the lens: the root path's `where`s under `root` (null
796
823
  when it has none), each relation path's own under `relations`, keyed by the path, and each model
797
- default's (`mapDefaults[map].models[model].where`) under `mapDefaults`, keyed the same way — one
824
+ default's (`mapDefaults[map].models[model].where`) under `mapDefaults`, keyed the same way: one
798
825
  predicate per model however many paths reach it. Each is the `where` as its layer wrote it: a
799
826
  parent layer's clamp on a hop is reported at that hop's path, never folded into what a later
800
- layer wrote through it. A `where` that reads through a relation the lens hides throws — that
827
+ layer wrote through it. A `where` that reads through a relation the lens hides throws, because that
801
828
  hop's clamps have no path to report at, and `check()` still carries them. A lens that spans maps
802
829
  reports every map's defaults; a caller writing one database reads its own map's. A path `where` reads `columns` by its path from the lens model (`status` at the root,
803
830
  `brandReferenceRequestFanUsers.id` below it); a model default by `'<Model>.<field>'`
@@ -818,6 +845,56 @@ the lens hides throws, and its condition's fields are checked from the relation,
818
845
  model it sits on. A model default compiles to one predicate for every path that reaches its
819
846
  model, so it throws when a to-many relation it reads carries different clamps on two of them.
820
847
 
848
+ **Join mode: `toMany: 'join'`.** For a caller that can't run a correlated subquery (an Omni
849
+ topic rebuilds one as its own query and loses the correlation), the root's `where` reads a to-many
850
+ relation on the row the caller's join brings instead. Nothing about the join is a new option: the
851
+ caller LEFT JOINs each to-many relation the root's `where` reads (a relation the lens declares),
852
+ ON the map's relation keys (`relationKeys`, the same keys a to-one relation's existence reads) AND
853
+ `relations['<path>']` AND the related model's `mapDefaults` entry, and reads the related columns as
854
+ `columns['<path>.<field>']`. `tables` is not read. A join the `where` does not read only fans the
855
+ rows out (count distinct); a read of a relation the caller did not join fails loudly (a missing
856
+ column).
857
+
858
+ ```ts
859
+ toLensWhereSql(lens, { columns, toMany: 'join' });
860
+ // root: "(${fan_users.deleted_at} IS NULL AND ${fan_user_affiliation.fan_user_uuid} IS NOT NULL)"
861
+ // relations: { affiliations: "(${fan_user_affiliation.affiliation} = 'advocate' AND ${fan_user_affiliation.ended_at} IS NULL)" }
862
+ // the topic: LEFT JOIN fan_user_affiliation ON <keys> AND relations.affiliations [AND its model default]
863
+ ```
864
+
865
+ - **What compiles:** `notEmpty` is `<key> IS NOT NULL`, and `any(cond)` is
866
+ `(<key> IS NOT NULL AND cond)`, with `cond` on the joined columns. The key is the first key
867
+ column: a matched row's key equals the parent's and is never NULL, an unmatched row is all NULL,
868
+ so one column decides. `cond` may hold on a missing value (`endedAt notExists`): the
869
+ `IS NOT NULL` guard has already dropped the all-NULL row of a parent with no rows.
870
+ - **Positive operators only.** `empty`, `none` and `all` can hold with no rows (the catalog's
871
+ `holdsOnNoRows`), which takes an anti-join, not the topic's join: `all(cond)` is
872
+ `none(NOT cond)`, and the join drops the parents with no rows that `all` keeps. They throw, as do
873
+ the counts, `exists` / `notExists` on the relation (a to-many relation has one spelling, an
874
+ `arrayOperator` rule) and a field read through it (`affiliations.affiliation`).
875
+ - **The root's `where` only.** A relation path's `where` sits in that relation's ON, ahead of the
876
+ joins below it, and a model default compiles once for every path that reaches its model, where
877
+ the join exists only on the paths the lens shows: either one reading a to-many relation throws.
878
+ So do a to-many relation, or any relation, read inside a joined `any`.
879
+ - **One `any` per relation.** One joined row stands for the relation, so two `any` rules on it
880
+ (`any advocate AND any prospect`, in one `where` or across layers) would need one row to meet
881
+ both, where `check()` lets each find its own: it throws. Write one `any` whose condition says
882
+ which row (`any: [advocate, prospect]` for either). `notEmpty` beside an `any` is fine.
883
+ - **One alias per model default.** `mapDefaults` holds one predicate per model, on
884
+ `columns['<Model>.<field>']`, so it can sit on one table alias. A joined relation whose model has
885
+ a default `where` throws when the root's `where` needs that default on a second alias too: a
886
+ to-many self-relation (the root is that model as well), or two joined relations that reach one
887
+ model. Compile with `toMany: 'subquery'`, which carries the default inside each `EXISTS`.
888
+ - **The layer guard.** The ON carries every clamp on the relation, from every layer, but `check()`
889
+ reads a `where` through the clamps of the layers above its own only. So a root `where` that
890
+ reads a joined relation throws when one of that relation's clamps (its path `where` or its
891
+ model's default) sits in the `where`'s own layer or a later one, naming the path and both layers.
892
+ Move the clamp into an earlier narrowing: then the ON is exactly what `check()` reads.
893
+ - **`any(cond)` hides rows.** The rows that fail `cond` are gone from the whole query, not only
894
+ from the filter; `check()` hides nothing. Where you can, write the condition as the relation's
895
+ `where` (in a layer above) and have the root read `notEmpty`.
896
+ - **Fan-out.** A joined to-many relation repeats the parent once per related row: count distinct.
897
+
821
898
  **Absent, not hidden.** A row a relation's `where` filters out is absent from the SQL join, so a
822
899
  negation through that relation holds for it; `check()` under the lens treats the row as hidden.
823
900
  The lens is a projection: the difference is accepted and documented.
@@ -834,21 +911,21 @@ Not every backend supports every rule shape.
834
911
  | Array `all` / `any` / `none` | Yes | Yes | No |
835
912
  | Array `atLeast` / `atMost` / `exactly` | Yes | Yes, with `map` + `model` | No |
836
913
  | Array `empty` / `notEmpty` | Yes | Yes | Yes (list and Json columns, not relations) |
837
- | Aggregate `sum` / `avg` — primitive or object array | Yes | No | Yes |
838
- | Aggregate `sum` / `avg` — relation list | Yes | Yes, with `map` + `model` | No |
914
+ | Aggregate `sum` / `avg`, primitive or object array | Yes | No | Yes |
915
+ | Aggregate `sum` / `avg`, relation list | Yes | Yes, with `map` + `model` | No |
839
916
  | Date comparisons | Yes | Most | Yes |
840
917
  | Date expressions (`ago`/`ahead`/`this`/`last`/`next`/`start`/`end`) + `within` | Yes | Yes | Yes |
841
918
  | `dayIn` / `dayNotIn` | Yes | No | Yes |
842
919
  | Windowing (`filter` / `orderBy` / `take` / `skip`) | Yes | Extremal (`take: 1`, aligned, no `filter`), or a `filter` alone | No |
843
- | `path` — a bare root-row column, or `$.` the current element's | Yes (reads the row) | Same model, same visit, exactly the same type, with `equals` / `notEquals` / `lessThan(Equals)` / `greaterThan(Equals)` — a Prisma field reference, resolved by `executePrismaPlan`; anything else throws | Yes (a column; not in a relation filter, not a substring or set operator) |
844
- | `offset` and unit amounts — value or bind | Yes | Yes | Yes |
845
- | `offset` and unit amounts — row refs (`$.` or bare) | Yes | No | Yes (not a date offset's) |
920
+ | `path`: a bare root-row column, or `$.` the current element's | Yes (reads the row) | Same model, same visit, exactly the same type, with `equals` / `notEquals` / `lessThan(Equals)` / `greaterThan(Equals)` (a Prisma field reference, resolved by `executePrismaPlan`); anything else throws | Yes (a column; not in a relation filter, not a substring or set operator) |
921
+ | `offset` and unit amounts, value or bind | Yes | Yes | Yes |
922
+ | `offset` and unit amounts, row refs (`$.` or bare) | Yes | No | Yes (not a date offset's) |
846
923
  | `$$.` scope refs and `$`-prefixed `field` | Yes | No | No |
847
924
 
848
925
  ### NULL Semantics
849
926
 
850
- A negated operator is the complement of its positive form — the same answer
851
- `check()` gives, where `null !== 'x'` is simply true. SQL's three-valued logic
927
+ A negated operator is the complement of its positive form: the same answer
928
+ `check()` gives, where `null !== 'x'` is true. SQL's three-valued logic
852
929
  disagrees (`col <> 'x'` is NULL, never true, for a NULL column), so the
853
930
  compilers carry NULL rows explicitly:
854
931
 
@@ -864,19 +941,19 @@ compilers carry NULL rows explicitly:
864
941
  The **absent set** of a path is wider than a NULL leaf: an optional to-one hop can be NULL too,
865
942
  and `{ rel: { col: { equals: null } } }` only matches when the relation exists. So every negation
866
943
  also carries `{ rel: { is: null } }` for each optional to-one hop on the path (licensed by the
867
- relation entry's `isRequired: false`) — `profile.bio notEquals 'x'` compiles to
944
+ relation entry's `isRequired: false`). `profile.bio notEquals 'x'` compiles to
868
945
  `{ OR: [{ profile: { bio: { not: 'x' } } }, { profile: { bio: { equals: null } } }, { profile: { is: null } }] }`,
869
946
  matching check() (a missing hop reads as NULL) and toSql (LEFT JOIN + `IS NULL`). `equals null`
870
947
  and `in [null, …]` carry the same hop arms: a user with no profile has a NULL `profile.bio`.
871
948
 
872
- `toPrisma()` can only add the null arm when it knows the column is nullable —
949
+ `toPrisma()` can only add the null arm when it knows the column is nullable, because
873
950
  an `equals: null` on a NOT NULL column is a Prisma validation error. Nullability
874
951
  comes from the field map: `FieldMapEntry.isRequired: false` (prisma-map emits it).
875
952
  Without `{ map, model }`, or on an entry that doesn't declare it, the bare
876
953
  `not` / `notIn` is emitted and NULL rows fall out, as they always did.
877
954
 
878
955
  Date rules follow the same split. The positive operators answer non-match on both
879
- rails — a bare boundary is not something a NULL column satisfies, so `check()`
956
+ rails: a bare boundary is not something a NULL column satisfies, so `check()`
880
957
  reports the rule's ordinary non-match (honoring `error`) and the compilers keep the
881
958
  bare `<` / `BETWEEN`. The negative-flavored ones (`notBefore`, `notAfter`, `notWithin`, `notBetween`, `dayNotIn`) follow
882
959
  the negation ruling instead: a never-set date is not in the range, so a null column
@@ -890,7 +967,7 @@ positive operator, ask for them:
890
967
  | `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) |
891
968
  | `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) |
892
969
  | `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) |
893
- | `dayNotIn` | matches | `(EXTRACT(DOW FROM col) <> ALL($1) OR col IS NULL)` | — (no Prisma output) |
970
+ | `dayNotIn` | matches | `(EXTRACT(DOW FROM col) <> ALL($1) OR col IS NULL)` | none (no Prisma output) |
894
971
  | `notExists` OR `before` | matches via the first arm | `(col IS NULL OR col < $1)` | `{ OR: [{ col: { equals: null } }, { col: { lt: … } }] }` |
895
972
 
896
973
  `0` is an instant (1970-01-01) and compares; `''` is malformed data and raises
@@ -902,9 +979,9 @@ positive operator, ask for them:
902
979
  - `dayIn` and `dayNotIn` are not supported by Prisma output
903
980
  - `path: '$.field'` column-to-column comparisons are not supported by Prisma `WHERE`; no scope ref (`$$.` path, prefixed `field`) compiles
904
981
  - count-based and aggregate relation operators require `{ map, model }`
905
- - aggregate rules on JSON/native stored arrays are not supported by Prisma — use `toSql()` or `check()` for those
982
+ - aggregate rules on JSON/native stored arrays are not supported by Prisma; use `toSql()` or `check()` for those
906
983
  - 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`
907
- - 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`
984
+ - 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`
908
985
  - 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
909
986
 
910
987
  ### SQL Limitations
@@ -928,7 +1005,7 @@ engines themselves differ:
928
1005
  - Ordered string comparisons (`lessThan`, `between` on text) follow each engine's order:
929
1006
  `check()` compares UTF-16 code units, Postgres the column's collation.
930
1007
  - An array or aggregate rule on a Json value that isn't an array is a data error. `check()`
931
- throws on it; SQL can't raise per row, so it reads the value as an empty array — for an
1008
+ throws on it; SQL can't raise per row, so it reads the value as an empty array, for an
932
1009
  aggregate and for `empty` / `notEmpty` alike.
933
1010
 
934
1011
  ## TypeScript Types
@@ -978,18 +1055,18 @@ Lens & bridges:
978
1055
 
979
1056
  A lens has three forms, each with its own job:
980
1057
 
981
- - **Composed** — a `Lens`, or a `LensNarrowing` whose `parent` holds the layer above it as an
1058
+ - **Composed**: a `Lens`, or a `LensNarrowing` whose `parent` holds the layer above it as an
982
1059
  object, down to the base lens. Every evaluator takes this form.
983
- - **Stored** — `StoredLens`, one record per layer: its `id`, `parents` (the ids of every layer it
1060
+ - **Stored**: `StoredLens`, one record per layer: its `id`, `parents` (the ids of every layer it
984
1061
  composes with, the base lens first) and its own part. The base lens is the root-most record,
985
1062
  stored as itself with no parents. `storeLens(lens, ids)` writes a composed lens out as records;
986
- `composeLens(id, records)` reads them back — fetch the layer, then the ids it lists — validating
1063
+ `composeLens(id, records)` reads them back (fetch the layer, then the ids it lists), validating
987
1064
  each layer against the ones above it and failing closed on a missing record, a base out of
988
1065
  place, or a parent whose own list disagrees.
989
- - **Projected** — what a lens exposes, which never leads back to the lens:
1066
+ - **Projected**: what a lens exposes, which never leads back to the lens:
990
1067
  - `projectLens(lens)` returns `Record<dottedPath, ProjectedVisit>` for per-path checks where
991
1068
  sibling paths to the same model diverge.
992
- - `projectLens(lens, { by: 'model' })` returns the leak-safe total surface *as a Lens* — every
1069
+ - `projectLens(lens, { by: 'model' })` returns the leak-safe total surface *as a Lens*: every
993
1070
  model the relations turned on reach, with the full narrowing applied, unioned per model, `where`
994
1071
  stripped. Use it as the server→client builder surface; it never exposes the raw lens. It is a
995
1072
  view, not a gate: as a lens it is bare and turns no relation on, so gate rules against the
@@ -1087,7 +1164,7 @@ Two error classes say whose input went wrong; each sets `name`, so check with `i
1087
1164
  | Class | Thrown when | Fix |
1088
1165
  | --- | --- | --- |
1089
1166
  | `UsageError` | The caller's input is missing or malformed: no `now` for a relative date, an invalid `now` or time zone, a bind never bound (`bindRule` / `bindLens` before compiling; `bindings` for `check`). | Supply the input. |
1090
- | `LensRefusal` (`code`) | The lens itself can't do it: a later layer's clamp reads what its parent hides, a clamp or source a compile has no form for, a source path that can't carry its link. | Fix the lens — `validateNarrowing` reports the same refusal as an issue. |
1167
+ | `LensRefusal` (`code`) | The lens itself can't do it: a later layer's clamp reads what its parent hides, a clamp or source a compile has no form for, a source path that can't carry its link. | Fix the lens; `validateNarrowing` reports the same refusal as an issue. |
1091
1168
 
1092
1169
  ```ts
1093
1170
  import { LensRefusal, UsageError } from '@inixiative/json-rules';
@@ -1128,35 +1205,35 @@ check(
1128
1205
 
1129
1206
  ## Lens & Multi-Source Data
1130
1207
 
1131
- > **For the full lens guide — including the three anchor layers for `where`
1208
+ > **For the full lens guide, including the three anchor layers for `where`
1132
1209
  > (root, model-default, relation-descent), the `all` operator filter-first
1133
- > trick, per-model enum narrowing, and a validate-then-apply usage pattern —
1210
+ > trick, per-model enum narrowing, and a validate-then-apply usage pattern,
1134
1211
  > see [docs/LENS.md](./docs/LENS.md).**
1135
1212
  > This section covers the high-level shape and the multi-source bridges.
1136
1213
 
1137
1214
  ### What a lens is *for*
1138
1215
 
1139
- A lens is not a query filter. It's a composable, **enforceable model of authority
1140
- over data** — *what a party can see and what it can do* — delegated down a chain of
1216
+ A lens is not a query filter. It is a composable, **enforceable model of authority
1217
+ over data** (*what a party can see and what it can do*), delegated down a chain of
1141
1218
  trust boundaries (platform → org → space → subtenant → client). Each layer can only
1142
1219
  **narrow**, never widen (`validateNarrowing` keeps the chain monotonic), and the
1143
1220
  boundary is **enforced, not documented**:
1144
1221
 
1145
- - a rule authored against a lens provably can't reference outside it —
1146
- `validateRuleInLens`, at author time;
1222
+ - a rule authored against a lens provably can't reference outside it
1223
+ (`validateRuleInLens`, at author time);
1147
1224
  - the row-scope **`where` is the clamp, applied server-side at execution** via
1148
- `narrowRule` — the authored rule never sees it and can't escape it;
1149
- - what reaches an untrusted party reveals nothing hidden — `projectLens(…, { by: 'model' })`.
1225
+ `narrowRule`; the authored rule never sees it and can't escape it;
1226
+ - what reaches an untrusted party reveals nothing hidden (`projectLens(…, { by: 'model' })`).
1150
1227
 
1151
1228
  A lens defines a **surface area**, reused for distinct, separately-enforced
1152
1229
  constraints that may **diverge**: the *data-flow* surface (what you receive / pass
1153
1230
  into an interpolated template / expose to a client) vs the *reasoning* surface
1154
- (what you may author predicates against — which can be narrower than what you
1155
- actually get back). One predicate DSL (`Condition`) expresses both the **clamp**
1231
+ (what you may author predicates against, which can be narrower than what you
1232
+ get back). One predicate DSL (`Condition`) expresses both the **clamp**
1156
1233
  (`where`) and the **use** (rules), compiling to `check` / `toPrisma` / `toSql`.
1157
1234
  That's why the same primitive backs permissions, email targeting/conditions,
1158
- feature flags, and state-transition guards — it's the authority/visibility spine
1159
- they compose on, not a filter helper.
1235
+ feature flags, and state-transition guards: each composes on the same authority
1236
+ and visibility model.
1160
1237
 
1161
1238
  ### How it's built
1162
1239
 
@@ -1164,7 +1241,7 @@ The `Lens` primitive is a schema-aware view layer over one or more `FieldMap`s.
1164
1241
 
1165
1242
  ### FieldMap & FieldMapSet
1166
1243
 
1167
- A `FieldMap` is `{ models, enums? }` — models keyed by name, plus an optional enum registry scoped to that source. A `FieldMapSet` groups one or more `FieldMap`s and declares the cross-source edges between them:
1244
+ A `FieldMap` is `{ models, enums? }`: models keyed by name, plus an optional enum registry scoped to that source. A `FieldMapSet` groups one or more `FieldMap`s and declares the cross-source edges between them:
1168
1245
 
1169
1246
  ```ts
1170
1247
  import { stitchFieldMaps } from '@inixiative/json-rules';
@@ -1190,7 +1267,7 @@ const set = stitchFieldMaps({
1190
1267
  });
1191
1268
  ```
1192
1269
 
1193
- `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 used at eval time for hydration. Bridge cardinality controls list-vs-single on each side.
1270
+ `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 used at eval time for hydration. Bridge cardinality controls list-vs-single on each side.
1194
1271
 
1195
1272
  ### Lens
1196
1273
 
@@ -1207,12 +1284,12 @@ const lens = createLens({
1207
1284
  });
1208
1285
  ```
1209
1286
 
1210
- The lens is **schema only** — no data lives on it. Runtime data (rows, foreign tables, FE picker sources) is passed alongside, separately, when you need it.
1287
+ The lens is **schema only**; no data lives on it. Runtime data (rows, foreign tables, FE picker sources) is passed alongside, separately, when you need it.
1211
1288
 
1212
1289
  ### Relations
1213
1290
 
1214
1291
  Relations are fields, off by default. A bare lens reads its anchor model's columns and nothing
1215
- else. The first narrowing over the base lens turns a relation on through the relation object —
1292
+ else. The first narrowing over the base lens turns a relation on through the relation object,
1216
1293
  never through `picks`, which names columns only:
1217
1294
 
1218
1295
  ```ts
@@ -1239,7 +1316,7 @@ validateRuleInLens({ field: 'posts', arrayOperator: ArrayOperator.any, condition
1239
1316
  visited, and may nest further relations.
1240
1317
  - **Only the first narrowing turns relations on; later layers narrow.** A later layer may omit a
1241
1318
  relation (`omits: ['org']`, which `picks` never conflicts with), or restate one its parent shows
1242
- to add that hop's narrowing — a restatement hides nothing else. Naming a relation its parent
1319
+ to add that hop's narrowing; a restatement hides nothing else. Naming a relation its parent
1243
1320
  doesn't show fails `validateNarrowing` (`not_visible`), and does nothing at runtime.
1244
1321
  - **The model defaults grow a tree.** From the anchor and every spelled path, model-default
1245
1322
  turn-ons are followed breadth-first, each model once, at its nearest reach (ties: the earlier
@@ -1248,7 +1325,7 @@ validateRuleInLens({ field: 'posts', arrayOperator: ArrayOperator.any, condition
1248
1325
  agree and stay small. `lensVisit(lens, 'org.users')` resolves one visit on demand, as
1249
1326
  `projectLens` would give it, or `null`.
1250
1327
  - **Clamps.** The first narrowing's `where`s (and source eligibility `where`s) may read any
1251
- relation on the schema; a later layer's may read only what its parent shows — a delegate can't
1328
+ relation on the schema; a later layer's may read only what its parent shows, so a delegate can't
1252
1329
  probe a relation it can't see (`validateNarrowing` reports it; every posture throws). A bare
1253
1330
  value `path` reads the root row, so only `root.where` may hold one. `toLensSelect` fetches exactly the columns clamps read, and
1254
1331
  `projectRows({ keepClampColumns: true })` keeps them for a re-check.
@@ -1276,7 +1353,7 @@ const narrowing: LensNarrowing = {
1276
1353
  };
1277
1354
  ```
1278
1355
 
1279
- Composition across chained narrowings is pure intersection: relations are turned on by the first narrowing and only hidden after it. `where` clauses are anchored to the model they describe — `root.where` ANDs at the lens anchor, `mapDefaults[X].models[Y].where` injects at every visit of Y in map X, and `root.relations[R]...where` injects when the rule descends through R. Under the `all` array operator the clamp goes into the rule's window `filter`, so out-of-scope rows are dropped before the user's "every row matches" check; `check()` and `toPrisma` run it. See [docs/LENS.md](./docs/LENS.md) for the full anchor semantics.
1356
+ Composition across chained narrowings is pure intersection: relations are turned on by the first narrowing and only hidden after it. `where` clauses are anchored to the model they describe: `root.where` ANDs at the lens anchor, `mapDefaults[X].models[Y].where` injects at every visit of Y in map X, and `root.relations[R]...where` injects when the rule descends through R. Under the `all` array operator the clamp goes into the rule's window `filter`, so out-of-scope rows are dropped before the user's "every row matches" check; `check()` and `toPrisma` run it. See [docs/LENS.md](./docs/LENS.md) for the full anchor semantics.
1280
1357
 
1281
1358
  ### Lens Utilities
1282
1359
 
@@ -1284,15 +1361,15 @@ Composition across chained narrowings is pure intersection: relations are turned
1284
1361
  | --- | --- |
1285
1362
  | `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. |
1286
1363
  | `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 } })`. |
1287
- | `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). |
1288
- | `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`. |
1364
+ | `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). |
1365
+ | `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`. |
1289
1366
  | `validateRuleInLens(rule, lens)` | Validates a user rule's field paths and enum values against the narrowed lens, path-aware. Returns `{ ok, errors: { path, message, code }[] }` like `validateRule` (codes such as `not_in_lens`, `operator_kind_mismatch`, `invalid_value`, `value_not_allowed`). Every relation a field, a value ref, an offset or an `orderBy` / aggregate field crosses must be turned on. A bare value `path` is a root-row column, gated like a field. The security gate. |
1290
- | `describeRule(rule, lens)` | `{ sources, bridgesCrossed, supportedTargets, errors }`: the maps a rule reads, whether it crosses a bridge, which of `check` / `toPrisma` / `toSql` can run it (by the rule's shape, as `validateRule` reads it — a compiler may still refuse a field's kind, such as a date rule on a String column on Prisma), and the lens gate's `ValidationIssue`s. For routing and UX; `validateRuleInLens` stays the gate. |
1367
+ | `describeRule(rule, lens)` | `{ sources, bridgesCrossed, supportedTargets, errors }`: the maps a rule reads, whether it crosses a bridge, which of `check` / `toPrisma` / `toSql` can run it (by the rule's shape, as `validateRule` reads it; a compiler may still refuse a field's kind, such as a date rule on a String column on Prisma), and the lens gate's `ValidationIssue`s. For routing and UX; `validateRuleInLens` stays the gate. |
1291
1368
  | `getLensRoot(lensOrNarrowing)` | The base lens a narrowing chain is rooted at; a lens is its own. Throws on a cyclic chain. |
1292
1369
  | `clampLens(lens, clamps)` | The lens with `clamps` (`{ root?: { where }, mapDefaults?: { [map]: { models: { [model]: { where?, sources? } } } } }`) ANDed into its first narrowing over the base lens, one added over a bare lens; later layers kept as they were. Only the first layer's clamps read the whole schema, so a clamp on what a later layer hides goes here. A source's `where` ANDs; its `label` / `groupBy` win, and a source clamp on a field with none adds that option set. Wheres only narrow. |
1293
- | `lensVisit(lens, relationPath, options?)` | One visit as `projectLens` (by path) gives it — its shown fields with values and options, sources, labels and axes — at a dotted relation path from the anchor (`''` for the anchor), resolved on demand: nothing is enumerated, so it is cheap on any schema. `null` when a relation on the path isn't shown there (off, omitted, or outside the model-default tree). A builder walks a lens with it instead of re-deriving the lens's rules. |
1370
+ | `lensVisit(lens, relationPath, options?)` | One visit as `projectLens` (by path) gives it (its shown fields with values and options, sources, labels and axes) at a dotted relation path from the anchor (`''` for the anchor), resolved on demand: nothing is enumerated, so it is cheap on any schema. `null` when a relation on the path isn't shown there (off, omitted, or outside the model-default tree). A builder walks a lens with it instead of re-deriving the lens's rules. |
1294
1371
  | `walkLensPath(lens, path)` | Resolves one dotted path through the lens hop by hop: `{ outcome: 'resolved', hops, terminal, jsonSubPath }`, or `hidden` (a column it doesn't keep, or a relation it doesn't turn on there) / `missing` / `pastScalar` with the failing `index`. |
1295
- | `readLensValue(lens, row, path, options?)` | One value off a row, as the lens shows it: `{ ok: true, value }`, or `{ ok: false, reason }` — `hidden` / `missing` / `pastScalar` (the walk `validateRuleInLens` gates a field with), `relation` (the path ends on rows, not a value) or `list` (it crosses a to-many). Each row on the way, the root included, is checked against its visit's clamps: one a clamp hides, or a missing one, reads `null`. Only own properties are read, into a Json column too. `options` is what each clamp is checked with (`now`, `bindings`). For values a template interpolates. |
1372
+ | `readLensValue(lens, row, path, options?)` | One value off a row, as the lens shows it: `{ ok: true, value }`, or `{ ok: false, reason }`, where `reason` is `hidden` / `missing` / `pastScalar` (the walk `validateRuleInLens` gates a field with), `relation` (the path ends on rows, not a value) or `list` (it crosses a to-many). Each row on the way, the root included, is checked against its visit's clamps: one a clamp hides, or a missing one, reads `null`. Only own properties are read, into a Json column too. `options` is what each clamp is checked with (`now`, `bindings`). For values a template interpolates. |
1296
1373
  | `orderRecords(items, orderBy)` | Records sorted by an `OrderBy` exactly as a window orders them on every rail: each key in turn, own-property path reads, `dir` order, NULL or absent last in either direction, ties in input order. Returns a new array. Strings sort in JavaScript code-unit order, which can differ from a database's collation (see [Where the Rails Differ](#where-the-rails-differ)). |
1297
1374
  | `narrowRule(rule, narrowing)` | Composes the user rule with the lens's `where` clauses, injecting each at its anchor in the rule tree. Under an `all`, the clamp goes into the rule's window `filter`, which `check()` evaluates and `toPrisma` folds into the rule (`toSql` compiles no relation arrays). Other rules pass to `check` / `toPrisma` / `toSql`. |
1298
1375
  | `coerceRule(rule, lens)` | Stamps each field rule with its field's `coerceType` from the lens (`Int`, `Float`, `Decimal`, `BigInt`, `DateTime`, `Boolean`, `String`). Leaves date rules, aggregate comparisons, rules that already carry a `coerceType`, and anything below a Json column alone. |
@@ -1380,18 +1457,18 @@ const projection = projectLens(narrowing, { sourceValues: [values] });
1380
1457
 
1381
1458
  | Function | Purpose |
1382
1459
  | --- | --- |
1383
- | `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. |
1460
+ | `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. |
1384
1461
  | `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 sorted. 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`. |
1385
- | `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). |
1462
+ | `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). |
1386
1463
 
1387
1464
  Options never offer a value the lens disallows: `projectLens` drops fetched values outside a
1388
1465
  field's allowed set. Nor do they come through a row the lens hides: each source `where` is
1389
- narrowed under the whole lens as `narrowRule` narrows a rule — every relation it crosses carries
1466
+ narrowed under the whole lens as `narrowRule` narrows a rule: every relation it crosses carries
1390
1467
  that visit's clamps, inside an array condition (into its `condition`, or its `filter` under `all`,
1391
1468
  a window or no condition) and on each hop and terminal relation of a dotted path. A clamp a rule
1392
1469
  couldn't carry there (one narrowRule can't re-root, a to-many relation read flat) is refused, as
1393
1470
  it is for a rule; so is a source whose query has a window toPrisma can't compile (by its shape,
1394
- before anything compiles — `materializeSources` refuses it too, so the two never disagree).
1471
+ before anything compiles; `materializeSources` refuses it too, so the two never disagree).
1395
1472
 
1396
1473
  #### Two kinds of source
1397
1474
 
@@ -1399,7 +1476,7 @@ A source declared down a relation path offers the rows **reachable** from there:
1399
1476
  carried down through each relation's inverse (where the map declares one), and every clamp above
1400
1477
  it with it, so a Tag source under `User.tagAttachments.tag` offers the tags a live
1401
1478
  attachment of an in-tenant user points at. When a field should offer every row the lens lets its
1402
- model show — linked or not, what a rule may *name* — point the path source at the model's own
1479
+ model show (linked or not, what a rule may *name*), point the path source at the model's own
1403
1480
  source:
1404
1481
 
1405
1482
  ```ts
@@ -1426,34 +1503,34 @@ mapDefaults: {
1426
1503
  },
1427
1504
  ```
1428
1505
 
1429
- `from: 'mapDefaults'` resolves where it sits — `mapDefaults[<this path's map>].models[<this path's
1430
- model>].sources[<field>]` — and takes that source's eligibility (tenancy included), label and
1506
+ `from: 'mapDefaults'` resolves where it sits (`mapDefaults[<this path's map>].models[<this path's
1507
+ model>].sources[<field>]`) and takes that source's eligibility (tenancy included), label and
1431
1508
  axes; its own `where`, and child layers, only narrow it. A pointer drops the clamps the path
1432
1509
  carries down only in the layer that declares it: every layer before or after it still carries
1433
1510
  theirs, so a child's pointer can only narrow what its parent gave, and a tenant layer added after a
1434
1511
  pointer always narrows it. How depends on how it scopes: through `mapDefaults` (the model's own
1435
1512
  clamp or source) the pointer still offers unlinked rows; through a root `where` the clamp can only
1436
- reach the pointer down the path, so it offers just the linked rows — and across a bridge the
1513
+ reach the pointer down the path, so it offers just the linked rows, and across a bridge the
1437
1514
  clamp comes back as the query's `recheck` (below). Scope tenancy through `mapDefaults` to keep a pointer's unlinked rows.
1438
1515
  A pointer whose model declares no source fails `validateNarrowing` (`invalid_source`) and throws
1439
1516
  from `projectLens` (by path) / `toSourceQueries` / `materializeSources`, even where a layer hides
1440
1517
  its field; `projectLens(…, { by: 'model' })` and `describeRuleSources` read the lens without
1441
1518
  validating it. Across a bridge it is how a picker gets options at all: the
1442
1519
  model source compiles against the far map alone, with that map's own tenancy, where a path source
1443
- over-fetches and re-checks (see "Sources across a bridge"). A clamp a path can't carry down — a relation whose
1444
- map declares no inverse — is a `LensRefusal`, never an empty list. `materializeSources` refuses a pointer — a fetched collection can't hold unlinked
1520
+ over-fetches and re-checks (see "Sources across a bridge"). A clamp a path can't carry down (a relation whose
1521
+ map declares no inverse) is a `LensRefusal`, never an empty list. `materializeSources` refuses a pointer, because a fetched collection can't hold unlinked
1445
1522
  rows; query it with `toSourceQueries` and `materializeSourceQuery`.
1446
1523
 
1447
1524
  #### Sources across a bridge
1448
1525
 
1449
1526
  A source whose path, `where`, `label` or an axis reads across a bridge can't be decided by one
1450
- database — each holds one side. `toSourceQueries` still returns a real query for the side it can
1527
+ database: each holds one side. `toSourceQueries` still returns a real query for the side it can
1451
1528
  see, and marks it with `recheck`:
1452
1529
 
1453
1530
  - **The query over-fetches.** What reads across the bridge compiles to TRUE (the compilers'
1454
1531
  over-fetch), so the query never pre-filters on what it can't see: its rows are a **superset** of
1455
1532
  the true options. Everything local is still decided by the database.
1456
- - **`recheck` is what the database couldn't decide** — the conjuncts of `composedWhere` that read
1533
+ - **`recheck` is what the database couldn't decide**: the conjuncts of `composedWhere` that read
1457
1534
  across a bridge, or `true` when only the label or an axis does. **If `recheck` is present, the
1458
1535
  query's rows are candidates, not options.** A source that reads no bridge has no `recheck`.
1459
1536
  - **The query selects local columns only:** the value, a local label and local axes, the local
@@ -1461,15 +1538,15 @@ see, and marks it with `recheck`:
1461
1538
  read crosses first). It drops `distinct`, since candidates differ in what the re-check reads. A
1462
1539
  label or axis across the bridge is not selected.
1463
1540
  - **Load the far side, then materialize.** Put the far row inline on each candidate under its
1464
- bridge field (the `indexBridges` shape — one row, or a list where the bridge names many) and
1541
+ bridge field (the `indexBridges` shape: one row, or a list where the bridge names many) and
1465
1542
  call `materializeSourceQuery(query, rows, { lens, rowShape?, now? })`. It requires every key the
1466
- re-check and a bridged label or axis read, as `materializeSources` does — a candidate without
1543
+ re-check and a bridged label or axis read, as `materializeSources` does (a candidate without
1467
1544
  the far side, a far row without a column read, or a list where the bridge names one row throws a
1468
- `UsageError` — keeps the candidates `check(recheck, row)` holds, and reads the label and axes
1545
+ `UsageError`), keeps the candidates `check(recheck, row)` holds, and reads the label and axes
1469
1546
  across the bridge from the far side, in either row shape. Without `lens` it throws.
1470
1547
  - **A source past a bridge** (its path crosses one) is queried against its own model's map; the
1471
1548
  clamps above it are carried back across the bridge through the far model's bridge field, and
1472
- come back as its `recheck` — so each candidate holds the near rows inline
1549
+ come back as its `recheck`, so each candidate holds the near rows inline
1473
1550
  (`{ id, industry, 'prisma:FanUser': [{ email, … }] }`).
1474
1551
  - **A re-check reading into a Json column selects the column whole** (`meta: true`, never a nested
1475
1552
  select into it); the re-check reads inside it in memory.
@@ -1509,20 +1586,20 @@ const holds = forRecheck.filter((row) => check(narrowRule(rule, narrowing), row,
1509
1586
 
1510
1587
  | Function | Purpose |
1511
1588
  | --- | --- |
1512
- | `toLensSelect(lensOrNarrowing, options?)` | `{ select }` for `findMany` at the base model. It selects each visit's visible columns and the relations turned on there (one that is off is not fetched; the model-default tree bounds it), and every column a `where` on the way reads. A to-many relation carries its visit's clamps compiled as its `where`, so related rows come pre-narrowed — unless a clamp reads that list: a clamp reads it whole, as the database does, so it is fetched whole and `projectRows` cuts it. A to-one relation takes no `where` in Prisma, so `projectRows` drops one its clamp hides. A relation that shows no column — one turned on with all its columns hidden, or one a clamp reads only for presence or a count — is fetched by its key alone — the join key, else `id` — even a hidden one, as a clamp's columns are; never another column. The fetch carries it for the re-check and a viewer's projection drops it; a model with no key is not fetched, and presence on it can't be re-checked from fetched rows. A root that shows no column is selected by its `id` likewise. Bridges are skipped. It also selects what each projected source reads — the value, its label and axes, and every column and relation its option query's condition reads — as it does a clamp's columns, so `materializeSources` over the fetched rows offers what the database does; a viewer's projection drops them. For a source across a bridge that is its local reads: what it reads on this side, hidden or not, and each crossed bridge's local `on` key, so the rows plus the far side loaded under its bridge field answer it. A to-many relation's clamp that needs a counting step (a count or an aggregate), or has a window toPrisma can't compile, is refused (a `LensRefusal`, which `validateNarrowing` reports) before anything compiles. `options` is the clock for compiling the clamps. The root's own clamps are the query's `where`: `toPrisma(rule, { lens })`. |
1513
- | `projectRows(lensOrNarrowing, rows, options?)` | Rows cut to what the lens shows, recursively. Hidden columns, and relations that are off or omitted, are removed. A row a visit's `where` hides is dropped from the root or a list, and a to-one row becomes `null`. `keepClampColumns: true` keeps the columns those `where`s and the projected sources read, even hidden ones, and a hidden to-one row, or a hidden row of a list a clamp reads, as those columns alone, so `check(narrowRule(rule, lens), row)` re-tests the clamps as the database does, for any rule the lens admits; that output carries hidden values, so never return it to a viewer. The other options (`now`, `bindings`) are what each `where` is checked with. A `Decimal` column's value — a Decimal.js-like object such as Prisma's `Decimal` (anything with `toNumber()`), or a numeric string — comes back a number, a list column element by element; a non-numeric value passes through. Plain JSON out. |
1589
+ | `toLensSelect(lensOrNarrowing, options?)` | `{ select }` for `findMany` at the base model. It selects each visit's visible columns and the relations turned on there (one that is off is not fetched; the model-default tree bounds it), and every column a `where` on the way reads. A to-many relation carries its visit's clamps compiled as its `where`, so related rows come pre-narrowed, unless a clamp reads that list: a clamp reads it whole, as the database does, so it is fetched whole and `projectRows` cuts it. A to-one relation takes no `where` in Prisma, so `projectRows` drops one its clamp hides. A relation that shows no column (one turned on with all its columns hidden, or one a clamp reads only for presence or a count) is fetched by its key alone (the join key, else `id`), even a hidden one, as a clamp's columns are; never another column. The fetch carries it for the re-check and a viewer's projection drops it; a model with no key is not fetched, and presence on it can't be re-checked from fetched rows. A root that shows no column is selected by its `id` likewise. Bridges are skipped. It also selects what each projected source reads (the value, its label and axes, and every column and relation its option query's condition reads), as it does a clamp's columns, so `materializeSources` over the fetched rows offers what the database does; a viewer's projection drops them. For a source across a bridge that is its local reads: what it reads on this side, hidden or not, and each crossed bridge's local `on` key, so the rows plus the far side loaded under its bridge field answer it. A to-many relation's clamp that needs a counting step (a count or an aggregate), or has a window toPrisma can't compile, is refused (a `LensRefusal`, which `validateNarrowing` reports) before anything compiles. `options` is the clock for compiling the clamps. The root's own clamps are the query's `where`: `toPrisma(rule, { lens })`. |
1590
+ | `projectRows(lensOrNarrowing, rows, options?)` | Rows cut to what the lens shows, recursively. Hidden columns, and relations that are off or omitted, are removed. A row a visit's `where` hides is dropped from the root or a list, and a to-one row becomes `null`. `keepClampColumns: true` keeps the columns those `where`s and the projected sources read, even hidden ones, and a hidden to-one row, or a hidden row of a list a clamp reads, as those columns alone, so `check(narrowRule(rule, lens), row)` re-tests the clamps as the database does, for any rule the lens admits; that output carries hidden values, so never return it to a viewer. The other options (`now`, `bindings`) are what each `where` is checked with. A `Decimal` column's value, whether a Decimal.js-like object such as Prisma's `Decimal` (anything with `toNumber()`) or a numeric string, comes back a number, a list column element by element; a non-numeric value passes through. Plain JSON out. |
1514
1591
 
1515
1592
  ### Evaluating Across Bridges
1516
1593
 
1517
- `path:` refs (used for value comparisons) walk via the same dotted-path mechanism as `field:`. Bridge keys (`'salesforce:Contact'`) are just plain object properties, so `path: 'salesforce:Contact.industry'` works in both `field:` (left side) and `path:` (right side) positions.
1594
+ `path:` refs (used for value comparisons) walk via the same dotted-path mechanism as `field:`. Bridge keys (`'salesforce:Contact'`) are plain object properties, so `path: 'salesforce:Contact.industry'` works in both `field:` (left side) and `path:` (right side) positions.
1518
1595
 
1519
1596
  **Limitations to know:**
1520
1597
 
1521
- - **1-many bridge arrays are not iterable mid-path.** `field: 'crm:MarketingEvent.campaign'` or `path: 'crm:MarketingEvent.campaign'` returns `undefined` when the bridge value is an array — a path read follows own properties one segment at a time and doesn't fan out across array elements. Use a numeric index (`crm:MarketingEvent.0.campaign` or `crm:MarketingEvent[0].campaign`) or `arrayOperator` on the `field:` side to iterate. A name on `Object.prototype` (`constructor`, `toString`) reads as absent.
1522
- - **Bridge keys are plain object properties.** The engine doesn't consult `lens.bridges` at eval time — callers structure `data` correctly using the schema as a guide. Use `indexBridges(lens, rawForeign)` to pre-index foreign rows by `on` field, then embed under bridge keys per anchor row.
1598
+ - **1-many bridge arrays are not iterable mid-path.** `field: 'crm:MarketingEvent.campaign'` or `path: 'crm:MarketingEvent.campaign'` returns `undefined` when the bridge value is an array: a path read follows own properties one segment at a time and doesn't fan out across array elements. Use a numeric index (`crm:MarketingEvent.0.campaign` or `crm:MarketingEvent[0].campaign`) or `arrayOperator` on the `field:` side to iterate. A name on `Object.prototype` (`constructor`, `toString`) reads as absent.
1599
+ - **Bridge keys are plain object properties.** The engine doesn't consult `lens.bridges` at eval time; callers structure `data` correctly using the schema as a guide. Use `indexBridges(lens, rawForeign)` to pre-index foreign rows by `on` field, then embed under bridge keys per anchor row.
1523
1600
 
1524
1601
 
1525
- `check()` itself is bridge-unaware — it walks paths via plain property access. The lens primitive is **schema metadata** (what fields exist, what bridges link them, what `on` fields join each side). The caller is responsible for structuring `data` accordingly:
1602
+ `check()` itself is bridge-unaware: it walks paths via plain property access. The lens primitive is **schema metadata** (what fields exist, what bridges link them, what `on` fields join each side). The caller is responsible for structuring `data` accordingly:
1526
1603
 
1527
1604
  ```ts
1528
1605
  const fanUser = { id: 'u1', email: 'a@b.com', crmId: 'c1' };
@@ -1536,7 +1613,7 @@ const rule = { field: 'salesforce:Contact.industry', operator: Operator.equals,
1536
1613
  check(rule, data);
1537
1614
  ```
1538
1615
 
1539
- For **bidirectional traversal**, use JavaScript object references — `check`'s path walker handles circular structures fine because rules are finite trees and only resolve named paths:
1616
+ For **bidirectional traversal**, use JavaScript object references. `check`'s path walker handles circular structures fine because rules are finite trees and only resolve named paths:
1540
1617
 
1541
1618
  ```ts
1542
1619
  fanUser['salesforce:Contact'] = contact;
@@ -1565,7 +1642,7 @@ check(
1565
1642
  );
1566
1643
  ```
1567
1644
 
1568
- The lens schema (with `Bridge.endpoints[*].on`) is what tells the caller how to fetch and index foreign data. The runtime engine just walks the resulting structure.
1645
+ The lens schema (with `Bridge.endpoints[*].on`) is what tells the caller how to fetch and index foreign data. The runtime engine walks the resulting structure.
1569
1646
 
1570
1647
  ## Examples
1571
1648