foldkit-entity 0.16.0 → 0.18.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 (82) hide show
  1. package/README.md +582 -240
  2. package/dist/conformance/index.d.ts.map +1 -1
  3. package/dist/conformance/index.js +30 -4
  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/descriptor.d.ts +5 -1
  9. package/dist/descriptor.d.ts.map +1 -1
  10. package/dist/descriptor.js +6 -2
  11. package/dist/descriptor.js.map +1 -1
  12. package/dist/entity.d.ts +16 -3
  13. package/dist/entity.d.ts.map +1 -1
  14. package/dist/entity.js +44 -14
  15. package/dist/entity.js.map +1 -1
  16. package/dist/enumerate.d.ts +44 -0
  17. package/dist/enumerate.d.ts.map +1 -0
  18. package/dist/enumerate.js +128 -0
  19. package/dist/enumerate.js.map +1 -0
  20. package/dist/evaluate.d.ts +12 -6
  21. package/dist/evaluate.d.ts.map +1 -1
  22. package/dist/evaluate.js +48 -23
  23. package/dist/evaluate.js.map +1 -1
  24. package/dist/expr.d.ts +78 -22
  25. package/dist/expr.d.ts.map +1 -1
  26. package/dist/expr.js +86 -57
  27. package/dist/expr.js.map +1 -1
  28. package/dist/footprint.d.ts +120 -0
  29. package/dist/footprint.d.ts.map +1 -0
  30. package/dist/footprint.js +41 -0
  31. package/dist/footprint.js.map +1 -0
  32. package/dist/held.js +11 -3
  33. package/dist/held.js.map +1 -1
  34. package/dist/index.d.ts +24 -7
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +10 -6
  37. package/dist/index.js.map +1 -1
  38. package/dist/invariant.d.ts +41 -11
  39. package/dist/invariant.d.ts.map +1 -1
  40. package/dist/invariant.js +102 -51
  41. package/dist/invariant.js.map +1 -1
  42. package/dist/law.d.ts.map +1 -1
  43. package/dist/law.js +3 -9
  44. package/dist/law.js.map +1 -1
  45. package/dist/lawCore.d.ts +42 -0
  46. package/dist/lawCore.d.ts.map +1 -0
  47. package/dist/lawCore.js +12 -0
  48. package/dist/lawCore.js.map +1 -0
  49. package/dist/lawIds.d.ts +15 -0
  50. package/dist/lawIds.d.ts.map +1 -0
  51. package/dist/lawIds.js +13 -0
  52. package/dist/lawIds.js.map +1 -0
  53. package/dist/laws.d.ts +308 -0
  54. package/dist/laws.d.ts.map +1 -0
  55. package/dist/laws.js +566 -0
  56. package/dist/laws.js.map +1 -0
  57. package/dist/memoryTable.d.ts +11 -0
  58. package/dist/memoryTable.d.ts.map +1 -0
  59. package/dist/memoryTable.js +69 -0
  60. package/dist/memoryTable.js.map +1 -0
  61. package/dist/operators.d.ts +1 -1
  62. package/dist/operators.d.ts.map +1 -1
  63. package/dist/operators.js +2 -66
  64. package/dist/operators.js.map +1 -1
  65. package/dist/refine.d.ts +64 -0
  66. package/dist/refine.d.ts.map +1 -0
  67. package/dist/refine.js +104 -0
  68. package/dist/refine.js.map +1 -0
  69. package/dist/rows.d.ts +15 -0
  70. package/dist/rows.d.ts.map +1 -0
  71. package/dist/rows.js +23 -0
  72. package/dist/rows.js.map +1 -0
  73. package/dist/sets.js.map +1 -1
  74. package/dist/uncollated.d.ts +10 -0
  75. package/dist/uncollated.d.ts.map +1 -0
  76. package/dist/uncollated.js +18 -0
  77. package/dist/uncollated.js.map +1 -0
  78. package/dist/write.d.ts +65 -7
  79. package/dist/write.d.ts.map +1 -1
  80. package/dist/write.js +128 -30
  81. package/dist/write.js.map +1 -1
  82. package/package.json +3 -3
