foldkit-entity 0.15.0 → 0.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.
Files changed (48) hide show
  1. package/README.md +128 -17
  2. package/dist/conformance/index.d.ts.map +1 -1
  3. package/dist/conformance/index.js +20 -0
  4. package/dist/conformance/index.js.map +1 -1
  5. package/dist/conformance/operator.d.ts.map +1 -1
  6. package/dist/conformance/operator.js +13 -4
  7. package/dist/conformance/operator.js.map +1 -1
  8. package/dist/entity.d.ts +14 -2
  9. package/dist/entity.d.ts.map +1 -1
  10. package/dist/entity.js +41 -12
  11. package/dist/entity.js.map +1 -1
  12. package/dist/evaluate.d.ts +1 -1
  13. package/dist/evaluate.d.ts.map +1 -1
  14. package/dist/evaluate.js +22 -18
  15. package/dist/evaluate.js.map +1 -1
  16. package/dist/expr.d.ts +70 -20
  17. package/dist/expr.d.ts.map +1 -1
  18. package/dist/expr.js +67 -47
  19. package/dist/expr.js.map +1 -1
  20. package/dist/held.js +11 -3
  21. package/dist/held.js.map +1 -1
  22. package/dist/index.d.ts +38 -6
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +9 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/invariant.d.ts.map +1 -1
  27. package/dist/invariant.js +26 -20
  28. package/dist/invariant.js.map +1 -1
  29. package/dist/law.d.ts.map +1 -1
  30. package/dist/law.js +3 -9
  31. package/dist/law.js.map +1 -1
  32. package/dist/lawCore.d.ts +42 -0
  33. package/dist/lawCore.d.ts.map +1 -0
  34. package/dist/lawCore.js +12 -0
  35. package/dist/lawCore.js.map +1 -0
  36. package/dist/memoryTable.d.ts +11 -0
  37. package/dist/memoryTable.d.ts.map +1 -0
  38. package/dist/memoryTable.js +69 -0
  39. package/dist/memoryTable.js.map +1 -0
  40. package/dist/operators.d.ts.map +1 -1
  41. package/dist/operators.js +2 -66
  42. package/dist/operators.js.map +1 -1
  43. package/dist/sets.js.map +1 -1
  44. package/dist/write.d.ts +1 -1
  45. package/dist/write.d.ts.map +1 -1
  46. package/dist/write.js +40 -18
  47. package/dist/write.js.map +1 -1
  48. package/package.json +1 -1
@@ -2,8 +2,8 @@ import { Option } from "effect";
2
2
  import { Collation } from "./collation.js";
3
3
  import { AnyQuery, Operandish, Operation, OperatorDescriptor, OperatorTable, OrderTerm, Predicate } from "./expr.js";
4
4
  import { HeldRow, HeldRows, Pinned } from "./held.js";
5
- import { MemoryOperators } from "./operators.js";
6
5
  import { ExprContext, NowExpr, ViewerExpr } from "./context.js";
6
+ import { MemoryOperators } from "./operators.js";
7
7
  /** A row as this interpreter reads one: values by field key. */
8
8
  export type Row = Readonly<Record<string, unknown>>;
9
9
  export declare class QueryEvaluateError extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"evaluate.d.ts","names":[],"sources":["../src/evaluate.ts"],"mappings":";;;;;;;YAiDY,MAAM,SAAS;qBAEd,2BAA2B;EACtC,YAAY;;;;;;;qBAWD,6BAA6B;WAC/B,UAAU;;WAEV;;EAET,YAAY,UAAU,oBAAoB,YAAW;;;;;;qBAyC1C,4BAA4B;EACvC,YAAY,MAAM,sBAAsB,kBAAkB;;;iBAyF3C;WACN,MAAM;WACN;;;;;;;qBAoHE,yBAAyB;EACpC,YAAY;;;;;;;qBA+GD,gBAAa,UACd,oBAAkB,QACpB,wBAAsB;WAEnB,WAAW,OAAO,OAAO;WACzB,WAAW;;;KA+BnB;;;;;;;;qBAoDQ,iBAAc,MACnB,YAAU;WAEL,QAAQ;WACR,YAAY;WACZ,UAAU;;;YAkMX,iBAAiB;;;;;;;;qBAYhB,UAAO,MACZ,WAAS,OACR,KAAG,YACC,iBAAe,UAChB,gBACT,OAAO,OAAO;;qBA8BJ,YAAS,MACd,WAAS,KACV,KAAG,QACD,KAAG,OACJ,KAAG,YACE,oBACV;;;;;;YAiBS,QAAQ,IAAI;WACT;WAAwB,OAAO;;WAC/B;WAA0B;;;UAM/B;WACC,QAAQ;WACR,YAAY;;WAEZ,UAA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QAAQ;WACR,YAAY;WACZ,UAAU;;;YAsMX,iBAAiB;;;;;;;;qBAYhB,UAAO,MACZ,WAAS,OACR,KAAG,YACC,iBAAe,UAChB,gBACT,OAAO,OAAO;;qBA8BJ,YAAS,MACd,WAAS,KACV,KAAG,QACD,KAAG,OACJ,KAAG,YACE,oBACV;;;;;;YAiBS,QAAQ,IAAI;WACT;WAAwB,OAAO;;WAC/B;WAA0B;;;UAM/B;WACC,QAAQ;WACR,YAAY;;WAEZ,UAAU;;;;;WAKV,OAAO;;;;;;;;;qBAqBL;;EAEX,YAAS,WACI,WAAS,KACf,SAAO,UACH;aAA0B,OAAO;QACzC;;;;;;;;;EAqBH,QAAK,MACG,UAAQ,OACP,KAAG,KACL,SAAO,UACH,KAAK;aAAoC;QACjD;;;;;;;;EAgCH,OAAI,YACU,cAAc,YAAU;aAChB,QAAQ;aAA0B,UAAU;QAC/D;EAEH,QAAQ,GAAG,GAAC,SACD,QAAQ,IAAE;aACD,UAAU,OAAO,MAAM;aAAY,YAAY,mBAAmB;QACnF;;;;;;;;;;;qBAqLQ,cAAW,OACf,cAAc,YAAU,MACzB,KAAG,OACF,KAAG,eACG;WAEF,QAAQ;WACR,YAAY;WACZ,UAAU;;;;;;;;qBAmBV,WAAW,cAAc;;;;;;qBAmBzB,kBAAe,MACpB,UAAQ,YACH;;;;;;;;;qBAkBA,WAAQ,MACb,UAAQ,OACP,KAAG,MACJ,cAAc,MAAI;WAEb,YAAY;;WAEZ,UAAU;MAEpB,cAAc;;iBAaA;WACN,SAAS,cAAc;WACvB,SAAS,cAAc;;;;;;;;;;;;;qBAcrB,eAAY,MACjB,UAAQ,OACP,KAAG,MACJ,cAAc,MAAI;WAEb,YAAY;;WAEZ,UAAU;MAEpB"}
package/dist/evaluate.js CHANGED
@@ -4,7 +4,7 @@ import { absurd } from "effect/Function";
4
4
  import { Collation } from "./collation.js";
5
5
  import { Expr, Query, dependenciesOf, isPredicate, missingName, noOperators } from "./expr.js";
6
6
  import { Held } from "./held.js";
7
- import { Operators } from "./operators.js";
7
+ import { kernelOperators } from "./memoryTable.js";
8
8
  import { contextValue } from "./context.js";
9
9
  // src/evaluate.ts
10
10
  /**
@@ -134,12 +134,7 @@ const reached = (from, via) => {
134
134
  /** A value two `eq`s agree on exactly, on both sides of the wire: never null, NaN or a structure. */
135
135
  const pinnable = (value) => typeof value === "string" || typeof value === "boolean" || typeof value === "bigint" || typeof value === "number" && !Number.isNaN(value);
136
136
  /** An `eq` of a field of the row and something else, the field first. */
137
- const fieldAndSide = (predicate) => {
138
- if (predicate._tag !== "Eq") return Option.none();
139
- if (predicate.left._tag === "Field") return Option.some([predicate.left, predicate.right]);
140
- if (predicate.right._tag === "Field") return Option.some([predicate.right, predicate.left]);
141
- return Option.none();
142
- };
137
+ const fieldAndSide = Match.type().pipe(Match.tag("Eq", ({ left, right }) => Option.orElse(Option.map(fieldOf(left), (field) => [field, right]), () => Option.map(fieldOf(right), (field) => [field, left]))), Match.orElse(() => Option.none()));
143
138
  const pinsOf = (predicates, input, context) => {
144
139
  const pins = /* @__PURE__ */ new Map();
145
140
  let whole = true;
@@ -163,6 +158,9 @@ const pinsOf = (predicates, input, context) => {
163
158
  whole
164
159
  };
165
160
  };
161
+ const fieldOf = Match.type().pipe(Match.tag("Field", (field) => Option.some(field)), Match.orElse(() => Option.none()));
162
+ /** A filter's conjuncts; built once, since `exists` asks for every row judged. */
163
+ const operandsOf = Match.type().pipe(Match.tag("And", ({ operands }) => operands), Match.orElse((single) => [single]));
166
164
  /**
167
165
  * Whether some row pointing at the one `via` reaches holds the filter: true
168
166
  * as soon as a held one does, false only when every one is held and none
@@ -175,7 +173,7 @@ const exists = (node, scope) => {
175
173
  if (isUnheld(anchor)) return anchor;
176
174
  const pinned = Option.match(node.where, {
177
175
  onNone: () => /* @__PURE__ */ new Map(),
178
- onSome: (where) => pinsOf(where._tag === "And" ? where.operands : [where], scope.input, scope.context).pins
176
+ onSome: (where) => pinsOf(operandsOf(where), scope.input, scope.context).pins
179
177
  });
180
178
  const { rows, missing } = anchor.pointing(node.relation, pinned);
181
179
  let unheld = Option.map(missing, (reason) => new Unheld(reason));