@@ -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,SAA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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 { uncollatedText } from './uncollated.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/**\n * Refuses an order over text with no declared collation: JavaScript would\n * answer by code point where SQLite compares bytes and Postgres follows its\n * locale. Asked wherever the answer depends on the order, and not of a\n * membership judged alone (`evaluateEach`), which no order decides.\n */\nconst checkCollated = (terms: ReadonlyArray<OrderTerm>, query: string) => {\n for (const term of terms) {\n const uncollated = uncollatedText(term)\n if (Option.isSome(uncollated)) {\n throw new QueryEvaluateError(`query \"${query}\" cannot be ordered: ${uncollated.value}`)\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 checkCollated(terms, query)\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, text with no declared collation, keys\n * of different kinds, or an operator the table lacks. For a client placing\n * one row among others it 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 checkCollated(terms, query)\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 *\n * The order is part of the answer, so an order over text with no declared\n * collation is refused (`Query.placement`'s reason): declare one on the field,\n * or on the term.\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. It judges membership, which no order\n * decides, so an order over text with no declared collation does not refuse it:\n * `matched` is then in code point order, which no other reader need follow.\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,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,GAA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gB,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"}
package/dist/expr.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { Array, Option, Pipeable, Schema } from "effect";
1
+ import { Array as Array$1, Option, Pipeable, Schema } from "effect";
2
2
  import { AnyEntity, AnyVariantEntity, EntityField, EntityIdentity, EntityRelation, IdOf } from "./index.js";
3
+ import { Refinement } from "./refine.js";
3
4
  import { Collation as Collation$1 } from "./collation.js";
4
5
  import { NowExpr, ViewerExpr, ViewerPathExpr, viewer } from "./context.js";
5
6
  import { Law as Law$1 } from "./law.js";
@@ -121,7 +122,7 @@ export type OneRelation = EntityRelation<string, string, AnyEntity, 'one', boole
121
122
  export interface PathExpr<T> {
122
123
  readonly _tag: 'Path';
123
124
  /** The relations followed, in order, the first one the judged row's own. */
124
- readonly via: Array.NonEmptyReadonlyArray<OneRelation>;
125
+ readonly via: Array$1.NonEmptyReadonlyArray<OneRelation>;
125
126
  /** What is read on the row reached: a field of the last relation's target. */
126
127
  readonly field: FieldExpr<T>;
127
128
  }
@@ -197,12 +198,12 @@ export interface InPredicate {
197
198
  */
198
199
  export interface AndPredicate {
199
200
  readonly _tag: 'And';
200
- readonly operands: Array.NonEmptyReadonlyArray<Predicate>;
201
+ readonly operands: Array$1.NonEmptyReadonlyArray<Predicate>;
201
202
  }
202
203
  /** At least one operand holds. Never empty, and never holding another `or`. */
203
204
  export interface OrPredicate {
204
205
  readonly _tag: 'Or';
205
- readonly operands: Array.NonEmptyReadonlyArray<Predicate>;
206
+ readonly operands: Array$1.NonEmptyReadonlyArray<Predicate>;
206
207
  }
207
208
  /**
208
209
  * The operand does not hold. As SQL's `not`, an unknown stays unknown, so a row
@@ -257,16 +258,20 @@ type OwnOperand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> |
257
258
  /**
258
259
  * Type-only: the Entities a predicate's fields belong to, by name, so
259
260
  * `Query.where` can refuse one over another Entity where it is written. Never
260
- * set at run time; a predicate built without it (typed plain `Predicate`)
261
- * reads as unknown and is checked at run time only.
261
+ * set at run time. A node built without it (typed plain `Predicate`) names
262
+ * nothing, so it adds no name to a combination and the run-time ownership
263
+ * check is what proves it.
262
264
  */
263
265
  export interface Reads<Names extends string> {
264
266
  readonly '~reads'?: Names;
265
267
  }
266
268
  /**
267
269
  * The Entity names an operand reads: a field's own, a marked node's, none for
268
- * a value or an input. A node with no marker (a `Predicate` typed plainly)
269
- * reads as `string`, unknown.
270
+ * a value or an input. A node with no marker (`Predicate`, `Expr<string>`)
271
+ * answers `never`, not `string`: an unknown read contributes nothing, so
272
+ * `and(onAuthor, plain)` still reads `'Author'` and is refused over another
273
+ * Entity, where `string` would absorb every name it is unioned with and lose
274
+ * that refusal. Ownership of what the type cannot see is checked at run time.
270
275
  */
271
276
  export type ReadsOf<X> = X extends EntityField<infer Name, string, Schema.Constraint> ? Name : X extends EntityRelation<infer Name, string, AnyEntity, 'one', boolean> ? Name : X extends PlainValue | {
272
277
  readonly _tag: 'Literal' | 'Input' | 'Viewer' | 'Now';
@@ -359,11 +364,19 @@ export interface QueryDependencies extends Dependencies {
359
364
  * fall back past it.
360
365
  */
361
366
  export type OrderedOperand = EntityField<string, string, Schema.Constraint & Schema.Codec<number | string | Date | null, any, any, any>> | Expr<number> | Expr<number | null> | Expr<string> | Expr<string | null> | Expr<Date> | Expr<Date | null>;
367
+ /** What a comparison's other side may be, typed from the side it is applied to. */
368
+ type CompareRight<L> = ValueOf<L> | Expr<ValueOf<L>>;
369
+ /** Intersected onto the subject of a step, so a value that does not fit it is refused at the step. */
370
+ type Fits<Right, Allowed, Name extends string> = [Right] extends [Allowed] ? unknown : Invalid<`foldkit-entity: ${Name} was given a value that does not fit the operand it is applied to`>;
371
+ /** `Expr.lt` and its siblings' `step`: the comparison's right side and options, then its left. */
372
+ export type CompareStep = <const R>(right: R, options?: {
373
+ readonly collation?: Collation$1 | undefined;
374
+ }) => <L extends OrderedOperand>(left: L & Fits<R, CompareRight<L>, 'a comparison step'>) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
362
375
  /** `Expr.and` and `Expr.or`: one operand is that operand, and two or more are one node. */
363
376
  interface Connective<Node extends Predicate> {
364
377
  <P extends Predicate>(only: P): P;
365
378
  <A extends Predicate, B extends Predicate, Rest extends ReadonlyArray<Predicate>>(first: A, second: B, ...rest: Rest): Node & Reads<ReadsOf<A> | ReadsOf<B> | ReadsOf<Rest[number]>>;
366
- (...operands: Array.NonEmptyReadonlyArray<Predicate>): Predicate;
379
+ (...operands: Array$1.NonEmptyReadonlyArray<Predicate>): Predicate;
367
380
  }
368
381
  /** A schema's stored form, which is what an operator takes and gives. */
369
382
  type StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>;
@@ -390,8 +403,19 @@ export interface Operator<In extends ReadonlyArray<Schema.Top>, Out extends Sche
390
403
  * or `required`, as `Expr.lt(field, value, { collation })` is.
391
404
  */
392
405
  <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]>; }>(...args: [...A, CallOptions]): CallOf<Out> & Reads<ReadsOf<A[number]>>;
406
+ /**
407
+ * The call without its first argument, for `pipe` and `flow`:
408
+ * `pipe(Product.fields.upc, startsWith.step('A'))` builds the node
409
+ * `startsWith(Product.fields.upc, 'A')` builds. One signature, so reads stay
410
+ * exact through `pipe`, which an overload would lose. It takes no
411
+ * `CallOptions`; a call that needs a collation is written data-first.
412
+ */
413
+ readonly step: OperatorStep<In, Out>;
393
414
  readonly descriptor: OperatorDescriptor;
394
415
  }
416
+ type OperatorArguments<In extends ReadonlyArray<Schema.Top>> = { readonly [K in keyof In]: ArgumentOf<In[K]>; };
417
+ /** An operator's step: its arguments past the first, then the first. */
418
+ export type OperatorStep<In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top> = <const Rest extends (OperatorArguments<In> extends readonly [unknown, ...infer R] ? Readonly<R> : never)>(...rest: Rest) => <const Self extends (OperatorArguments<In> extends readonly [infer First, ...Array<unknown>] ? First : never)>(self: Self) => CallOf<Out> & Reads<ReadsOf<Self> | ReadsOf<Rest[number]>>;
395
419
  /** What a call may say past its arguments. */