@@ -331,7 +329,7 @@ const valueOfOperand = (node, options = {}) => {
331
329
  row: noRow,
332
330
  input: options.input ?? {},
333
331
  next: noRow,
334
- operators: options.operators ?? Operators.kernel,
332
+ operators: options.operators ?? kernelOperators,
335
333
  judging: false,
336
334
  find: noRows,
337
335
  context: options.context
@@ -394,6 +392,7 @@ const holds = (node, scope) => {
394
392
  case "In": {
395
393
  const among = valueOf(node.among, scope);
396
394
  if (isUnheld(among)) return among;
395
+ if (isNull(among)) return "unknown";
397
396
  if (!Array.isArray(among)) throw new QueryEvaluateError("a membership test was given a list that is not a list");
398
397
  if (among.length === 0) return false;
399
398
  const value = valueOf(node.value, scope);
@@ -449,7 +448,7 @@ const readsBeyond = /* @__PURE__ */ new WeakMap();
449
448
  * predicate before it builds anything: `isNull($status)` is known before any
450
449
  * row is. Refuses what `evaluate` refuses (text holding a NUL).
451
450
  */
452
- const decided = (node, input, operators = Operators.kernel, context) => {
451
+ const decided = (node, input, operators = kernelOperators, context) => {
453
452
  let reads = readsBeyond.get(node);
454
453
  if (reads === void 0) {
455
454
  const read = dependenciesOf(node);
@@ -470,7 +469,7 @@ const decided = (node, input, operators = Operators.kernel, context) => {
470
469
  })));
471
470
  };
472
471
  /** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
473
- const truthOver = (node, row, input = {}, next = {}, operators = Operators.kernel) => settled(holds(node, {
472
+ const truthOver = (node, row, input = {}, next = {}, operators = kernelOperators) => settled(holds(node, {
474
473
  row: flat(row),
475
474
  input,
476
475
  next: flat(next),
@@ -508,7 +507,7 @@ const Judge = {
508
507
  row: viewOf(row),
509
508
  input: options.input ?? {},
510
509
  next: options.next === void 0 ? noRow : viewOf(options.next),
511
- operators: options.operators ?? Operators.kernel,
510
+ operators: options.operators ?? kernelOperators,
512
511
  judging: true,
513
512
  context: options.context,
514
513
  find: finder(options.rows)
@@ -529,7 +528,7 @@ const Judge = {
529
528
  row: viewOf(row),
530
529
  input,
531
530
  next: noRow,
532
- operators: options.operators ?? Operators.kernel,
531
+ operators: options.operators ?? kernelOperators,
533
532
  judging: true,
534
533
  context: options.context,
535
534
  find: finder(options.rows)
@@ -548,7 +547,12 @@ const Judge = {
548
547
  * whose filter fixes the same values counts.
549
548
  */
550
549
  pins: (predicates, options = {}) => pinsOf(predicates, options.input ?? {}, options.context),
551
- match: (verdict, cases) => verdict._tag === "Known" ? cases.onKnown(verdict.truth) : cases.onUnknown(verdict.reason)
550
+ match: (verdict, cases) => {
551
+ switch (verdict._tag) {
552
+ case "Known": return cases.onKnown(verdict.truth);
553
+ case "Unknown": return cases.onUnknown(verdict.reason);
554
+ }
555
+ }
552
556
  };
553
557
  /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
554
558
  const matches = (body, row, input, operators, context) => body.where.map((node) => settled(holds(node, {
@@ -658,7 +662,7 @@ const ordered = (rows, terms, query, scope) => {
658
662
  const compareRows = (terms, left, right, query, options = {}) => {
659
663
  const scope = {
660
664
  input: options.input ?? {},
661
- operators: options.operators ?? Operators.kernel,
665
+ operators: options.operators ?? kernelOperators,
662
666
  context: options.context
663
667
  };
664
668
  const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)];
@@ -689,7 +693,7 @@ const supported = [
689
693
  * than skipping it and answering a different question. Called by `evaluate`;
690
694
  * call it directly to check a body once instead of on every run.
691
695
  */
692
- const assertSupported = (body, operators = Operators.kernel) => {
696
+ const assertSupported = (body, operators = kernelOperators) => {
693
697
  const missing = Query.unsupported(body, supported, operators);
694
698
  if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
695
699
  };
@@ -702,7 +706,7 @@ const assertSupported = (body, operators = Operators.kernel) => {
702
706
  * with anywhere else.
703
707
  */
704
708
  const evaluate = (body, input, rows, options = {}) => {
705
- const operators = options.operators ?? Operators.kernel;
709
+ const operators = options.operators ?? kernelOperators;
706
710
  const { context } = options;
707
711
  assertSupported(body, operators);
708
712
  return ordered(rows.filter((row) => matches(body, row, input, operators, context)), Query.orderFor(body, input), body.entity.name, {
@@ -723,7 +727,7 @@ const evaluate = (body, input, rows, options = {}) => {
723
727
  * keys of different kinds across rows.
724
728
  */
725
729
  const evaluateEach = (body, input, rows, options = {}) => {
726
- const operators = options.operators ?? Operators.kernel;
730
+ const operators = options.operators ?? kernelOperators;
727
731
  const { context } = options;
728
732
  assertSupported(body, operators);
729
733
  const terms = Query.orderFor(body, input);
@@ -1 +1 @@
1
- {"version":3,"file":"evaluate.js","names":[],"sources":["../src/evaluate.ts"],"sourcesContent":["/**\n * The reference interpreter: a query body run over rows already in memory.\n *\n * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body\n * directly, which is what makes \"source-neutral\" a fact rather than a claim —\n * the two are checked against each other over a real database, and a body that\n * means one thing here and another there is a bug in one of them.\n *\n * It is also the interpreter to reach for when there is no database: a test\n * that wants rows, a server assembling a page from values it already holds, or\n * a client judging rows it already has.\n *\n * It lives in `foldkit-entity` because it is the **reference semantics** of the\n * IR this package owns — what §6.0.1 means operationally rather than in prose —\n * and a specification's reference implementation belongs with the\n * specification. The rule that keeps it here: **it may depend on the IR and\n * nothing else.** The moment it wants a Remote concept it has moved to the\n * wrong place and should leave.\n *\n * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,\n * because SQL is what the other interpreter runs. The important case is null:\n * `null = null` is unknown in SQL and a row is not matched by it, where\n * JavaScript would happily call the two equal.\n */\nimport { Match, Option, Schema, SchemaAST } from 'effect'\nimport { absurd } from 'effect/Function'\nimport { Collation } from './collation.js'\nimport { Expr, Query, dependenciesOf, isPredicate, missingName, noOperators } from './expr.js'\nimport type {\n AnyExpr,\n AnyQuery,\n CallExpr,\n ExistsPredicate,\n OneRelation,\n Operandish,\n Operation,\n OperatorDescriptor,\n OperatorTable,\n OrderTerm,\n Predicate,\n TestPredicate,\n} from './expr.js'\nimport { Held, type HeldRow, type HeldRows, type Pinned } from './held.js'\nimport type { AnyEntity } from './index.js'\nimport { Operators, type MemoryImplementation, type MemoryOperators } from './operators.js'\nimport { contextValue, type ExprContext, type NowExpr, type ViewerExpr } from './context.js'\nimport { own } from './record.js'\n\n/** A row as this interpreter reads one: values by field key. */\nexport type Row = Readonly<Record<string, unknown>>\n\nexport class QueryEvaluateError extends Error {\n constructor(message: string) {\n super(`[foldkit-entity] ${message}`)\n this.name = 'QueryEvaluateError'\n }\n}\n\n/**\n * A call of a primitive operator the table does not implement. Its own class,\n * because a form judging an invariant reads it as a judgement it cannot make\n * (`Undecided`), not as a failure.\n */\nexport class OperatorMissingError extends QueryEvaluateError {\n readonly operator: OperatorDescriptor\n /** The operator by its id, and its version past the first. */\n readonly named: string\n /** `operators`, the table that lacks it, names the versions of it that it does hold. */\n constructor(operator: OperatorDescriptor, operators: OperatorTable = noOperators) {\n super(`this interpreter does not run the operator \"${missingName(operator, operators)}\"`)\n this.name = 'OperatorMissingError'\n this.operator = operator\n this.named = operatorName(operator)\n }\n}\n\n/** An operator by its id, and its version when that is not the first. */\nconst operatorName = (operator: OperatorDescriptor): string =>\n operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`\n\n/**\n * What a predicate is judged over: the row, the input it was given, and the row\n * a write would leave, which an invariant reads (`Next`).\n */\ninterface Scope {\n readonly row: View\n readonly input: Row\n readonly next: View\n /** How a primitive operator is run. */\n readonly operators: MemoryOperators\n /**\n * Whether this is `Judge`, for which an operator the table lacks is one more\n * thing it does not know; elsewhere it refuses the run.\n */\n readonly judging: boolean\n /** What `Expr.viewer` and `Expr.now` read; a run given none refuses them. */\n readonly context?: ExprContext | undefined\n /** The row of `entity` with this id, where a path from the viewer starts. */\n readonly find: (entity: AnyEntity, id: unknown) => View | null | Unheld\n}\n\n/** A run given one row: the viewer's row is another, which it does not have. */\nconst noRows = (entity: AnyEntity): Unheld =>\n new Unheld(`a path from the viewer reads a ${entity.name}, another row`)\n\n/**\n * A run that reads `Expr.viewer` or `Expr.now` and was given no context. No\n * row causes it, so `evaluateEach` refuses the run rather than each row.\n */\nexport class ContextMissingError extends QueryEvaluateError {\n constructor(term: ViewerExpr<unknown> | NowExpr<unknown>, why: string) {\n super(`this run reads ${Expr.show(term)}, but ${why}`)\n this.name = 'ContextMissingError'\n }\n}\n\nconst contextOf = (node: ViewerExpr<unknown> | NowExpr<unknown>, scope: Scope): unknown => {\n if (scope.context === undefined) {\n throw new ContextMissingError(node, 'was given no context to read it from')\n }\n return Option.getOrThrowWith(\n contextValue(node, scope.context),\n () => new ContextMissingError(node, 'its context has no reading of the time'),\n )\n}\n\n/**\n * What the interpreter does not know: a value, or a truth, that rests on\n * something the holder does not have. Never a value a row holds, which is\n * what lets one sit among values. SQL has no such thing; its unknown is null.\n */\nclass Unheld {\n constructor(readonly reason: string) {}\n}\n\nconst isUnheld = (value: unknown): value is Unheld => value instanceof Unheld\n\n/** A truth, or that it rests on something not held: what `holds` comes to. */\ntype Judged = Truth | Unheld\n\n/** A row as the interpreter reads it, whoever holds it: values may be `Unheld`. */\ninterface View {\n readonly field: (key: string) => unknown\n /** The row a `one` relation points at; null for none. */\n readonly follow: (relation: OneRelation) => View | null | Unheld\n readonly pointing: (\n relation: OneRelation,\n pinned: Pinned,\n ) => {\n readonly rows: ReadonlyArray<View>\n readonly missing: Option.Option<string>\n }\n}\n\n/**\n * One plain row, all a two-valued run is given: a key it lacks is null, as\n * SQL binds a missing value, and no other row can be reached from it.\n */\nconst flat = (row: Row): View => ({\n field: key => own(row, key),\n follow: relation => new Unheld(`${relation.owner.name}.${relation.key} leads to another row`),\n pointing: relation => ({\n rows: [],\n missing: Option.some(`${relation.owner.name}.${relation.key} is read from other rows`),\n }),\n})\n\n/** A holder's row as the interpreter reads it. */\nconst viewOf = (row: HeldRow): View => ({\n field: key =>\n Held.match(row.field(key), { onHeld: value => value, onUnheld: reason => new Unheld(reason) }),\n follow: relation =>\n Held.match<Option.Option<HeldRow>, View | null | Unheld>(row.follow(relation), {\n onHeld: target => Option.match(target, { onNone: () => null, onSome: viewOf }),\n onUnheld: reason => new Unheld(reason),\n }),\n pointing: (relation, pinned) => {\n const { rows, missing } = row.pointing(relation, pinned)\n return { rows: rows.map(viewOf), missing }\n },\n})\n\n/** A run that is given no row: whatever it reads of one, it lacks. */\nconst noRow: View = flat({})\n\n/**\n * The row `via` reaches from `from`: null when a link is null or reaches a row\n * the holder knows is not there.\n */\nconst reached = (from: View, via: ReadonlyArray<OneRelation>): View | null | Unheld => {\n let at: View | null | Unheld = from\n for (const relation of via) {\n if (at === null || isUnheld(at)) return at\n at = at.follow(relation)\n }\n return at\n}\n\n/** What a conjunction fixes by field, and whether that is all it says (`Judge.pins`). */\nexport interface Pins {\n readonly pins: Pinned\n readonly whole: boolean\n}\n\n/** A value two `eq`s agree on exactly, on both sides of the wire: never null, NaN or a structure. */\nconst pinnable = (value: unknown): boolean =>\n typeof value === 'string' ||\n typeof value === 'boolean' ||\n typeof value === 'bigint' ||\n (typeof value === 'number' && !Number.isNaN(value))\n\n/** An `eq` of a field of the row and something else, the field first. */\nconst fieldAndSide = (\n predicate: Predicate,\n): Option.Option<readonly [{ readonly key: string }, Operandish]> => {\n if (predicate._tag !== 'Eq') return Option.none()\n if (predicate.left._tag === 'Field') return Option.some([predicate.left, predicate.right])\n if (predicate.right._tag === 'Field') return Option.some([predicate.right, predicate.left])\n return Option.none()\n}\n\nconst pinsOf = (\n predicates: ReadonlyArray<Predicate>,\n input: Row,\n context: ExprContext | undefined,\n): Pins => {\n const pins = new Map<string, unknown>()\n let whole = true\n const given = (node: Operandish): Option.Option<unknown> =>\n Match.value(node).pipe(\n Match.tags({\n Literal: ({ value }) => Option.some<unknown>(value),\n Input: ({ key }) => Option.some<unknown>(own(input, key)),\n Viewer: viewer => (context === undefined ? Option.none() : contextValue(viewer, context)),\n }),\n Match.orElse(() => Option.none()),\n )\n for (const predicate of predicates) {\n const pin = Option.flatMap(fieldAndSide(predicate), ([field, side]) =>\n Option.map(Option.filter(given(side), pinnable), value => [field.key, value] as const),\n )\n if (Option.isNone(pin)) {\n whole = false\n continue\n }\n const [key, value] = pin.value\n if (pins.has(key) && pins.get(key) !== value) whole = false\n pins.set(key, value)\n }\n return { pins, whole }\n}\n\n/**\n * Whether some row pointing at the one `via` reaches holds the filter: true\n * as soon as a held one does, false only when every one is held and none\n * does. SQL's exists is never null; reached through a path that reaches no\n * row, it is, as the path's field would be.\n */\nconst exists = (node: ExistsPredicate, scope: Scope): Judged => {\n const anchor = reached(scope.row, node.via)\n if (anchor === null) return 'unknown'\n if (isUnheld(anchor)) return anchor\n const pinned = Option.match(node.where, {\n onNone: (): Pinned => new Map(),\n onSome: where =>\n pinsOf(where._tag === 'And' ? where.operands : [where], scope.input, scope.context).pins,\n })\n const { rows, missing } = anchor.pointing(node.relation, pinned)\n let unheld = Option.map(missing, reason => new Unheld(reason))\n for (const row of rows) {\n const truth = Option.match(node.where, {\n onNone: (): Judged => true,\n onSome: where => holds(where, { ...scope, row, next: noRow }),\n })\n if (truth === true) return true\n if (isUnheld(truth)) unheld = Option.orElse(unheld, () => Option.some(truth))\n }\n return Option.getOrElse(unheld, (): Judged => false)\n}\n\nconst valueOf = (node: AnyExpr, scope: Scope): unknown => {\n switch (node._tag) {\n case 'Field':\n return scope.row.field(node.key)\n case 'Next':\n return scope.next.field(node.field.key)\n case 'Literal':\n return node.value\n case 'Input':\n return own(scope.input, node.key)\n case 'Call':\n return called(node, scope)\n case 'Viewer':\n case 'Now':\n return contextOf(node, scope)\n case 'Path': {\n const row = reached(scope.row, node.via)\n return row === null || isUnheld(row) ? row : row.field(node.field.key)\n }\n case 'ViewerPath': {\n // A visitor, or a viewer of another Entity, has no row to start from.\n const id = contextOf(node.viewer, scope)\n if (id === null) return null\n const start = scope.find(node.viewer.target(), id)\n const row = start === null || isUnheld(start) ? start : reached(start, node.via)\n return row === null || isUnheld(row) ? row : row.field(node.field.key)\n }\n default:\n return absurd(node)\n }\n}\n\n/**\n * What a run given one row could not decide without another: a path's or an\n * exists' row. It refuses rather than read the others as absent, which would\n * drop a row from a list on no evidence. `Judge` reads them from a holder.\n */\nexport class RowsMissingError extends QueryEvaluateError {\n constructor(reason: string) {\n super(`${reason}, which a run over one row cannot read; judge it with \\`Judge\\``)\n this.name = 'RowsMissingError'\n }\n}\n\n/** A two-valued run's answer: what it could not decide is refused. */\nconst settled = (judged: Judged): Truth => {\n if (isUnheld(judged)) throw new RowsMissingError(judged.reason)\n return judged\n}\n\n/**\n * What a call comes to, as a value (a predicate's truth as SQL's, unknown as\n * null). A defined operator's is what it means, as SQL compiles it; a\n * primitive one's is the table's implementation, or it is refused by name.\n */\nconst called = (call: CallExpr<unknown> | TestPredicate, scope: Scope): unknown => {\n const expansion: Option.Option<AnyExpr | Predicate> = call.expansion\n return Option.match(expansion, {\n onSome: body => sideOf(body, scope),\n onNone: () =>\n Option.match(scope.operators.get(call.operator), {\n onSome: run => ran(call, run, scope),\n onNone: () => {\n // An operator only the server runs: a holder cannot say what it comes to.\n if (scope.judging) {\n return new Unheld(\n `this holder does not run the operator \"${operatorName(call.operator)}\"`,\n )\n }\n throw new OperatorMissingError(call.operator, scope.operators)\n },\n }),\n })\n}\n\n/**\n * A call of a primitive operator run, its arguments worked out over the\n * scope. With an argument not held it is not run: null when a strict\n * operator is given a null besides, as SQL's would be, else not known.\n */\nconst ran = (\n call: CallExpr<unknown> | TestPredicate,\n run: MemoryImplementation['run'],\n scope: Scope,\n): unknown => {\n const values = call.args.map(arg => sideOf(arg, scope))\n const unheld = values.find(isUnheld)\n if (unheld !== undefined) {\n return call.operator.nulls === 'strict' && values.some(isNull) ? null : unheld\n }\n return runWith(\n call.operator,\n run,\n values,\n call.collation,\n call._tag === 'Test',\n scope.operators.checked,\n )\n}\n\n/**\n * A primitive operator run over values: strict about null and NUL before it\n * is asked, a throw it makes named as its own, and, in a checked table, its\n * answer held to its output schema (a predicate's null is its unknown).\n */\nconst runWith = (\n operator: OperatorDescriptor,\n run: MemoryImplementation['run'],\n values: ReadonlyArray<unknown>,\n collation: Option.Option<Collation>,\n predicate: boolean,\n checked: boolean,\n): unknown => {\n // NUL before null: SQL refuses text holding it where it is compiled, whatever\n // else the call is given, so a null beside it must not answer first.\n if (values.some(holdsNul)) {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" was given text holding a NUL character, which SQL text cannot hold portably`,\n )\n }\n if (operator.nulls === 'strict' && values.some(isNull)) return null\n let answer: unknown\n try {\n // A value never given (an input left out, a key the row lacks) is null to an\n // implementation that handles null, as SQL binds it.\n answer = run(\n values.map(value => (value === undefined ? null : value)),\n { collation },\n )\n } catch (error) {\n if (error instanceof QueryEvaluateError) throw error\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n const unknownTruth = predicate && answer === null\n if (checked && !unknownTruth && !Schema.is(Schema.toEncoded(operator.output))(answer)) {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" answered ${JSON.stringify(answer)}, which its output schema does not admit`,\n )\n }\n return answer\n}\n\n/**\n * A primitive operator over stored values, as a call of it is run: what a\n * computed assignment comes to (`Write.apply`). Refused, as a call is, when\n * `operators` does not implement it.\n */\nexport const applyOperator = (\n operator: OperatorDescriptor,\n values: ReadonlyArray<unknown>,\n options: {\n readonly collation: Option.Option<Collation>\n readonly operators: MemoryOperators\n },\n): unknown =>\n Option.match(options.operators.get(operator), {\n onNone: () => {\n throw new OperatorMissingError(operator, options.operators)\n },\n onSome: run =>\n runWith(\n operator,\n run,\n values,\n options.collation,\n SchemaAST.isBoolean(Schema.toEncoded(operator.output).ast),\n options.operators.checked,\n ),\n })\n\n/** A predicate operator's answer as a truth: null is unknown, anything but a boolean refused. */\nconst truthOf = (call: TestPredicate, answer: unknown): Judged => {\n if (isUnheld(answer)) return answer\n if (answer === null || answer === undefined) return 'unknown'\n if (typeof answer !== 'boolean') {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(call.operator)}\" answered ${JSON.stringify(answer)}, which is not a truth`,\n )\n }\n return answer\n}\n\n/** SQL's unknown: neither true nor false, and a row is kept only on true. */\ntype Truth = boolean | 'unknown'\n\nconst isNull = (value: unknown): boolean => value === null || value === undefined\n\nconst { foldAscii } = Collation\n\nconst NUL = String.fromCharCode(0)\n\n/**\n * Whether `value` is text holding a NUL, which Postgres text cannot hold and\n * SQLite compares only up to: no two interpreters agree on it.\n */\nconst holdsNul = (value: unknown): boolean => typeof value === 'string' && value.includes(NUL)\n\n/**\n * Whether `value` is NaN, which no two interpreters agree on either: SQLite\n * stores it as null, Postgres orders it after every number and equal to\n * itself, JavaScript equal to nothing. Refused where values compare or\n * order, as NUL is.\n */\nconst isNaNValue = (value: unknown): boolean => typeof value === 'number' && Number.isNaN(value)\n\nconst refusedNaN = (what: string): QueryEvaluateError =>\n new QueryEvaluateError(\n `${what} was given NaN, which SQLite stores as null and Postgres orders after every number`,\n )\n\n/** Refuses NaN given to a comparison (a literal or an input), before a null beside it answers. */\nconst refuseGivenNaN = (what: string, sides: ReadonlyArray<readonly [Operandish, unknown]>) => {\n if (\n sides.some(\n ([side, value]) =>\n !isPredicate(side) &&\n (side._tag === 'Literal' || side._tag === 'Input') &&\n isNaNValue(value),\n )\n ) {\n throw refusedNaN(what)\n }\n}\n\n/** A predicate used as a value is its own truth; anything else is its value. */\nconst sideOf = (node: Operandish, scope: Scope): unknown =>\n isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope)\n\n/**\n * What an operand comes to over no row: a call of literals and inputs, run by\n * `operators` (the kernel's when not given), a predicate as its truth with\n * unknown as null. How a conformance check asks an implementation one\n * question; refuses what `evaluate` refuses (an operator the table lacks,\n * text holding NUL).\n */\nexport const valueOfOperand = (\n node: Operandish,\n options: {\n readonly input?: Row | undefined\n readonly operators?: MemoryOperators | undefined\n readonly context?: ExprContext | undefined\n } = {},\n): unknown => {\n const value = sideOf(node, {\n row: noRow,\n input: options.input ?? {},\n next: noRow,\n operators: options.operators ?? Operators.kernel,\n judging: false,\n find: noRows,\n context: options.context,\n })\n if (isUnheld(value)) throw new RowsMissingError(value.reason)\n return value\n}\n\n/**\n * Refuses a value the query was given (a literal or an input) holding a NUL,\n * before any null beside it can answer: SQL refuses such a parameter where it\n * compiles, whatever the row holds. A NUL stored in a row is refused after,\n * as SQL meets it only beside a value that is not null.\n */\nconst refuseGivenNul = (\n message: string,\n sides: ReadonlyArray<readonly [Operandish, unknown]>,\n): void => {\n if (\n sides.some(\n ([side, value]) =>\n !isPredicate(side) && (side._tag === 'Literal' || side._tag === 'Input') && holdsNul(value),\n )\n ) {\n throw new QueryEvaluateError(message)\n }\n}\n\n/**\n * A predicate compared as a value. SQL's unknown is null there too, so an\n * unknown compared to anything stays unknown rather than becoming false.\n */\nconst truthValue = (truth: Judged): unknown => (truth === 'unknown' ? null : truth)\n\n/**\n * A predicate's truth, SQL's three values, or `Unheld` where it rests on what\n * the holder lacks. A null decides before anything unheld beside it, as it\n * decides SQL's answer whatever the other side holds; past that, what is not\n * held is not known, except where `and`'s false or `or`'s true settles it.\n */\nconst holds = (node: Predicate, scope: Scope): Judged => {\n switch (node._tag) {\n case 'Exists':\n return exists(node, scope)\n case 'Test':\n return truthOf(node, called(node, scope))\n case 'Eq': {\n const left = sideOf(node.left, scope)\n const right = sideOf(node.right, scope)\n // `null = anything` is unknown in SQL, including `null = null`. A row is\n // kept only when a comparison is true, so an unknown drops it either way;\n // saying so explicitly is what keeps this honest about three-valued logic\n // rather than accidentally right about it.\n const nul =\n 'an equality was given text holding a NUL character, which SQL text cannot hold portably'\n refuseGivenNul(nul, [\n [node.left, left],\n [node.right, right],\n ])\n refuseGivenNaN('an equality', [\n [node.left, left],\n [node.right, right],\n ])\n if (isNull(left) || isNull(right)) return 'unknown'\n if (isUnheld(left)) return left\n if (isUnheld(right)) return right\n if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul)\n if (isNaNValue(left) || isNaNValue(right)) throw refusedNaN('an equality')\n return left === right\n }\n case 'Null': {\n // The one comparison SQL never leaves unknown: asking whether a value\n // is absent always has an answer, unless the value is not held.\n const value = valueOf(node.operand, scope)\n return isUnheld(value) ? value : isNull(value) !== node.present\n }\n case 'Contains': {\n const value = valueOf(node.value, scope)\n const search = sideOf(node.search, scope)\n // `null like anything` is unknown, which is why an empty search is not\n // the same as no filter over a column that can be null.\n refuseGivenNul(\n 'a containment test was given text holding a NUL character, which SQL text cannot hold portably',\n [\n [node.search, search],\n [node.value, value],\n ],\n )\n if (isNull(value) || isNull(search)) return 'unknown'\n if (isUnheld(value)) return value\n if (isUnheld(search)) return search\n if (typeof value !== 'string' || typeof search !== 'string') {\n throw new QueryEvaluateError('a containment test was given something that is not text')\n }\n // Postgres text cannot hold NUL and SQLite's `like` stops at it, so no\n // two interpreters agree on such a value: refused rather than answered.\n if (holdsNul(value) || holdsNul(search)) {\n throw new QueryEvaluateError(\n 'a containment test was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n // Case-insensitive for ASCII letters only, because that is what\n // `Expr.contains` documents and what the compiled SQL folds both sides to.\n return foldAscii(value).includes(foldAscii(search))\n }\n case 'In': {\n const among = valueOf(node.among, scope)\n if (isUnheld(among)) return among\n if (!Array.isArray(among)) {\n throw new QueryEvaluateError('a membership test was given a list that is not a list')\n }\n // SQL's `in`: an empty list is false whatever the value, then a null\n // value is unknown, a match is true, and no match against a list\n // holding a null is unknown, since that null might have been it.\n if (among.length === 0) return false\n const value = valueOf(node.value, scope)\n if (holdsNul(value) || among.some(holdsNul)) {\n throw new QueryEvaluateError(\n 'a membership test was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n if (isNaNValue(value) || among.some(isNaNValue)) throw refusedNaN('a membership test')\n if (isNull(value)) return 'unknown'\n if (isUnheld(value)) return value\n if (among.some(each => each === value)) return true\n return among.some(isNull) ? 'unknown' : false\n }\n // Every operand is asked, with no short cut: SQL fixes no order, so one\n // that refuses its value (a NUL) refuses here whichever operand decided.\n case 'And': {\n const truths = node.operands.map(operand => holds(operand, scope))\n if (truths.includes(false)) return false\n // Unheld before SQL's unknown: with an unknown beside it, an unheld\n // operand could still make the whole false.\n const unheld = truths.find(isUnheld)\n if (unheld !== undefined) return unheld\n return truths.includes('unknown') ? 'unknown' : true\n }\n case 'Or': {\n const truths = node.operands.map(operand => holds(operand, scope))\n if (truths.includes(true)) return true\n const unheld = truths.find(isUnheld)\n if (unheld !== undefined) return unheld\n return truths.includes('unknown') ? 'unknown' : false\n }\n case 'Not': {\n const truth = holds(node.operand, scope)\n return truth === 'unknown' || isUnheld(truth) ? truth : !truth\n }\n case 'Compare': {\n const left = valueOf(node.left, scope)\n const right = valueOf(node.right, scope)\n const nul =\n 'a comparison was given text holding a NUL character, which SQL text cannot hold portably'\n refuseGivenNul(nul, [\n [node.left, left],\n [node.right, right],\n ])\n refuseGivenNaN('a comparison', [\n [node.left, left],\n [node.right, right],\n ])\n if (isNull(left) || isNull(right)) return 'unknown'\n if (isUnheld(left)) return left\n if (isUnheld(right)) return right\n if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul)\n if (isNaNValue(left) || isNaNValue(right)) throw refusedNaN('a comparison')\n // Numbers with numbers and text with text, as `orderBy` compares them,\n // so a comparison and an ordering never disagree about what is first.\n const kind = typeof left\n if (kind !== typeof right || (kind !== 'number' && kind !== 'string')) {\n throw new QueryEvaluateError('a comparison was given values that do not order together')\n }\n const order = compare(left, right, node.collation)\n return Match.value(node.operator).pipe(\n Match.when('lt', () => order < 0),\n Match.when('lte', () => order <= 0),\n Match.when('gt', () => order > 0),\n Match.when('gte', () => order >= 0),\n Match.exhaustive,\n )\n }\n }\n}\n\n/** What a predicate comes to: SQL's three values, of which a row is kept only on `true`. */\nexport type PredicateTruth = Truth\n\n/** What a predicate reads besides its input, asked once per node: nodes are frozen. */\nconst readsBeyond = new WeakMap<Predicate, { readonly field: boolean; readonly context: boolean }>()\n\n/**\n * A predicate's truth from the input (and the context, when given) alone,\n * when it reads no field; none when it reads one, or reads the context and\n * none is given. An interpreter that runs per request decides such a\n * predicate before it builds anything: `isNull($status)` is known before any\n * row is. Refuses what `evaluate` refuses (text holding a NUL).\n */\nexport const decided = (\n node: Predicate,\n input: Row,\n operators: MemoryOperators = Operators.kernel,\n context?: ExprContext,\n): Option.Option<PredicateTruth> => {\n let reads = readsBeyond.get(node)\n if (reads === undefined) {\n // A field after a write is a field too: nothing in the input alone decides it.\n const read = dependenciesOf(node)\n reads = {\n // So is a path's or an exists' row: each is read from a row.\n field: read.fields.length + read.next.length + read.reaches.length > 0,\n context: read.operations.some(operation => operation === 'viewer' || operation === 'now'),\n }\n readsBeyond.set(node, reads)\n }\n return reads.field || (reads.context && context === undefined)\n ? Option.none()\n : Option.some(\n settled(\n holds(node, {\n row: noRow,\n input,\n next: noRow,\n operators,\n judging: false,\n find: noRows,\n context,\n }),\n ),\n )\n}\n\n/** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */\nexport const truthOver = (\n node: Predicate,\n row: Row,\n input: Row = {},\n next: Row = {},\n operators: MemoryOperators = Operators.kernel,\n): PredicateTruth =>\n settled(\n holds(node, {\n row: flat(row),\n input,\n next: flat(next),\n operators,\n judging: false,\n find: noRows,\n }),\n )\n\n/**\n * What `Judge` comes to: known, or unknown because it rests on something the\n * holder lacks. A known predicate's truth is SQL's three values, its\n * `'unknown'` being SQL's null, which is decided: a row is not kept on it.\n */\nexport type Verdict<T = PredicateTruth> =\n | { readonly _tag: 'Known'; readonly truth: T }\n | { readonly _tag: 'Unknown'; readonly reason: string }\n\nconst known = <T>(truth: T): Verdict<T> => ({ _tag: 'Known', truth })\nconst unknownBecause = <T>(reason: string): Verdict<T> => ({ _tag: 'Unknown', reason })\n\n/** What a verdict reads over, besides the row judged. */\ninterface JudgeOptions {\n readonly input?: Row | undefined\n readonly operators?: MemoryOperators | undefined\n /** What `Expr.viewer` and `Expr.now` read; a predicate reading one refuses a run without it. */\n readonly context?: ExprContext | undefined\n /**\n * The holder's rows, where a path from the viewer starts. Without them the\n * viewer's row is not held, and such a path is unknown.\n */\n readonly rows?: HeldRows | undefined\n}\n\n/** How a judgement reaches a row by its id: through the holder's rows, when it was given them. */\nconst finder =\n (rows: HeldRows | undefined) =>\n (entity: AnyEntity, id: unknown): View | null | Unheld =>\n rows === undefined\n ? noRows(entity)\n : Held.match<Option.Option<HeldRow>, View | null | Unheld>(rows.find(entity, id), {\n onHeld: found => Option.match(found, { onNone: () => null, onSome: viewOf }),\n onUnheld: reason => new Unheld(reason),\n })\n\n/**\n * The reference interpreter over what a holder has (`HeldRow`), three-valued:\n * where an answer rests on a row or field the holder lacks or may not see, or\n * on an operator only the server runs, it is unknown, and is never guessed.\n * Where it is known, it is what SQL answers over the same rows: the law the\n * conformance suite checks.\n */\nexport const Judge = {\n /** A predicate over one held row, and, for an invariant, the row a write would leave. */\n predicate: (\n predicate: Predicate,\n row: HeldRow,\n options: JudgeOptions & { readonly next?: HeldRow | undefined } = {},\n ): Verdict => {\n const judged = holds(predicate, {\n row: viewOf(row),\n input: options.input ?? {},\n next: options.next === undefined ? noRow : viewOf(options.next),\n operators: options.operators ?? Operators.kernel,\n judging: true,\n context: options.context,\n find: finder(options.rows),\n })\n return isUnheld(judged) ? unknownBecause(judged.reason) : known(judged)\n },\n\n /**\n * Whether a held row is in a query's result: known when every predicate\n * holds (in) or one fails or is null (out), unknown otherwise. `serverOnly`\n * names a filter the server conjoins that this holder does not run (a Read\n * rule, a source's own `where`): a row the body admits is then unknown, and\n * one it refuses is still out. Refuses, as `evaluate` does, a given value\n * holding a NUL.\n */\n query: (\n body: AnyQuery,\n input: Row,\n row: HeldRow,\n options: Omit<JudgeOptions, 'input'> & { readonly serverOnly?: string | undefined } = {},\n ): Verdict<boolean> => {\n if (givenUnportable(body.where, Query.dependencies(body).inputs, input)) {\n throw new QueryEvaluateError(\n `query \"${body.entity.name}\" was given text holding a NUL character, or NaN, which no two backends agree on`,\n )\n }\n const scope: Scope = {\n row: viewOf(row),\n input,\n next: noRow,\n operators: options.operators ?? Operators.kernel,\n judging: true,\n context: options.context,\n find: finder(options.rows),\n }\n // Every predicate is asked, as `evaluate` asks them: one may refuse its value.\n const truths = body.where.map(each => holds(each, scope))\n if (truths.some(truth => truth === false || truth === 'unknown')) return known(false)\n const unheld = truths.find(isUnheld)\n if (unheld !== undefined) return unknownBecause(unheld.reason)\n return options.serverOnly === undefined\n ? known(true)\n : unknownBecause(`the server also filters by ${options.serverOnly}`)\n },\n\n /**\n * What a conjunction fixes by field: each `eq` of a field and a literal, an\n * input or the viewer, by the field's key, and whether that is all it says\n * (`whole`), so every row holding those values satisfies it. A holder holding\n * every row a `whole` list's body fixes this way holds every row an exists\n * whose filter fixes the same values counts.\n */\n pins: (\n predicates: ReadonlyArray<Predicate>,\n options: { readonly input?: Row | undefined; readonly context?: ExprContext | undefined } = {},\n ): Pins => pinsOf(predicates, options.input ?? {}, options.context),\n\n match: <T, A>(\n verdict: Verdict<T>,\n cases: { readonly onKnown: (truth: T) => A; readonly onUnknown: (reason: string) => A },\n ): A =>\n verdict._tag === 'Known' ? cases.onKnown(verdict.truth) : cases.onUnknown(verdict.reason),\n}\n\n/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */\nconst matches = (\n body: AnyQuery,\n row: Row,\n input: Row,\n operators: MemoryOperators,\n context: ExprContext | undefined,\n): boolean =>\n // Every predicate is asked, as `and` asks every operand: SQL fixes no order, so\n // one that refuses its value refuses whichever comes first in the list.\n body.where\n .map(node =>\n settled(\n holds(node, {\n row: flat(row),\n input,\n next: noRow,\n operators,\n judging: false,\n find: noRows,\n context,\n }),\n ),\n )\n .every(truth => truth === true)\n\n/** The kinds of value this interpreter orders by; every key of one term must share one. */\nconst comparable = new Set(['string', 'number', 'boolean'])\n\n/**\n * Text by code point, as SQLite's `BINARY` and Postgres's `\"C\"` compare it.\n * JavaScript's `<` compares UTF-16 code units, which puts a character past\n * U+FFFF (two units, the first from U+D800) before U+E000 to U+FFFF, where\n * every byte-ordered backend puts it after.\n */\nconst byCodePoint = (left: string, right: string): number => {\n let i = 0\n let j = 0\n while (i < left.length && j < right.length) {\n const a = left.codePointAt(i)!\n const b = right.codePointAt(j)!\n if (a !== b) return a < b ? -1 : 1\n i += a > 0xffff ? 2 : 1\n j += b > 0xffff ? 2 : 1\n }\n return i < left.length ? 1 : j < right.length ? -1 : 0\n}\n\n/** Two keys of one term, text by its collation (code point when none is declared). */\nconst compare = (left: unknown, right: unknown, collation: Option.Option<Collation>): number => {\n if (typeof left === 'string' && typeof right === 'string') {\n const fold = Option.exists(collation, declared => declared._tag === 'AsciiFold')\n return fold ? byCodePoint(foldAscii(left), foldAscii(right)) : byCodePoint(left, right)\n }\n if (typeof left === 'boolean' && typeof right === 'boolean') {\n return Number(left) - Number(right)\n }\n return (left as number) - (right as number)\n}\n\n/** What an order's keys are worked out with: a call may read the input, and runs by the table. */\ninterface OrderScope {\n readonly input: Row\n readonly operators: MemoryOperators\n readonly context?: ExprContext | undefined\n}\n\n/** Each term's key for one row: a field's value, or what a call comes to over the row. */\nconst keysOf = (row: Row, terms: ReadonlyArray<OrderTerm>, scope: OrderScope) =>\n terms.map(term => {\n const key = valueOf(term.expr, {\n row: flat(row),\n input: scope.input,\n next: noRow,\n operators: scope.operators,\n judging: false,\n find: noRows,\n context: scope.context,\n })\n // One row's NaN would make every comparison with it NaN, and the sort of\n // every other row with it: refused for that row.\n if (isNaNValue(key)) throw refusedNaN(`an order by ${Expr.show(term.expr)}`)\n return key\n })\n\n/**\n * Refuses an ordering this interpreter will not answer for, before sorting, so\n * the refusal names the first offending row in row order rather than whichever\n * pair the engine's sort happened to compare first. Every term is checked over\n * every row's keys: a key whose kind differs from the first present one's. A\n * null key is not refused; the term says where it goes.\n */\nconst checkOrder = (\n keys: ReadonlyArray<ReadonlyArray<unknown>>,\n terms: ReadonlyArray<OrderTerm>,\n query: string,\n) =>\n terms.forEach((term, index) => {\n if (term.expr._tag !== 'Field' && term.expr._tag !== 'Call') {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by something that is neither a field nor a call`,\n )\n }\n if (Option.exists(term.collation, declared => declared._tag === 'Locale')) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders ${Expr.show(term.expr)} by a backend's locale collation, which only that backend has`,\n )\n }\n let first: string | undefined\n for (const row of keys) {\n const value = row[index]\n if (isNull(value)) continue\n const kind = typeof value\n first ??= kind\n if (kind !== first || !comparable.has(kind)) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by values this interpreter cannot compare (${first} and ${kind})`,\n )\n }\n }\n })\n\n/** Two rows' keys by checked terms: negative when `left` sorts first. */\nconst byTerms = (\n terms: ReadonlyArray<OrderTerm>,\n left: ReadonlyArray<unknown>,\n right: ReadonlyArray<unknown>,\n): number => {\n for (const [index, term] of terms.entries()) {\n const absentLeft = isNull(left[index])\n const absentRight = isNull(right[index])\n // Where a row without a value goes is the term's to say, whichever the\n // direction; two such rows tie, for the next term.\n if (absentLeft || absentRight) {\n if (absentLeft && absentRight) continue\n return absentLeft === (term.nulls === 'first') ? -1 : 1\n }\n const sign = compare(left[index], right[index], term.collation)\n if (sign !== 0) return term.direction === 'asc' ? sign : -sign\n }\n return 0\n}\n\nconst ordered = (\n rows: ReadonlyArray<Row>,\n terms: ReadonlyArray<OrderTerm>,\n query: string,\n scope: OrderScope,\n) => {\n // Keys are worked out and checked however few the rows, so a term refused over\n // one row is refused as it is over many, as `evaluateEach` refuses it.\n if (terms.length === 0) return [...rows]\n // Each row's keys worked out once, not once per comparison: a call may be dear.\n const keyed = rows.map(row => ({ row, keys: keysOf(row, terms, scope) }))\n checkOrder(\n keyed.map(({ keys }) => keys),\n terms,\n query,\n )\n return keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row)\n}\n\n/**\n * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),\n * as `evaluate` sorts: negative when it comes first. A call among them runs\n * over each row with `input` and `operators` (the kernel's when not given).\n * Refuses what `evaluate` refuses, for these two rows: a term over neither a\n * field nor a call, a locale collation, keys of different kinds, or an\n * operator the table lacks. For a client placing one row among others it\n * holds.\n */\nexport const compareRows = (\n terms: ReadonlyArray<OrderTerm>,\n left: Row,\n right: Row,\n query: string,\n options: {\n readonly input?: Row | undefined\n readonly operators?: MemoryOperators | undefined\n readonly context?: ExprContext | undefined\n } = {},\n): number => {\n const scope = {\n input: options.input ?? {},\n operators: options.operators ?? Operators.kernel,\n context: options.context,\n }\n const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)] as const\n checkOrder(keys, terms, query)\n return byTerms(terms, keys[0], keys[1])\n}\n\n/**\n * The operations this interpreter runs. It is the reference, so this is the\n * whole kernel — but it is declared rather than assumed, because an\n * interpreter that gains an operator and forgets to say so is exactly what\n * `Query.unsupported` exists to catch.\n */\nexport const supported: ReadonlyArray<Operation> = [\n 'eq',\n 'isNull',\n 'isNotNull',\n 'contains',\n 'in',\n 'and',\n 'or',\n 'not',\n 'compare',\n 'viewer',\n 'now',\n]\n\n/**\n * Refuses a body needing an operation this interpreter does not run, rather\n * than skipping it and answering a different question. Called by `evaluate`;\n * call it directly to check a body once instead of on every run.\n */\nexport const assertSupported = (\n body: AnyQuery,\n operators: MemoryOperators = Operators.kernel,\n): void => {\n const missing = Query.unsupported(body, supported, operators)\n if (missing.length > 0) {\n throw new QueryEvaluateError(\n `this interpreter does not run ${missing.join(', ')}, which query \"${body.entity.name}\" needs`,\n )\n }\n}\n\n/**\n * The rows the body matches, in the order it asks for. Pure: it reads the rows\n * it is given and nothing else.\n *\n * `input` holds the values this run was given, by the keys the body's\n * placeholders were built with — the same record the query would be called\n * with anywhere else.\n */\nexport const evaluate = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n options: {\n readonly operators?: MemoryOperators | undefined\n /** What `Expr.viewer` and `Expr.now` read; a body reading one refuses a run without it. */\n readonly context?: ExprContext | undefined\n } = {},\n): ReadonlyArray<Row> => {\n const operators = options.operators ?? Operators.kernel\n const { context } = options\n assertSupported(body, operators)\n return ordered(\n rows.filter(row => matches(body, row, input, operators, context)),\n Query.orderFor(body, input),\n body.entity.name,\n { input, operators, context },\n )\n}\n\n/** What `evaluateEach` made of each row: those it matched, in order, and those it refused. */\nexport interface Evaluated {\n readonly matched: ReadonlyArray<Row>\n readonly refused: ReadonlyArray<Row>\n}\n\n/**\n * As `evaluate`, with each row judged alone: a row whose own values are\n * refused (text holding a NUL, a value an operator fails on) is set aside in\n * `refused` and the others are still answered. A client judging the rows it\n * holds wants this, since one bad stored row says nothing about the rest.\n *\n * What no single row causes still refuses the run: an operation or operator\n * the table lacks, an order by a locale collation, an input the body reads\n * holding a NUL (every row would refuse, and no row is the cause), and order\n * keys of different kinds across rows.\n */\nexport const evaluateEach = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n options: {\n readonly operators?: MemoryOperators | undefined\n /** As `evaluate`'s. */\n readonly context?: ExprContext | undefined\n } = {},\n): Evaluated => {\n const operators = options.operators ?? Operators.kernel\n const { context } = options\n assertSupported(body, operators)\n const terms = Query.orderFor(body, input)\n const read = [...body.where, ...terms.map(term => term.expr)]\n const scope = { input, operators, context }\n const keyed: Array<{ readonly row: Row; readonly keys: ReadonlyArray<unknown> }> = []\n const refused: Row[] = []\n for (const row of rows) {\n try {\n if (matches(body, row, input, operators, context))\n keyed.push({ row, keys: keysOf(row, terms, scope) })\n } catch (error) {\n if (\n !(error instanceof QueryEvaluateError) ||\n error instanceof ContextMissingError ||\n // An alternative of `Order.chosen` this input did not choose reads nothing.\n givenUnportable(read, dependenciesOf(...read).inputs, input)\n )\n throw error\n refused.push(row)\n }\n }\n checkOrder(\n keyed.map(({ keys }) => keys),\n terms,\n body.entity.name,\n )\n return {\n matched: keyed\n .sort((left, right) => byTerms(terms, left.keys, right.keys))\n .map(({ row }) => row),\n refused,\n }\n}\n\n/**\n * Whether a constant of `read`, or a value of `input` that `inputs` name, is\n * one no two backends agree on (text holding a NUL, NaN), or a list holding\n * one: every row would refuse.\n */\nconst givenUnportable = (\n read: ReadonlyArray<AnyExpr | Predicate>,\n inputs: ReadonlyArray<string>,\n input: Row,\n): boolean =>\n Expr.givesUnportable(...read) ||\n inputs.some(key => {\n const value = input[key]\n const unportable = (each: unknown) => holdsNul(each) || isNaNValue(each)\n return Array.isArray(value) ? value.some(unportable) : unportable(value)\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,SAAiB;EAC3B,MAAM,oBAAoB,SAAS;EACnC,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,uBAAb,cAA0C,mBAAmB;CAC3D;;CAEA;;CAEA,YAAY,UAA8B,YAA2B,aAAa;EAChF,MAAM,+CAA+C,YAAY,UAAU,SAAS,EAAE,EAAE;EACxF,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,QAAQ,aAAa,QAAQ;CACpC;AACF;;AAGA,MAAM,gBAAgB,aACpB,SAAS,YAAY,IAAI,SAAS,KAAK,GAAG,SAAS,GAAG,GAAG,SAAS;;AAwBpE,MAAM,UAAU,WACd,IAAI,OAAO,kCAAkC,OAAO,KAAK,cAAc;;;;;AAMzE,IAAa,sBAAb,cAAyC,mBAAmB;CAC1D,YAAY,MAA8C,KAAa;EACrE,MAAM,kBAAkB,KAAK,KAAK,IAAI,EAAE,QAAQ,KAAK;EACrD,KAAK,OAAO;CACd;AACF;AAEA,MAAM,aAAa,MAA8C,UAA0B;CACzF,IAAI,MAAM,YAAY,KAAA,GACpB,MAAM,IAAI,oBAAoB,MAAM,sCAAsC;CAE5E,OAAO,OAAO,eACZ,aAAa,MAAM,MAAM,OAAO,SAC1B,IAAI,oBAAoB,MAAM,wCAAwC,CAC9E;AACF;;;;;;AAOA,IAAM,SAAN,MAAa;CACU;CAArB,YAAY,QAAyB;EAAhB,KAAA,SAAA;CAAiB;AACxC;AAEA,MAAM,YAAY,UAAoC,iBAAiB;;;;;AAuBvE,MAAM,QAAQ,SAAo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AAO,KAAK;EAAE,CAAC;CACvD,SAAS,OAAO;EACd,IACE,EAAE,iBAAiB,uBACnB,iBAAiB,uBAEjB,gBAAgB,MAAM,eAAe,GAAG,IAAI,CAAC,CAAC,QAAQ,KAAK,GAE3D,MAAM;EACR,QAAQ,KAAK,GAAG;CAClB;CAEF,WACE,MAAM,KAAK,EAAE,WAAW,IAAI,GAC5B,OACA,KAAK,OAAO,IACd;CACA,OAAO;EACL,SAAS,MACN,MAAM,MAAM,UAAU,QAAQ,OAAO,KAAK,MAAM,MAAM,IAAI,CAAC,CAAC,CAC5D,KAAK,EAAE,UAAU,GAAG;EACvB;CACF;AACF;;;;;;AAOA,MAAM,mBACJ,MACA,QACA,UAEA,KAAK,gBAAgB,GAAG,IAAI,KAC5B,OAAO,MAAK,QAAO;CACjB,MAAM,QAAQ,MAAM;CACpB,MAAM,cAAc,SAAkB,SAAS,IAAI,KAAK,WAAW,IAAI;CACvE,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK,UAAU,IAAI,WAAW,KAAK;AACzE,CAAC"}
1
+ {"version":3,"file":"evaluate.js","names":[],"sources":["../src/evaluate.ts"],"sourcesContent":["/**\n * The reference interpreter: a query body run over rows already in memory.\n *\n * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body\n * directly, which is what makes \"source-neutral\" a fact rather than a claim —\n * the two are checked against each other over a real database, and a body that\n * means one thing here and another there is a bug in one of them.\n *\n * It is also the interpreter to reach for when there is no database: a test\n * that wants rows, a server assembling a page from values it already holds, or\n * a client judging rows it already has.\n *\n * It lives in `foldkit-entity` because it is the **reference semantics** of the\n * IR this package owns — what §6.0.1 means operationally rather than in prose —\n * and a specification's reference implementation belongs with the\n * specification. The rule that keeps it here: **it may depend on the IR and\n * nothing else.** The moment it wants a Remote concept it has moved to the\n * wrong place and should leave.\n *\n * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,\n * because SQL is what the other interpreter runs. The important case is null:\n * `null = null` is unknown in SQL and a row is not matched by it, where\n * JavaScript would happily call the two equal.\n */\nimport { Match, Option, Schema, SchemaAST } from 'effect'\nimport { absurd } from 'effect/Function'\nimport { Collation } from './collation.js'\nimport { Expr, Query, dependenciesOf, isPredicate, missingName, noOperators } from './expr.js'\nimport type {\n AnyExpr,\n AnyQuery,\n CallExpr,\n ExistsPredicate,\n OneRelation,\n Operandish,\n Operation,\n OperatorDescriptor,\n OperatorTable,\n OrderTerm,\n Predicate,\n TestPredicate,\n} from './expr.js'\nimport { Held, type HeldRow, type HeldRows, type Pinned } from './held.js'\nimport type { AnyEntity } from './index.js'\nimport { kernelOperators } from './memoryTable.js'\nimport type { MemoryImplementation, MemoryOperators } from './operators.js'\nimport { contextValue, type ExprContext, type NowExpr, type ViewerExpr } from './context.js'\nimport { own } from './record.js'\n\n/** A row as this interpreter reads one: values by field key. */\nexport type Row = Readonly<Record<string, unknown>>\n\nexport class QueryEvaluateError extends Error {\n constructor(message: string) {\n super(`[foldkit-entity] ${message}`)\n this.name = 'QueryEvaluateError'\n }\n}\n\n/**\n * A call of a primitive operator the table does not implement. Its own class,\n * because a form judging an invariant reads it as a judgement it cannot make\n * (`Undecided`), not as a failure.\n */\nexport class OperatorMissingError extends QueryEvaluateError {\n readonly operator: OperatorDescriptor\n /** The operator by its id, and its version past the first. */\n readonly named: string\n /** `operators`, the table that lacks it, names the versions of it that it does hold. */\n constructor(operator: OperatorDescriptor, operators: OperatorTable = noOperators) {\n super(`this interpreter does not run the operator \"${missingName(operator, operators)}\"`)\n this.name = 'OperatorMissingError'\n this.operator = operator\n this.named = operatorName(operator)\n }\n}\n\n/** An operator by its id, and its version when that is not the first. */\nconst operatorName = (operator: OperatorDescriptor): string =>\n operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`\n\n/**\n * What a predicate is judged over: the row, the input it was given, and the row\n * a write would leave, which an invariant reads (`Next`).\n */\ninterface Scope {\n readonly row: View\n readonly input: Row\n readonly next: View\n /** How a primitive operator is run. */\n readonly operators: MemoryOperators\n /**\n * Whether this is `Judge`, for which an operator the table lacks is one more\n * thing it does not know; elsewhere it refuses the run.\n */\n readonly judging: boolean\n /** What `Expr.viewer` and `Expr.now` read; a run given none refuses them. */\n readonly context?: ExprContext | undefined\n /** The row of `entity` with this id, where a path from the viewer starts. */\n readonly find: (entity: AnyEntity, id: unknown) => View | null | Unheld\n}\n\n/** A run given one row: the viewer's row is another, which it does not have. */\nconst noRows = (entity: AnyEntity): Unheld =>\n new Unheld(`a path from the viewer reads a ${entity.name}, another row`)\n\n/**\n * A run that reads `Expr.viewer` or `Expr.now` and was given no context. No\n * row causes it, so `evaluateEach` refuses the run rather than each row.\n */\nexport class ContextMissingError extends QueryEvaluateError {\n constructor(term: ViewerExpr<unknown> | NowExpr<unknown>, why: string) {\n super(`this run reads ${Expr.show(term)}, but ${why}`)\n this.name = 'ContextMissingError'\n }\n}\n\nconst contextOf = (node: ViewerExpr<unknown> | NowExpr<unknown>, scope: Scope): unknown => {\n if (scope.context === undefined) {\n throw new ContextMissingError(node, 'was given no context to read it from')\n }\n return Option.getOrThrowWith(\n contextValue(node, scope.context),\n () => new ContextMissingError(node, 'its context has no reading of the time'),\n )\n}\n\n/**\n * What the interpreter does not know: a value, or a truth, that rests on\n * something the holder does not have. Never a value a row holds, which is\n * what lets one sit among values. SQL has no such thing; its unknown is null.\n */\nclass Unheld {\n constructor(readonly reason: string) {}\n}\n\nconst isUnheld = (value: unknown): value is Unheld => value instanceof Unheld\n\n/** A truth, or that it rests on something not held: what `holds` comes to. */\ntype Judged = Truth | Unheld\n\n/** A row as the interpreter reads it, whoever holds it: values may be `Unheld`. */\ninterface View {\n readonly field: (key: string) => unknown\n /** The row a `one` relation points at; null for none. */\n readonly follow: (relation: OneRelation) => View | null | Unheld\n readonly pointing: (\n relation: OneRelation,\n pinned: Pinned,\n ) => {\n readonly rows: ReadonlyArray<View>\n readonly missing: Option.Option<string>\n }\n}\n\n/**\n * One plain row, all a two-valued run is given: a key it lacks is null, as\n * SQL binds a missing value, and no other row can be reached from it.\n */\nconst flat = (row: Row): View => ({\n field: key => own(row, key),\n follow: relation => new Unheld(`${relation.owner.name}.${relation.key} leads to another row`),\n pointing: relation => ({\n rows: [],\n missing: Option.some(`${relation.owner.name}.${relation.key} is read from other rows`),\n }),\n})\n\n/** A holder's row as the interpreter reads it. */\nconst viewOf = (row: HeldRow): View => ({\n field: key =>\n Held.match(row.field(key), { onHeld: value => value, onUnheld: reason => new Unheld(reason) }),\n follow: relation =>\n Held.match<Option.Option<HeldRow>, View | null | Unheld>(row.follow(relation), {\n onHeld: target => Option.match(target, { onNone: () => null, onSome: viewOf }),\n onUnheld: reason => new Unheld(reason),\n }),\n pointing: (relation, pinned) => {\n const { rows, missing } = row.pointing(relation, pinned)\n return { rows: rows.map(viewOf), missing }\n },\n})\n\n/** A run that is given no row: whatever it reads of one, it lacks. */\nconst noRow: View = flat({})\n\n/**\n * The row `via` reaches from `from`: null when a link is null or reaches a row\n * the holder knows is not there.\n */\nconst reached = (from: View, via: ReadonlyArray<OneRelation>): View | null | Unheld => {\n let at: View | null | Unheld = from\n for (const relation of via) {\n if (at === null || isUnheld(at)) return at\n at = at.follow(relation)\n }\n return at\n}\n\n/** What a conjunction fixes by field, and whether that is all it says (`Judge.pins`). */\nexport interface Pins {\n readonly pins: Pinned\n readonly whole: boolean\n}\n\n/** A value two `eq`s agree on exactly, on both sides of the wire: never null, NaN or a structure. */\nconst pinnable = (value: unknown): boolean =>\n typeof value === 'string' ||\n typeof value === 'boolean' ||\n typeof value === 'bigint' ||\n (typeof value === 'number' && !Number.isNaN(value))\n\n/** An `eq` of a field of the row and something else, the field first. */\nconst fieldAndSide = Match.type<Predicate>().pipe(\n Match.tag(\n 'Eq',\n ({ left, right }): Option.Option<readonly [{ readonly key: string }, Operandish]> =>\n Option.orElse(\n Option.map(fieldOf(left), field => [field, right] as const),\n () => Option.map(fieldOf(right), field => [field, left] as const),\n ),\n ),\n Match.orElse((): Option.Option<readonly [{ readonly key: string }, Operandish]> => Option.none()),\n)\n\nconst pinsOf = (\n predicates: ReadonlyArray<Predicate>,\n input: Row,\n context: ExprContext | undefined,\n): Pins => {\n const pins = new Map<string, unknown>()\n let whole = true\n const given = (node: Operandish): Option.Option<unknown> =>\n Match.value(node).pipe(\n Match.tags({\n Literal: ({ value }) => Option.some<unknown>(value),\n Input: ({ key }) => Option.some<unknown>(own(input, key)),\n Viewer: viewer => (context === undefined ? Option.none() : contextValue(viewer, context)),\n }),\n Match.orElse(() => Option.none()),\n )\n for (const predicate of predicates) {\n const pin = Option.flatMap(fieldAndSide(predicate), ([field, side]) =>\n Option.map(Option.filter(given(side), pinnable), value => [field.key, value] as const),\n )\n if (Option.isNone(pin)) {\n whole = false\n continue\n }\n const [key, value] = pin.value\n if (pins.has(key) && pins.get(key) !== value) whole = false\n pins.set(key, value)\n }\n return { pins, whole }\n}\n\nconst fieldOf = Match.type<Operandish>().pipe(\n Match.tag('Field', field => Option.some(field)),\n Match.orElse((): Option.Option<{ readonly key: string }> => Option.none()),\n)\n\n/** A filter's conjuncts; built once, since `exists` asks for every row judged. */\nconst operandsOf = Match.type<Predicate>().pipe(\n Match.tag('And', ({ operands }): ReadonlyArray<Predicate> => operands),\n Match.orElse(single => [single]),\n)\n\n/**\n * Whether some row pointing at the one `via` reaches holds the filter: true\n * as soon as a held one does, false only when every one is held and none\n * does. SQL's exists is never null; reached through a path that reaches no\n * row, it is, as the path's field would be.\n */\nconst exists = (node: ExistsPredicate, scope: Scope): Judged => {\n const anchor = reached(scope.row, node.via)\n if (anchor === null) return 'unknown'\n if (isUnheld(anchor)) return anchor\n const pinned = Option.match(node.where, {\n onNone: (): Pinned => new Map(),\n onSome: where => pinsOf(operandsOf(where), scope.input, scope.context).pins,\n })\n const { rows, missing } = anchor.pointing(node.relation, pinned)\n let unheld = Option.map(missing, reason => new Unheld(reason))\n for (const row of rows) {\n const truth = Option.match(node.where, {\n onNone: (): Judged => true,\n onSome: where => holds(where, { ...scope, row, next: noRow }),\n })\n if (truth === true) return true\n if (isUnheld(truth)) unheld = Option.orElse(unheld, () => Option.some(truth))\n }\n return Option.getOrElse(unheld, (): Judged => false)\n}\n\nconst valueOf = (node: AnyExpr, scope: Scope): unknown => {\n switch (node._tag) {\n case 'Field':\n return scope.row.field(node.key)\n case 'Next':\n return scope.next.field(node.field.key)\n case 'Literal':\n return node.value\n case 'Input':\n return own(scope.input, node.key)\n case 'Call':\n return called(node, scope)\n case 'Viewer':\n case 'Now':\n return contextOf(node, scope)\n case 'Path': {\n const row = reached(scope.row, node.via)\n return row === null || isUnheld(row) ? row : row.field(node.field.key)\n }\n case 'ViewerPath': {\n // A visitor, or a viewer of another Entity, has no row to start from.\n const id = contextOf(node.viewer, scope)\n if (id === null) return null\n const start = scope.find(node.viewer.target(), id)\n const row = start === null || isUnheld(start) ? start : reached(start, node.via)\n return row === null || isUnheld(row) ? row : row.field(node.field.key)\n }\n default:\n return absurd(node)\n }\n}\n\n/**\n * What a run given one row could not decide without another: a path's or an\n * exists' row. It refuses rather than read the others as absent, which would\n * drop a row from a list on no evidence. `Judge` reads them from a holder.\n */\nexport class RowsMissingError extends QueryEvaluateError {\n constructor(reason: string) {\n super(`${reason}, which a run over one row cannot read; judge it with \\`Judge\\``)\n this.name = 'RowsMissingError'\n }\n}\n\n/** A two-valued run's answer: what it could not decide is refused. */\nconst settled = (judged: Judged): Truth => {\n if (isUnheld(judged)) throw new RowsMissingError(judged.reason)\n return judged\n}\n\n/**\n * What a call comes to, as a value (a predicate's truth as SQL's, unknown as\n * null). A defined operator's is what it means, as SQL compiles it; a\n * primitive one's is the table's implementation, or it is refused by name.\n */\nconst called = (call: CallExpr<unknown> | TestPredicate, scope: Scope): unknown => {\n const expansion: Option.Option<AnyExpr | Predicate> = call.expansion\n return Option.match(expansion, {\n onSome: body => sideOf(body, scope),\n onNone: () =>\n Option.match(scope.operators.get(call.operator), {\n onSome: run => ran(call, run, scope),\n onNone: () => {\n // An operator only the server runs: a holder cannot say what it comes to.\n if (scope.judging) {\n return new Unheld(\n `this holder does not run the operator \"${operatorName(call.operator)}\"`,\n )\n }\n throw new OperatorMissingError(call.operator, scope.operators)\n },\n }),\n })\n}\n\n/**\n * A call of a primitive operator run, its arguments worked out over the\n * scope. With an argument not held it is not run: null when a strict\n * operator is given a null besides, as SQL's would be, else not known.\n */\nconst ran = (\n call: CallExpr<unknown> | TestPredicate,\n run: MemoryImplementation['run'],\n scope: Scope,\n): unknown => {\n const values = call.args.map(arg => sideOf(arg, scope))\n const unheld = values.find(isUnheld)\n if (unheld !== undefined) {\n return call.operator.nulls === 'strict' && values.some(isNull) ? null : unheld\n }\n return runWith(\n call.operator,\n run,\n values,\n call.collation,\n call._tag === 'Test',\n scope.operators.checked,\n )\n}\n\n/**\n * A primitive operator run over values: strict about null and NUL before it\n * is asked, a throw it makes named as its own, and, in a checked table, its\n * answer held to its output schema (a predicate's null is its unknown).\n */\nconst runWith = (\n operator: OperatorDescriptor,\n run: MemoryImplementation['run'],\n values: ReadonlyArray<unknown>,\n collation: Option.Option<Collation>,\n predicate: boolean,\n checked: boolean,\n): unknown => {\n // NUL before null: SQL refuses text holding it where it is compiled, whatever\n // else the call is given, so a null beside it must not answer first.\n if (values.some(holdsNul)) {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" was given text holding a NUL character, which SQL text cannot hold portably`,\n )\n }\n if (operator.nulls === 'strict' && values.some(isNull)) return null\n let answer: unknown\n try {\n // A value never given (an input left out, a key the row lacks) is null to an\n // implementation that handles null, as SQL binds it.\n answer = run(\n values.map(value => (value === undefined ? null : value)),\n { collation },\n )\n } catch (error) {\n if (error instanceof QueryEvaluateError) throw error\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n const unknownTruth = predicate && answer === null\n if (checked && !unknownTruth && !Schema.is(Schema.toEncoded(operator.output))(answer)) {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" answered ${JSON.stringify(answer)}, which its output schema does not admit`,\n )\n }\n return answer\n}\n\n/**\n * A primitive operator over stored values, as a call of it is run: what a\n * computed assignment comes to (`Write.apply`). Refused, as a call is, when\n * `operators` does not implement it.\n */\nexport const applyOperator = (\n operator: OperatorDescriptor,\n values: ReadonlyArray<unknown>,\n options: {\n readonly collation: Option.Option<Collation>\n readonly operators: MemoryOperators\n },\n): unknown =>\n Option.match(options.operators.get(operator), {\n onNone: () => {\n throw new OperatorMissingError(operator, options.operators)\n },\n onSome: run =>\n runWith(\n operator,\n run,\n values,\n options.collation,\n SchemaAST.isBoolean(Schema.toEncoded(operator.output).ast),\n options.operators.checked,\n ),\n })\n\n/** A predicate operator's answer as a truth: null is unknown, anything but a boolean refused. */\nconst truthOf = (call: TestPredicate, answer: unknown): Judged => {\n if (isUnheld(answer)) return answer\n if (answer === null || answer === undefined) return 'unknown'\n if (typeof answer !== 'boolean') {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(call.operator)}\" answered ${JSON.stringify(answer)}, which is not a truth`,\n )\n }\n return answer\n}\n\n/** SQL's unknown: neither true nor false, and a row is kept only on true. */\ntype Truth = boolean | 'unknown'\n\nconst isNull = (value: unknown): boolean => value === null || value === undefined\n\nconst { foldAscii } = Collation\n\nconst NUL = String.fromCharCode(0)\n\n/**\n * Whether `value` is text holding a NUL, which Postgres text cannot hold and\n * SQLite compares only up to: no two interpreters agree on it.\n */\nconst holdsNul = (value: unknown): boolean => typeof value === 'string' && value.includes(NUL)\n\n/**\n * Whether `value` is NaN, which no two interpreters agree on either: SQLite\n * stores it as null, Postgres orders it after every number and equal to\n * itself, JavaScript equal to nothing. Refused where values compare or\n * order, as NUL is.\n */\nconst isNaNValue = (value: unknown): boolean => typeof value === 'number' && Number.isNaN(value)\n\nconst refusedNaN = (what: string): QueryEvaluateError =>\n new QueryEvaluateError(\n `${what} was given NaN, which SQLite stores as null and Postgres orders after every number`,\n )\n\n/** Refuses NaN given to a comparison (a literal or an input), before a null beside it answers. */\nconst refuseGivenNaN = (what: string, sides: ReadonlyArray<readonly [Operandish, unknown]>) => {\n if (\n sides.some(\n ([side, value]) =>\n !isPredicate(side) &&\n (side._tag === 'Literal' || side._tag === 'Input') &&\n isNaNValue(value),\n )\n ) {\n throw refusedNaN(what)\n }\n}\n\n/** A predicate used as a value is its own truth; anything else is its value. */\nconst sideOf = (node: Operandish, scope: Scope): unknown =>\n isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope)\n\n/**\n * What an operand comes to over no row: a call of literals and inputs, run by\n * `operators` (the kernel's when not given), a predicate as its truth with\n * unknown as null. How a conformance check asks an implementation one\n * question; refuses what `evaluate` refuses (an operator the table lacks,\n * text holding NUL).\n */\nexport const valueOfOperand = (\n node: Operandish,\n options: {\n readonly input?: Row | undefined\n readonly operators?: MemoryOperators | undefined\n readonly context?: ExprContext | undefined\n } = {},\n): unknown => {\n const value = sideOf(node, {\n row: noRow,\n input: options.input ?? {},\n next: noRow,\n operators: options.operators ?? kernelOperators,\n judging: false,\n find: noRows,\n context: options.context,\n })\n if (isUnheld(value)) throw new RowsMissingError(value.reason)\n return value\n}\n\n/**\n * Refuses a value the query was given (a literal or an input) holding a NUL,\n * before any null beside it can answer: SQL refuses such a parameter where it\n * compiles, whatever the row holds. A NUL stored in a row is refused after,\n * as SQL meets it only beside a value that is not null.\n */\nconst refuseGivenNul = (\n message: string,\n sides: ReadonlyArray<readonly [Operandish, unknown]>,\n): void => {\n if (\n sides.some(\n ([side, value]) =>\n !isPredicate(side) && (side._tag === 'Literal' || side._tag === 'Input') && holdsNul(value),\n )\n ) {\n throw new QueryEvaluateError(message)\n }\n}\n\n/**\n * A predicate compared as a value. SQL's unknown is null there too, so an\n * unknown compared to anything stays unknown rather than becoming false.\n */\nconst truthValue = (truth: Judged): unknown => (truth === 'unknown' ? null : truth)\n\n/**\n * A predicate's truth, SQL's three values, or `Unheld` where it rests on what\n * the holder lacks. A null decides before anything unheld beside it, as it\n * decides SQL's answer whatever the other side holds; past that, what is not\n * held is not known, except where `and`'s false or `or`'s true settles it.\n */\nconst holds = (node: Predicate, scope: Scope): Judged => {\n switch (node._tag) {\n case 'Exists':\n return exists(node, scope)\n case 'Test':\n return truthOf(node, called(node, scope))\n case 'Eq': {\n const left = sideOf(node.left, scope)\n const right = sideOf(node.right, scope)\n // `null = anything` is unknown in SQL, including `null = null`. A row is\n // kept only when a comparison is true, so an unknown drops it either way;\n // saying so explicitly is what keeps this honest about three-valued logic\n // rather than accidentally right about it.\n const nul =\n 'an equality was given text holding a NUL character, which SQL text cannot hold portably'\n refuseGivenNul(nul, [\n [node.left, left],\n [node.right, right],\n ])\n refuseGivenNaN('an equality', [\n [node.left, left],\n [node.right, right],\n ])\n if (isNull(left) || isNull(right)) return 'unknown'\n if (isUnheld(left)) return left\n if (isUnheld(right)) return right\n if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul)\n if (isNaNValue(left) || isNaNValue(right)) throw refusedNaN('an equality')\n return left === right\n }\n case 'Null': {\n // The one comparison SQL never leaves unknown: asking whether a value\n // is absent always has an answer, unless the value is not held.\n const value = valueOf(node.operand, scope)\n return isUnheld(value) ? value : isNull(value) !== node.present\n }\n case 'Contains': {\n const value = valueOf(node.value, scope)\n const search = sideOf(node.search, scope)\n // `null like anything` is unknown, which is why an empty search is not\n // the same as no filter over a column that can be null.\n refuseGivenNul(\n 'a containment test was given text holding a NUL character, which SQL text cannot hold portably',\n [\n [node.search, search],\n [node.value, value],\n ],\n )\n if (isNull(value) || isNull(search)) return 'unknown'\n if (isUnheld(value)) return value\n if (isUnheld(search)) return search\n if (typeof value !== 'string' || typeof search !== 'string') {\n throw new QueryEvaluateError('a containment test was given something that is not text')\n }\n // Postgres text cannot hold NUL and SQLite's `like` stops at it, so no\n // two interpreters agree on such a value: refused rather than answered.\n if (holdsNul(value) || holdsNul(search)) {\n throw new QueryEvaluateError(\n 'a containment test was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n // Case-insensitive for ASCII letters only, because that is what\n // `Expr.contains` documents and what the compiled SQL folds both sides to.\n return foldAscii(value).includes(foldAscii(search))\n }\n case 'In': {\n const among = valueOf(node.among, scope)\n if (isUnheld(among)) return among\n // A list that is null (an optional input not given) is unknown, as `x in\n // null` is in SQL and as a comparison with null is: `whenGiven` guards\n // it, and every operand of an `or` is still asked.\n if (isNull(among)) return 'unknown'\n if (!Array.isArray(among)) {\n throw new QueryEvaluateError('a membership test was given a list that is not a list')\n }\n // SQL's `in`: an empty list is false whatever the value, then a null\n // value is unknown, a match is true, and no match against a list\n // holding a null is unknown, since that null might have been it.\n if (among.length === 0) return false\n const value = valueOf(node.value, scope)\n if (holdsNul(value) || among.some(holdsNul)) {\n throw new QueryEvaluateError(\n 'a membership test was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n if (isNaNValue(value) || among.some(isNaNValue)) throw refusedNaN('a membership test')\n if (isNull(value)) return 'unknown'\n if (isUnheld(value)) return value\n if (among.some(each => each === value)) return true\n return among.some(isNull) ? 'unknown' : false\n }\n // Every operand is asked, with no short cut: SQL fixes no order, so one\n // that refuses its value (a NUL) refuses here whichever operand decided.\n case 'And': {\n const truths = node.operands.map(operand => holds(operand, scope))\n if (truths.includes(false)) return false\n // Unheld before SQL's unknown: with an unknown beside it, an unheld\n // operand could still make the whole false.\n const unheld = truths.find(isUnheld)\n if (unheld !== undefined) return unheld\n return truths.includes('unknown') ? 'unknown' : true\n }\n case 'Or': {\n const truths = node.operands.map(operand => holds(operand, scope))\n if (truths.includes(true)) return true\n const unheld = truths.find(isUnheld)\n if (unheld !== undefined) return unheld\n return truths.includes('unknown') ? 'unknown' : false\n }\n case 'Not': {\n const truth = holds(node.operand, scope)\n return truth === 'unknown' || isUnheld(truth) ? truth : !truth\n }\n case 'Compare': {\n const left = valueOf(node.left, scope)\n const right = valueOf(node.right, scope)\n const nul =\n 'a comparison was given text holding a NUL character, which SQL text cannot hold portably'\n refuseGivenNul(nul, [\n [node.left, left],\n [node.right, right],\n ])\n refuseGivenNaN('a comparison', [\n [node.left, left],\n [node.right, right],\n ])\n if (isNull(left) || isNull(right)) return 'unknown'\n if (isUnheld(left)) return left\n if (isUnheld(right)) return right\n if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul)\n if (isNaNValue(left) || isNaNValue(right)) throw refusedNaN('a comparison')\n // Numbers with numbers and text with text, as `orderBy` compares them,\n // so a comparison and an ordering never disagree about what is first.\n const kind = typeof left\n if (kind !== typeof right || (kind !== 'number' && kind !== 'string')) {\n throw new QueryEvaluateError('a comparison was given values that do not order together')\n }\n const order = compare(left, right, node.collation)\n return Match.value(node.operator).pipe(\n Match.when('lt', () => order < 0),\n Match.when('lte', () => order <= 0),\n Match.when('gt', () => order > 0),\n Match.when('gte', () => order >= 0),\n Match.exhaustive,\n )\n }\n }\n}\n\n/** What a predicate comes to: SQL's three values, of which a row is kept only on `true`. */\nexport type PredicateTruth = Truth\n\n/** What a predicate reads besides its input, asked once per node: nodes are frozen. */\nconst readsBeyond = new WeakMap<Predicate, { readonly field: boolean; readonly context: boolean }>()\n\n/**\n * A predicate's truth from the input (and the context, when given) alone,\n * when it reads no field; none when it reads one, or reads the context and\n * none is given. An interpreter that runs per request decides such a\n * predicate before it builds anything: `isNull($status)` is known before any\n * row is. Refuses what `evaluate` refuses (text holding a NUL).\n */\nexport const decided = (\n node: Predicate,\n input: Row,\n operators: MemoryOperators = kernelOperators,\n context?: ExprContext,\n): Option.Option<PredicateTruth> => {\n let reads = readsBeyond.get(node)\n if (reads === undefined) {\n // A field after a write is a field too: nothing in the input alone decides it.\n const read = dependenciesOf(node)\n reads = {\n // So is a path's or an exists' row: each is read from a row.\n field: read.fields.length + read.next.length + read.reaches.length > 0,\n context: read.operations.some(operation => operation === 'viewer' || operation === 'now'),\n }\n readsBeyond.set(node, reads)\n }\n return reads.field || (reads.context && context === undefined)\n ? Option.none()\n : Option.some(\n settled(\n holds(node, {\n row: noRow,\n input,\n next: noRow,\n operators,\n judging: false,\n find: noRows,\n context,\n }),\n ),\n )\n}\n\n/** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */\nexport const truthOver = (\n node: Predicate,\n row: Row,\n input: Row = {},\n next: Row = {},\n operators: MemoryOperators = kernelOperators,\n): PredicateTruth =>\n settled(\n holds(node, {\n row: flat(row),\n input,\n next: flat(next),\n operators,\n judging: false,\n find: noRows,\n }),\n )\n\n/**\n * What `Judge` comes to: known, or unknown because it rests on something the\n * holder lacks. A known predicate's truth is SQL's three values, its\n * `'unknown'` being SQL's null, which is decided: a row is not kept on it.\n */\nexport type Verdict<T = PredicateTruth> =\n | { readonly _tag: 'Known'; readonly truth: T }\n | { readonly _tag: 'Unknown'; readonly reason: string }\n\nconst known = <T>(truth: T): Verdict<T> => ({ _tag: 'Known', truth })\nconst unknownBecause = <T>(reason: string): Verdict<T> => ({ _tag: 'Unknown', reason })\n\n/** What a verdict reads over, besides the row judged. */\ninterface JudgeOptions {\n readonly input?: Row | undefined\n readonly operators?: MemoryOperators | undefined\n /** What `Expr.viewer` and `Expr.now` read; a predicate reading one refuses a run without it. */\n readonly context?: ExprContext | undefined\n /**\n * The holder's rows, where a path from the viewer starts. Without them the\n * viewer's row is not held, and such a path is unknown.\n */\n readonly rows?: HeldRows | undefined\n}\n\n/** How a judgement reaches a row by its id: through the holder's rows, when it was given them. */\nconst finder =\n (rows: HeldRows | undefined) =>\n (entity: AnyEntity, id: unknown): View | null | Unheld =>\n rows === undefined\n ? noRows(entity)\n : Held.match<Option.Option<HeldRow>, View | null | Unheld>(rows.find(entity, id), {\n onHeld: found => Option.match(found, { onNone: () => null, onSome: viewOf }),\n onUnheld: reason => new Unheld(reason),\n })\n\n/**\n * The reference interpreter over what a holder has (`HeldRow`), three-valued:\n * where an answer rests on a row or field the holder lacks or may not see, or\n * on an operator only the server runs, it is unknown, and is never guessed.\n * Where it is known, it is what SQL answers over the same rows: the law the\n * conformance suite checks.\n */\nexport const Judge = {\n /** A predicate over one held row, and, for an invariant, the row a write would leave. */\n predicate: (\n predicate: Predicate,\n row: HeldRow,\n options: JudgeOptions & { readonly next?: HeldRow | undefined } = {},\n ): Verdict => {\n const judged = holds(predicate, {\n row: viewOf(row),\n input: options.input ?? {},\n next: options.next === undefined ? noRow : viewOf(options.next),\n operators: options.operators ?? kernelOperators,\n judging: true,\n context: options.context,\n find: finder(options.rows),\n })\n return isUnheld(judged) ? unknownBecause(judged.reason) : known(judged)\n },\n\n /**\n * Whether a held row is in a query's result: known when every predicate\n * holds (in) or one fails or is null (out), unknown otherwise. `serverOnly`\n * names a filter the server conjoins that this holder does not run (a Read\n * rule, a source's own `where`): a row the body admits is then unknown, and\n * one it refuses is still out. Refuses, as `evaluate` does, a given value\n * holding a NUL.\n */\n query: (\n body: AnyQuery,\n input: Row,\n row: HeldRow,\n options: Omit<JudgeOptions, 'input'> & { readonly serverOnly?: string | undefined } = {},\n ): Verdict<boolean> => {\n if (givenUnportable(body.where, Query.dependencies(body).inputs, input)) {\n throw new QueryEvaluateError(\n `query \"${body.entity.name}\" was given text holding a NUL character, or NaN, which no two backends agree on`,\n )\n }\n const scope: Scope = {\n row: viewOf(row),\n input,\n next: noRow,\n operators: options.operators ?? kernelOperators,\n judging: true,\n context: options.context,\n find: finder(options.rows),\n }\n // Every predicate is asked, as `evaluate` asks them: one may refuse its value.\n const truths = body.where.map(each => holds(each, scope))\n if (truths.some(truth => truth === false || truth === 'unknown')) return known(false)\n const unheld = truths.find(isUnheld)\n if (unheld !== undefined) return unknownBecause(unheld.reason)\n return options.serverOnly === undefined\n ? known(true)\n : unknownBecause(`the server also filters by ${options.serverOnly}`)\n },\n\n /**\n * What a conjunction fixes by field: each `eq` of a field and a literal, an\n * input or the viewer, by the field's key, and whether that is all it says\n * (`whole`), so every row holding those values satisfies it. A holder holding\n * every row a `whole` list's body fixes this way holds every row an exists\n * whose filter fixes the same values counts.\n */\n pins: (\n predicates: ReadonlyArray<Predicate>,\n options: { readonly input?: Row | undefined; readonly context?: ExprContext | undefined } = {},\n ): Pins => pinsOf(predicates, options.input ?? {}, options.context),\n\n match: <T, A>(\n verdict: Verdict<T>,\n cases: { readonly onKnown: (truth: T) => A; readonly onUnknown: (reason: string) => A },\n ): A => {\n switch (verdict._tag) {\n case 'Known':\n return cases.onKnown(verdict.truth)\n case 'Unknown':\n return cases.onUnknown(verdict.reason)\n }\n },\n}\n\n/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */\nconst matches = (\n body: AnyQuery,\n row: Row,\n input: Row,\n operators: MemoryOperators,\n context: ExprContext | undefined,\n): boolean =>\n // Every predicate is asked, as `and` asks every operand: SQL fixes no order, so\n // one that refuses its value refuses whichever comes first in the list.\n body.where\n .map(node =>\n settled(\n holds(node, {\n row: flat(row),\n input,\n next: noRow,\n operators,\n judging: false,\n find: noRows,\n context,\n }),\n ),\n )\n .every(truth => truth === true)\n\n/** The kinds of value this interpreter orders by; every key of one term must share one. */\nconst comparable = new Set(['string', 'number', 'boolean'])\n\n/**\n * Text by code point, as SQLite's `BINARY` and Postgres's `\"C\"` compare it.\n * JavaScript's `<` compares UTF-16 code units, which puts a character past\n * U+FFFF (two units, the first from U+D800) before U+E000 to U+FFFF, where\n * every byte-ordered backend puts it after.\n */\nconst byCodePoint = (left: string, right: string): number => {\n let i = 0\n let j = 0\n while (i < left.length && j < right.length) {\n const a = left.codePointAt(i)!\n const b = right.codePointAt(j)!\n if (a !== b) return a < b ? -1 : 1\n i += a > 0xffff ? 2 : 1\n j += b > 0xffff ? 2 : 1\n }\n return i < left.length ? 1 : j < right.length ? -1 : 0\n}\n\n/** Two keys of one term, text by its collation (code point when none is declared). */\nconst compare = (left: unknown, right: unknown, collation: Option.Option<Collation>): number => {\n if (typeof left === 'string' && typeof right === 'string') {\n const fold = Option.exists(collation, declared => declared._tag === 'AsciiFold')\n return fold ? byCodePoint(foldAscii(left), foldAscii(right)) : byCodePoint(left, right)\n }\n if (typeof left === 'boolean' && typeof right === 'boolean') {\n return Number(left) - Number(right)\n }\n return (left as number) - (right as number)\n}\n\n/** What an order's keys are worked out with: a call may read the input, and runs by the table. */\ninterface OrderScope {\n readonly input: Row\n readonly operators: MemoryOperators\n readonly context?: ExprContext | undefined\n}\n\n/** Each term's key for one row: a field's value, or what a call comes to over the row. */\nconst keysOf = (row: Row, terms: ReadonlyArray<OrderTerm>, scope: OrderScope) =>\n terms.map(term => {\n const key = valueOf(term.expr, {\n row: flat(row),\n input: scope.input,\n next: noRow,\n operators: scope.operators,\n judging: false,\n find: noRows,\n context: scope.context,\n })\n // One row's NaN would make every comparison with it NaN, and the sort of\n // every other row with it: refused for that row.\n if (isNaNValue(key)) throw refusedNaN(`an order by ${Expr.show(term.expr)}`)\n return key\n })\n\n/**\n * Refuses an ordering this interpreter will not answer for, before sorting, so\n * the refusal names the first offending row in row order rather than whichever\n * pair the engine's sort happened to compare first. Every term is checked over\n * every row's keys: a key whose kind differs from the first present one's. A\n * null key is not refused; the term says where it goes.\n */\nconst checkOrder = (\n keys: ReadonlyArray<ReadonlyArray<unknown>>,\n terms: ReadonlyArray<OrderTerm>,\n query: string,\n) =>\n terms.forEach((term, index) => {\n if (term.expr._tag !== 'Field' && term.expr._tag !== 'Call') {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by something that is neither a field nor a call`,\n )\n }\n if (Option.exists(term.collation, declared => declared._tag === 'Locale')) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders ${Expr.show(term.expr)} by a backend's locale collation, which only that backend has`,\n )\n }\n let first: string | undefined\n for (const row of keys) {\n const value = row[index]\n if (isNull(value)) continue\n const kind = typeof value\n first ??= kind\n if (kind !== first || !comparable.has(kind)) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by values this interpreter cannot compare (${first} and ${kind})`,\n )\n }\n }\n })\n\n/** Two rows' keys by checked terms: negative when `left` sorts first. */\nconst byTerms = (\n terms: ReadonlyArray<OrderTerm>,\n left: ReadonlyArray<unknown>,\n right: ReadonlyArray<unknown>,\n): number => {\n for (const [index, term] of terms.entries()) {\n const absentLeft = isNull(left[index])\n const absentRight = isNull(right[index])\n // Where a row without a value goes is the term's to say, whichever the\n // direction; two such rows tie, for the next term.\n if (absentLeft || absentRight) {\n if (absentLeft && absentRight) continue\n return absentLeft === (term.nulls === 'first') ? -1 : 1\n }\n const sign = compare(left[index], right[index], term.collation)\n if (sign !== 0) return term.direction === 'asc' ? sign : -sign\n }\n return 0\n}\n\nconst ordered = (\n rows: ReadonlyArray<Row>,\n terms: ReadonlyArray<OrderTerm>,\n query: string,\n scope: OrderScope,\n) => {\n // Keys are worked out and checked however few the rows, so a term refused over\n // one row is refused as it is over many, as `evaluateEach` refuses it.\n if (terms.length === 0) return [...rows]\n // Each row's keys worked out once, not once per comparison: a call may be dear.\n const keyed = rows.map(row => ({ row, keys: keysOf(row, terms, scope) }))\n checkOrder(\n keyed.map(({ keys }) => keys),\n terms,\n query,\n )\n return keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row)\n}\n\n/**\n * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),\n * as `evaluate` sorts: negative when it comes first. A call among them runs\n * over each row with `input` and `operators` (the kernel's when not given).\n * Refuses what `evaluate` refuses, for these two rows: a term over neither a\n * field nor a call, a locale collation, keys of different kinds, or an\n * operator the table lacks. For a client placing one row among others it\n * holds.\n */\nexport const compareRows = (\n terms: ReadonlyArray<OrderTerm>,\n left: Row,\n right: Row,\n query: string,\n options: {\n readonly input?: Row | undefined\n readonly operators?: MemoryOperators | undefined\n readonly context?: ExprContext | undefined\n } = {},\n): number => {\n const scope = {\n input: options.input ?? {},\n operators: options.operators ?? kernelOperators,\n context: options.context,\n }\n const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)] as const\n checkOrder(keys, terms, query)\n return byTerms(terms, keys[0], keys[1])\n}\n\n/**\n * The operations this interpreter runs. It is the reference, so this is the\n * whole kernel — but it is declared rather than assumed, because an\n * interpreter that gains an operator and forgets to say so is exactly what\n * `Query.unsupported` exists to catch.\n */\nexport const supported: ReadonlyArray<Operation> = [\n 'eq',\n 'isNull',\n 'isNotNull',\n 'contains',\n 'in',\n 'and',\n 'or',\n 'not',\n 'compare',\n 'viewer',\n 'now',\n]\n\n/**\n * Refuses a body needing an operation this interpreter does not run, rather\n * than skipping it and answering a different question. Called by `evaluate`;\n * call it directly to check a body once instead of on every run.\n */\nexport const assertSupported = (\n body: AnyQuery,\n operators: MemoryOperators = kernelOperators,\n): void => {\n const missing = Query.unsupported(body, supported, operators)\n if (missing.length > 0) {\n throw new QueryEvaluateError(\n `this interpreter does not run ${missing.join(', ')}, which query \"${body.entity.name}\" needs`,\n )\n }\n}\n\n/**\n * The rows the body matches, in the order it asks for. Pure: it reads the rows\n * it is given and nothing else.\n *\n * `input` holds the values this run was given, by the keys the body's\n * placeholders were built with — the same record the query would be called\n * with anywhere else.\n */\nexport const evaluate = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n options: {\n readonly operators?: MemoryOperators | undefined\n /** What `Expr.viewer` and `Expr.now` read; a body reading one refuses a run without it. */\n readonly context?: ExprContext | undefined\n } = {},\n): ReadonlyArray<Row> => {\n const operators = options.operators ?? kernelOperators\n const { context } = options\n assertSupported(body, operators)\n return ordered(\n rows.filter(row => matches(body, row, input, operators, context)),\n Query.orderFor(body, input),\n body.entity.name,\n { input, operators, context },\n )\n}\n\n/** What `evaluateEach` made of each row: those it matched, in order, and those it refused. */\nexport interface Evaluated {\n readonly matched: ReadonlyArray<Row>\n readonly refused: ReadonlyArray<Row>\n}\n\n/**\n * As `evaluate`, with each row judged alone: a row whose own values are\n * refused (text holding a NUL, a value an operator fails on) is set aside in\n * `refused` and the others are still answered. A client judging the rows it\n * holds wants this, since one bad stored row says nothing about the rest.\n *\n * What no single row causes still refuses the run: an operation or operator\n * the table lacks, an order by a locale collation, an input the body reads\n * holding a NUL (every row would refuse, and no row is the cause), and order\n * keys of different kinds across rows.\n */\nexport const evaluateEach = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n options: {\n readonly operators?: MemoryOperators | undefined\n /** As `evaluate`'s. */\n readonly context?: ExprContext | undefined\n } = {},\n): Evaluated => {\n const operators = options.operators ?? kernelOperators\n const { context } = options\n assertSupported(body, operators)\n const terms = Query.orderFor(body, input)\n const read = [...body.where, ...terms.map(term => term.expr)]\n const scope = { input, operators, context }\n const keyed: Array<{ readonly row: Row; readonly keys: ReadonlyArray<unknown> }> = []\n const refused: Row[] = []\n for (const row of rows) {\n try {\n if (matches(body, row, input, operators, context))\n keyed.push({ row, keys: keysOf(row, terms, scope) })\n } catch (error) {\n if (\n !(error instanceof QueryEvaluateError) ||\n error instanceof ContextMissingError ||\n // An alternative of `Order.chosen` this input did not choose reads nothing.\n givenUnportable(read, dependenciesOf(...read).inputs, input)\n )\n throw error\n refused.push(row)\n }\n }\n checkOrder(\n keyed.map(({ keys }) => keys),\n terms,\n body.entity.name,\n )\n return {\n matched: keyed\n .sort((left, right) => byTerms(terms, left.keys, right.keys))\n .map(({ row }) => row),\n refused,\n }\n}\n\n/**\n * Whether a constant of `read`, or a value of `input` that `inputs` name, is\n * one no two backends agree on (text holding a NUL, NaN), or a list holding\n * one: every row would refuse.\n */\nconst givenUnportable = (\n read: ReadonlyArray<AnyExpr | Predicate>,\n inputs: ReadonlyArray<string>,\n input: Row,\n): boolean =>\n Expr.givesUnportable(...read) ||\n inputs.some(key => {\n const value = input[key]\n const unportable = (each: unknown) => holdsNul(each) || isNaNValue(each)\n return Array.isArray(value) ? value.some(unportable) : unportable(value)\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,SAAiB;EAC3B,MAAM,oBAAoB,SAAS;EACnC,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,uBAAb,cAA0C,mBAAmB;CAC3D;;CAEA;;CAEA,YAAY,UAA8B,YAA2B,aAAa;EAChF,MAAM,+CAA+C,YAAY,UAAU,SAAS,EAAE,EAAE;EACxF,KAAK,OAAO;EACZ,KAAK,WAAW;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