396
420
  export interface CallOptions {
397
421
  /** The collation it compares text under, in place of its arguments' declared one. */
@@ -431,6 +455,19 @@ interface NextOf {
431
455
  <Name extends string, Key extends string, S extends Schema.Constraint>(field: EntityField<Name, Key, S>): NextExpr<Schema.Schema.Type<S>> & Reads<Name>;
432
456
  <Name extends string, Key extends string, Optional extends boolean>(relation: EntityRelation<Name, Key, AnyEntity, 'one', Optional>): NextExpr<Optional extends true ? string | null : string> & Reads<Name>;
433
457
  }
458
+ /** What `Expr.eq` accepts on the right, typed from its left. */
459
+ type EqRight<L> = ValueOf<L> | Expr<ValueOf<L>> | PathExpr<ValueOf<L> | null> | ViewerPathExpr<ValueOf<L> | null> | (boolean extends ValueOf<L> ? Predicate : never);
460
+ declare const eqCall: <L extends Operand<any> | PlainValue, R extends (L extends PlainValue ? Invalid<'foldkit-entity: Expr.eq takes the field on the left and the value on the right'> : EqRight<L>)>(left: L, right: R) => EqPredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
461
+ /** `Expr.eq.step`: the right side, then the left. */
462
+ export type EqStep = <const R>(right: R) => <L extends Operand<any>>(left: L & Fits<R, EqRight<L>, 'Expr.eq.step'>) => EqPredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
463
+ /** What `Expr.contains` searches for: a value or an input, never a row's own. */
464
+ type ContainsSearch = string | LiteralExpr<string> | InputExpr<string> | InputExpr<string | null>;
465
+ declare const containsCall: <L extends TextOperand>(value: L, search: ContainsSearch) => ContainsPredicate & Reads<ReadsOf<L>>;
466
+ /** `Expr.contains.step`: the search, then the text. */
467
+ export type ContainsStep = <const S extends ContainsSearch>(search: S) => <L extends TextOperand>(value: L) => ContainsPredicate & Reads<ReadsOf<L>>;
468
+ declare const inCall: <L extends Operand<any>>(value: L, among: ReadonlyArray<ValueOf<L>> | Expr<ReadonlyArray<ValueOf<L>>>) => InPredicate & Reads<ReadsOf<L>>;
469
+ /** `Expr.in.step`: the list or its input, then the value. */
470
+ export type InStep = <const R extends ReadonlyArray<unknown> | Expr<ReadonlyArray<unknown>>>(among: R) => <L extends Operand<any>>(value: L & Fits<R, ReadonlyArray<ValueOf<L>> | Expr<ReadonlyArray<ValueOf<L>>>, 'Expr.in.step'>) => InPredicate & Reads<ReadsOf<L>>;
434
471
  export declare const Expr: {
435
472
  /**
436
473
  * An operator, defined by what a call of it means: `definedAs` builds that
@@ -598,7 +635,9 @@ export declare const Expr: {
598
635
  * Expr.eq(Post.fields.status, 'active')
599
636
  * ```
600
637
  */
601
- eq: <L extends Operand<any> | PlainValue, R extends (L extends PlainValue ? Invalid<'foldkit-entity: Expr.eq takes the field on the left and the value on the right'> : ValueOf<L> | Expr<ValueOf<L>> | PathExpr<ValueOf<L> | null> | ViewerPathExpr<ValueOf<L> | null> | (boolean extends ValueOf<L> ? Predicate : never))>(left: L, right: R) => EqPredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
638
+ eq: typeof eqCall & {
639
+ step: EqStep;
640
+ };
602
641
  /**
603
642
  * Whether a field holds no value. Its opposite is `isNotNull`; both are the
604
643
  * one node, since a query asks which of the two it means, and `is not null`
@@ -623,7 +662,9 @@ export declare const Expr: {
623
662
  * nullable column that should match everything on an empty search says so:
624
663
  * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.
625
664
  */
626
- contains: <L extends TextOperand>(value: L, search: string | LiteralExpr<string> | InputExpr<string> | InputExpr<string | null>) => ContainsPredicate & Reads<ReadsOf<L>>;
665
+ contains: typeof containsCall & {
666
+ step: ContainsStep;
667
+ };
627
668
  /**
628
669
  * Whether a value is one of `among`: a list written out, or an input whose
629
670
  * value is one. Each element is compared as `eq` compares.
@@ -637,7 +678,9 @@ export declare const Expr: {
637
678
  * holding a null, and an empty list matches no row. A list written out is
638
679
  * copied, so changing the array afterwards does not change the query.
639
680
  */
640
- in: <L extends Operand<any>>(value: L, among: ReadonlyArray<ValueOf<L>> | Expr<ReadonlyArray<ValueOf<L>>>) => InPredicate & Reads<ReadsOf<L>>;
681
+ in: typeof inCall & {
682
+ step: InStep;
683
+ };
641
684
  /**
642
685
  * `left` orders before `right`. Numbers compare as numbers; text compares
643
686
  * under a collation, the one given or the field's declared one, which must be
@@ -651,21 +694,29 @@ export declare const Expr: {
651
694
  * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))
652
695
  * ```
653
696
  */
654
- lt: <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(left: L, right: R, options?: {
697
+ lt: (<L extends OrderedOperand, R extends CompareRight<L>>(left: L, right: R, options?: {
655
698
  readonly collation?: Collation$1 | undefined;
656
- }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
699
+ }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>) & {
700
+ step: CompareStep;
701
+ };
657
702
  /** `left` orders before `right`, or with it; see `Expr.lt`. */
658
- lte: <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(left: L, right: R, options?: {
703
+ lte: (<L extends OrderedOperand, R extends CompareRight<L>>(left: L, right: R, options?: {
659
704
  readonly collation?: Collation$1 | undefined;
660
- }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
705
+ }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>) & {
706
+ step: CompareStep;
707
+ };
661
708
  /** `left` orders after `right`; see `Expr.lt`. */
662
- gt: <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(left: L, right: R, options?: {
709
+ gt: (<L extends OrderedOperand, R extends CompareRight<L>>(left: L, right: R, options?: {
663
710
  readonly collation?: Collation$1 | undefined;
664
- }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
711
+ }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>) & {
712
+ step: CompareStep;
713
+ };
665
714
  /** `left` orders after `right`, or with it; see `Expr.lt`. */
666
- gte: <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(left: L, right: R, options?: {
715
+ gte: (<L extends OrderedOperand, R extends CompareRight<L>>(left: L, right: R, options?: {
667
716
  readonly collation?: Collation$1 | undefined;
668
- }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
717
+ }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>) & {
718
+ step: CompareStep;
719
+ };
669
720
  /**
670
721
  * Every operand holds, as one predicate to place inside another: `where`'s
671
722
  * list is already a conjunction, so this is for `or(and(a, b), c)`.
@@ -826,8 +877,11 @@ export type AnyQuery = Query<AnyEntity>;
826
877
  */
827
878
  export declare const maxQueryNodes = 1000;
828
879
  export declare const Query: {
829
- /** Every row of an Entity: the query each transformation narrows. */
830
- from: <E extends AnyEntity>(entity: E) => Query<E>;
880
+ /**
881
+ * Every row of an Entity, the query each transformation narrows; or every
882
+ * row in a state of one (`Query.from(Draft)`), its predicate in `where`.
883
+ */
884
+ from: <E extends AnyEntity>(source: E | Refinement<E, string, unknown>) => Query<E>;
831
885
  /**
832
886
  * Narrows to the rows the predicate holds for. Two `where`s conjoin — the
833
887
  * second never replaces the first — so a fragment can be written once and
@@ -911,5 +965,7 @@ export declare const Query: {
911
965
  */
912
966
  show: (self: AnyQuery) => string;
913
967
  };
968
+ /** Prints `node` as `name`: what `Entity.refine` names its predicates. */
969
+ export declare const nameNode: (node: Predicate, name: string) => void;
914
970
  export {};
915
971
  //# sourceMappingURL=expr.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"expr.d.ts","names":["Collation","Law","Arr"],"sources":["../src/expr.ts"],"mappings":";;;;;;iBAgCiB,YAAY;WAClB;WACA,OAAO;;;;;;iBAOD,UAAU;WAChB;WACA,OAAO;WACP;WACA,QAAQ,OAAO,MAAM;;;;;;WAMrB,WAAW,OAAO,OAAOA;;;;;;;;iBASnB,UAAU;WAChB;WACA;WACA,QAAQ,OAAO,MAAM;;;;;;;iBAQf,SAAS;WACf;WACA,OAAO,UAAU;;;;;;;;iBASX;WACN;WACA;WACA;WACA,aAAa,OAAO;;WAEpB,OAAO,cAAc,OAAO;WAC5B,QAAQ,OAAO;;;;;;WAMf,WAAW,OAAO,WAAW,MAAM,cAAc,gBAAgB;;;;;;WAMjE;;;;;;;WAOA;;WAEA,MAAM,cAAcC;;;iBAId;;WAEN,MAAM,UAAU;;;;;;WAMhB,WAAW,eAAe;;;qBAIxB,aAAa;;;;;qBAMb,cAAW,UAAc,oBAAkB,WAAa;;;;;;iBAmBpD,SAAS;WACf;WACA,UAAU;WACV,MAAM,cAAc;WACpB,WAAW,OAAO,OAAO,KAAK;;WAE9B,WAAW,OAAO,OAAOD;;;YAIxB,cAAc,+BAA+B;;;;;;iBAOxC,SAAS;WACf;;WAEA,KAAKE,MAAI,sBAAsB;;WAE/B,OAAO,UAAU;;;YAIhB,KAAK,KACb,YAAY,KACZ,UAAU,KACV,UAAU,KACV,SAAS,KACT,SAAS,KACT,WAAW,KACX,QAAQ,KACR,SAAS,KACT,eAAe;;YAGP,UAAU;;;;;;;;;YAUV,YACR,cACA,gBACA,oBACA,cACA,eACA,cACA,eACA,mBACA,gBACA;;;;;;;;iBASa;WACN;;W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