foldkit-entity 0.14.0 → 0.15.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 (93) hide show
  1. package/README.md +139 -5
  2. package/dist/collation.d.ts +33 -2
  3. package/dist/collation.d.ts.map +1 -0
  4. package/dist/conformance/index.d.ts +4 -4
  5. package/dist/conformance/index.d.ts.map +1 -1
  6. package/dist/conformance/index.js +5 -7
  7. package/dist/conformance/index.js.map +1 -1
  8. package/dist/conformance/operator.d.ts +1 -2
  9. package/dist/conformance/operator.d.ts.map +1 -1
  10. package/dist/conformance/operator.js +2 -6
  11. package/dist/conformance/operator.js.map +1 -1
  12. package/dist/conformance/relational.d.ts +17 -17
  13. package/dist/conformance/relational.d.ts.map +1 -1
  14. package/dist/conformance/relational.js +1 -3
  15. package/dist/conformance/relational.js.map +1 -1
  16. package/dist/conformance/variants.d.ts +47 -0
  17. package/dist/conformance/variants.d.ts.map +1 -0
  18. package/dist/conformance/variants.js +126 -0
  19. package/dist/conformance/variants.js.map +1 -0
  20. package/dist/context.d.ts +60 -2
  21. package/dist/context.d.ts.map +1 -0
  22. package/dist/descriptor.d.ts +33 -0
  23. package/dist/descriptor.d.ts.map +1 -0
  24. package/dist/descriptor.js +137 -0
  25. package/dist/descriptor.js.map +1 -0
  26. package/dist/entity.d.ts +231 -0
  27. package/dist/entity.d.ts.map +1 -0
  28. package/dist/entity.js +435 -0
  29. package/dist/entity.js.map +1 -0
  30. package/dist/evaluate.d.ts +204 -2
  31. package/dist/evaluate.d.ts.map +1 -0
  32. package/dist/evaluate.js +51 -7
  33. package/dist/evaluate.js.map +1 -1
  34. package/dist/expr.d.ts +915 -2
  35. package/dist/expr.d.ts.map +1 -0
  36. package/dist/expr.js +50 -10
  37. package/dist/expr.js.map +1 -1
  38. package/dist/held.d.ts +112 -2
  39. package/dist/held.d.ts.map +1 -0
  40. package/dist/held.js +13 -2
  41. package/dist/held.js.map +1 -1
  42. package/dist/ids.d.ts +8 -0
  43. package/dist/ids.d.ts.map +1 -0
  44. package/dist/ids.js +8 -0
  45. package/dist/ids.js.map +1 -0
  46. package/dist/index.d.ts +380 -6
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +108 -12
  49. package/dist/index.js.map +1 -0
  50. package/dist/invariant.d.ts +123 -2
  51. package/dist/invariant.d.ts.map +1 -0
  52. package/dist/invariant.js +236 -1
  53. package/dist/invariant.js.map +1 -0
  54. package/dist/law.d.ts +264 -2
  55. package/dist/law.d.ts.map +1 -0
  56. package/dist/law.js +1 -1
  57. package/dist/operators.d.ts +170 -2
  58. package/dist/operators.d.ts.map +1 -0
  59. package/dist/operators.js +3 -3
  60. package/dist/readFilter.d.ts +8 -2
  61. package/dist/readFilter.d.ts.map +1 -0
  62. package/dist/sets.d.ts +18 -2
  63. package/dist/sets.d.ts.map +1 -0
  64. package/dist/sets.js +1 -1
  65. package/dist/shape.d.ts +23 -2
  66. package/dist/shape.d.ts.map +1 -0
  67. package/dist/tested.d.ts +8 -2
  68. package/dist/tested.d.ts.map +1 -0
  69. package/dist/text.d.ts +27 -2
  70. package/dist/text.d.ts.map +1 -0
  71. package/dist/text.js +1 -1
  72. package/dist/variants.d.ts +72 -0
  73. package/dist/variants.d.ts.map +1 -0
  74. package/dist/variants.js +76 -0
  75. package/dist/variants.js.map +1 -0
  76. package/dist/words.d.ts +17 -2
  77. package/dist/words.d.ts.map +1 -0
  78. package/dist/write.d.ts +312 -2
  79. package/dist/write.d.ts.map +1 -0
  80. package/dist/write.js +3 -3
  81. package/package.json +3 -3
  82. package/dist/collation-BB4YTIbY.d.ts +0 -34
  83. package/dist/collation-BB4YTIbY.d.ts.map +0 -1
  84. package/dist/index-48JeXG0A.d.ts +0 -2585
  85. package/dist/index-48JeXG0A.d.ts.map +0 -1
  86. package/dist/readFilter-CWMnFRVw.d.ts +0 -9
  87. package/dist/readFilter-CWMnFRVw.d.ts.map +0 -1
  88. package/dist/shape-LAowRf9f.d.ts +0 -23
  89. package/dist/shape-LAowRf9f.d.ts.map +0 -1
  90. package/dist/src-DKhUqLoC.js +0 -731
  91. package/dist/src-DKhUqLoC.js.map +0 -1
  92. package/dist/words-a4e9o-TK.d.ts +0 -18
  93. package/dist/words-a4e9o-TK.d.ts.map +0 -1
package/dist/expr.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"expr.js","names":["Arr"],"sources":["../src/expr.ts"],"sourcesContent":["/**\n * `Expr` — a query's scalar computations as typed values.\n *\n * An Entity says what a domain has; an `Expr` says something about one row of\n * it. A field reference, an input placeholder, a literal, and comparisons of\n * those are all immutable data: building one performs no work, reads nothing,\n * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`\n * to SQL, an in-memory evaluator to a predicate over rows.\n *\n * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every\n * operation here is one a real query in this repository needs; the set grows\n * from queries, not from what a database could express.\n */\nimport { Array as Arr, Match, Option, Pipeable, Schema, SchemaAST } from 'effect'\nimport { absurd } from 'effect/Function'\nimport { Collation } from './collation.js'\nimport { SchemaShape } from './shape.js'\nimport { Law, type Side } from './law.js'\nimport { now, viewer, type NowExpr, type ViewerExpr, type ViewerPathExpr } from './context.js'\nimport { own } from './record.js'\nimport type {\n AnyEntity,\n Cardinality,\n EntityField,\n EntityIdentity,\n EntityRelation,\n IdOf,\n} from './index.js'\n\n/** A constant the query was written with. */\nexport interface LiteralExpr<T> {\n readonly _tag: 'Literal'\n readonly value: T\n}\n\n/**\n * One field of one Entity. `owner` is the Entity's identity rather than its\n * name, so two Entities defined with the same name are not one column.\n */\nexport interface FieldExpr<T> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<string>\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n /**\n * How it compares when ordered by, as the field declares (`Collation.of`).\n * An id is `binary` unless it says otherwise: its order need only be total\n * and agreed, and every order ends on it.\n */\n readonly collation: Option.Option<Collation>\n}\n\n/**\n * A value the query is given when it runs. A definition's body is built once,\n * so inside it an input is this placeholder and never the value: there is\n * nothing yet to branch on, and a query that wants to depend on what was passed\n * says so with an operation over the placeholder.\n */\nexport interface InputExpr<T> {\n readonly _tag: 'Input'\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/**\n * A field as the row a write would leave holds it: what an invariant reads\n * (`after.status`, beside `before.status` over a change). An interpreter that judges stored\n * rows alone refuses it, as the operation `next`.\n */\nexport interface NextExpr<T> {\n readonly _tag: 'Next'\n readonly field: FieldExpr<T>\n}\n\n/**\n * What an operator is, as the nodes that call it hold it: its identity, the\n * stored form of what it takes and gives, and, for an operator defined by an\n * expression, how to build that expression. It computes nothing itself.\n * Identity is this object; `id` and `version` name it.\n */\nexport interface OperatorDescriptor {\n readonly _tag: 'Operator'\n readonly id: string\n readonly version: number\n readonly description: Option.Option<string>\n /** One schema per argument, read as the stored form. */\n readonly input: ReadonlyArray<Schema.Top>\n readonly output: Schema.Top\n /**\n * Builds the expression a call means, from its arguments: an operator defined\n * by an expression. None for a primitive operator, which each interpreter\n * implements (`Operators`).\n */\n readonly definedAs: Option.Option<(...args: ReadonlyArray<Operandish>) => Operandish>\n /**\n * A primitive operator's null rule. `strict`: a null argument gives null, or\n * unknown for a predicate, and the implementation never sees one. `handled`:\n * the implementation is given nulls and answers for them.\n */\n readonly nulls: 'strict' | 'handled'\n /**\n * How a call compares text. `operands`: it carries the collation its collated\n * text arguments share, so its text result compares under it. `required`: the\n * same, refused where none is declared (it compares text itself, as\n * `Text.startsWith` does). `none`: it carries none.\n */\n readonly collation: 'none' | 'operands' | 'required'\n /** The equations every implementation keeps (`Law`), checked where declared, tested by `Conformance.laws`. */\n readonly laws: ReadonlyArray<Law>\n}\n\n/** What an interpreter runs, as far as a check of a body needs to know. */\nexport interface OperatorTable {\n /** Whether this table implements the operator. */\n readonly has: (operator: OperatorDescriptor) => boolean\n /**\n * The versions of the operator `id` it implements: what a refusal of a call\n * to another version names, since a client and a server on different\n * deploys can disagree on one.\n */\n readonly versions: (id: string) => ReadonlyArray<number>\n}\n\n/** A table implementing nothing: every primitive operator is unsupported by it. */\nexport const noOperators: OperatorTable = Object.freeze({ has: () => false, versions: () => [] })\n\n/**\n * An operator `operators` does not implement, by name, with the versions of it\n * the table does implement: `acme.slug@2 (this table has acme.slug)`.\n */\nexport const missingName = (operator: OperatorDescriptor, operators: OperatorTable): string => {\n const held = operators.versions(operator.id)\n // The same name and version from another `Expr.operator` call: a table holds\n // declarations, not names, so it is a different operator.\n if (held.includes(operator.version)) {\n return `${operatorName(operator)} (this table has another declaration of it; declare an operator once and import it)`\n }\n return held.length === 0\n ? operatorName(operator)\n : `${operatorName(operator)} (this table has ${held\n .map(version => operatorName({ ...operator, version }))\n .join(', ')})`\n}\n\n/**\n * A call of an operator whose result is a scalar. `expansion` is the\n * expression it means, built from its arguments when it was called: an\n * interpreter runs that, and needs nothing of its own for the operator.\n */\nexport interface CallExpr<T> {\n readonly _tag: 'Call'\n readonly operator: OperatorDescriptor\n readonly args: ReadonlyArray<Operandish>\n readonly expansion: Option.Option<Expr<T>>\n /** How its text result compares, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/** A `one` relation of any Entity: what a path follows and an exists points through. */\nexport type OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/**\n * A field of the row reached from the row judged by following `one`\n * relations (`Expr.path`). A null link, or a row the reader may not see,\n * reaches no row, and the path reads null.\n */\nexport interface PathExpr<T> {\n readonly _tag: 'Path'\n /** The relations followed, in order, the first one the judged row's own. */\n readonly via: Arr.NonEmptyReadonlyArray<OneRelation>\n /** What is read on the row reached: a field of the last relation's target. */\n readonly field: FieldExpr<T>\n}\n\n/** A typed scalar: what a comparison compares. */\nexport type Expr<T> =\n | LiteralExpr<T>\n | FieldExpr<T>\n | InputExpr<T>\n | NextExpr<T>\n | CallExpr<T>\n | ViewerExpr<T>\n | NowExpr<T>\n | PathExpr<T>\n | ViewerPathExpr<T>\n\n/** Any scalar, for the places that hold operands without caring what they are. */\nexport type AnyExpr = Expr<unknown>\n\n/**\n * `Expr<boolean>`, in the shape the operations that exist can actually take.\n * The design's kernel is all boolean-valued (`eq`, `and`, `isNull`,\n * `contains`, …), so a predicate is its own type rather than a phantom\n * parameter on a general operation node: `Predicate` and `Expr<string>` cannot\n * then be confused, which a structural phantom would allow. A scalar-valued\n * operation, if one is ever needed, joins `Expr` instead.\n */\nexport type Predicate =\n | EqPredicate\n | NullPredicate\n | ContainsPredicate\n | InPredicate\n | AndPredicate\n | OrPredicate\n | NotPredicate\n | ComparePredicate\n | TestPredicate\n | ExistsPredicate\n\n/**\n * Some row points at the row asked about through `relation`, a `one` relation\n * of another Entity, and holds `where` (`Expr.exists`). The row asked about is\n * the one judged, or the one `via` reaches from it; a path that reaches none\n * makes this unknown, as a path's field reads null. Only rows the reader may\n * see are sought.\n */\nexport interface ExistsPredicate {\n readonly _tag: 'Exists'\n /** The relations followed to the row asked about; empty for the row judged itself. */\n readonly via: ReadonlyArray<OneRelation>\n readonly relation: OneRelation\n /** What the pointing row must hold, over its own fields and the input. */\n readonly where: Option.Option<Predicate>\n}\n\n/** Two values are the same. */\nexport interface EqPredicate {\n readonly _tag: 'Eq'\n readonly left: Operandish\n readonly right: Operandish\n}\n\n/**\n * Whether a value is absent. `present` says which answer absence gives, so one\n * node covers `is null` and `is not null` rather than two that differ by a\n * negation nothing else can express.\n */\nexport interface NullPredicate {\n readonly _tag: 'Null'\n readonly operand: AnyExpr\n readonly present: boolean\n}\n\n/**\n * Whether a text value contains another. Containing the empty string is\n * everything, which is what lets a search box with nothing typed in it be the\n * same query as one with something — see `Expr.contains`.\n */\nexport interface ContainsPredicate {\n readonly _tag: 'Contains'\n readonly value: AnyExpr\n readonly search: Operandish\n}\n\n/**\n * Whether a value is one of a list. The list is a scalar whose value is an\n * array: a literal, or an input (a principal's `projectIds`, a picker's\n * chosen ids). Read as SQL's `in`: a null value is unknown, and so is no\n * match against a list holding a null; an empty list matches nothing.\n */\nexport interface InPredicate {\n readonly _tag: 'In'\n readonly value: AnyExpr\n readonly among: AnyExpr\n}\n\n/**\n * Every operand holds. `Query.where`'s list is already a conjunction; this is\n * one inside something else, `or(and(a, b), c)`. Never empty, and never holding\n * another `and`: `Expr.and` flattens one into its parent.\n */\nexport interface AndPredicate {\n readonly _tag: 'And'\n readonly operands: Arr.NonEmptyReadonlyArray<Predicate>\n}\n\n/** At least one operand holds. Never empty, and never holding another `or`. */\nexport interface OrPredicate {\n readonly _tag: 'Or'\n readonly operands: Arr.NonEmptyReadonlyArray<Predicate>\n}\n\n/**\n * The operand does not hold. As SQL's `not`, an unknown stays unknown, so a row\n * whose operand is unknown (a null compared) is matched by neither the operand\n * nor its `not`.\n */\nexport interface NotPredicate {\n readonly _tag: 'Not'\n readonly operand: Predicate\n}\n\n/** Which way a comparison orders its two sides: `left < right` for `lt`. */\nexport type CompareOperator = 'lt' | 'lte' | 'gt' | 'gte'\n\n/**\n * One scalar orders before, or after, the other. A null on either side is\n * unknown. `collation` is how text compares, decided where the comparison is\n * written (see `Expr.lt`); none for values that order intrinsically, numbers.\n */\nexport interface ComparePredicate {\n readonly _tag: 'Compare'\n readonly operator: CompareOperator\n readonly left: AnyExpr\n readonly right: AnyExpr\n readonly collation: Option.Option<Collation>\n}\n\n/**\n * A call of an operator whose result is a boolean, so it stands where any\n * predicate does: in `and`, `or` and `not`, a guard, an invariant. `expansion`\n * is the predicate it means, built when it was called.\n */\nexport interface TestPredicate {\n readonly _tag: 'Test'\n readonly operator: OperatorDescriptor\n readonly args: ReadonlyArray<Operandish>\n readonly expansion: Option.Option<Predicate>\n /** The collation it compares text under, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/**\n * Anything an operation can be given: a scalar, or a predicate where a boolean\n * is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the\n * second case, and it is how a query depends on an input without branching on\n * it.\n */\nexport type Operandish = AnyExpr | Predicate\n\n/**\n * A field, a `one` relation (the id it points at), a scalar already built from\n * one, or a predicate used as a boolean.\n */\ntype Operand<T> = OwnOperand<T> | OneRelation\n\n/** A field, a scalar, or a predicate: what an order term takes, since no list orders by a link. */\ntype OwnOperand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> | Predicate\n\n/**\n * Type-only: the Entities a predicate's fields belong to, by name, so\n * `Query.where` can refuse one over another Entity where it is written. Never\n * set at run time; a predicate built without it (typed plain `Predicate`)\n * reads as unknown and is checked at run time only.\n */\nexport interface Reads<Names extends string> {\n readonly '~reads'?: Names\n}\n\n/**\n * The Entity names an operand reads: a field's own, a marked node's, none for\n * a value or an input. A node with no marker (a `Predicate` typed plainly)\n * reads as `string`, unknown.\n */\nexport type ReadsOf<X> =\n X extends EntityField<infer Name, string, Schema.Constraint>\n ? Name\n : X extends EntityRelation<infer Name, string, AnyEntity, 'one', boolean>\n ? Name\n : X extends PlainValue | { readonly _tag: 'Literal' | 'Input' | 'Viewer' | 'Now' }\n ? never\n : X extends { readonly '~reads'?: infer Names }\n ? unknown extends Names\n ? string\n : Names extends string\n ? Names\n : never\n : never\n\n/**\n * Nothing when a query's predicates read its own Entity, none, or one unknown\n * to the type (checked at run time instead); else a failure naming both.\n */\ntype OverEntity<\n Names extends string,\n Name extends string,\n What extends string,\n> = string extends Names\n ? unknown\n : [Names] extends [Name]\n ? unknown\n : Invalid<`foldkit-entity: ${What} reads ${Exclude<Names, Name>}, but the query is from ${Name}`>\n\n/** A plain value, which `Expr.eq` takes on the right only. */\ntype PlainValue = string | number | boolean | bigint | null\n\n/** A compile-time failure whose type is the sentence that says what to do. */\nexport interface Invalid<Message extends string> {\n readonly '~invalid': Message\n}\n\n/** What an operand is worth, so a comparison's other side is checked against it. */\nexport type ValueOf<E> =\n E extends EntityField<string, string, infer S>\n ? Schema.Schema.Type<S>\n : E extends EntityRelation<string, string, infer Target, 'one', infer Optional>\n ? IdOf<Target> | (Optional extends true ? null : never)\n : E extends Predicate\n ? boolean\n : E extends Expr<infer T>\n ? T\n : never\n\n/**\n * A field or scalar whose value is text, or absent text.\n *\n * `Expr.contains` is a case-insensitive **text** search that compiles to\n * `lower(column) like lower(?)`. Over a number that is nonsense which reaches\n * the database — SQLite coerces and answers something, Postgres raises — so\n * the operand is constrained here rather than discovered there.\n *\n * Null belongs in the type, because a nullable text column is a real and\n * documented case: a null contains nothing, not even the empty string, so its\n * rows drop out of a search that would otherwise match everything.\n *\n * Written as a **constraint on the type parameter** rather than as a check\n * intersected onto the parameter (the `Invalid` idiom `foldkit-remote` uses for\n * an unregistered descriptor). That idiom compares an already-resolved indexed\n * access; here the check would be a conditional over the type being inferred,\n * and inference falls back to the constraint — whose `Expr<any>` branch makes\n * the check vacuously true, so every operand passes. A constraint cannot be\n * defeated that way.\n */\nexport type TextOperand =\n | EntityField<string, string, Schema.Constraint & Schema.Codec<string | null, any, any, any>>\n | Expr<string>\n | Expr<string | null>\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && '_tag' in value ? value._tag : undefined\n\n/**\n * An Entity's field and a `FieldExpr` are the same three members under the same\n * tag — the Entity's carries `metadata` besides — so this reads either and is\n * idempotent on its own output. Nothing needs to tell them apart, which is\n * better than telling them apart by which extra member happens to be present.\n */\n/**\n * Every node is frozen as it is made, so a query built from it stays the value\n * it was when `Query.where` checked it: nothing can swap a field or a literal\n * in afterwards. It also means no node can come to contain itself. A literal's\n * own payload is the caller's; the kernel compares scalars.\n */\nconst node = <T extends object>(value: T): T => Object.freeze(value)\n\nconst literal = <T>(value: T): LiteralExpr<T> => node({ _tag: 'Literal', value })\n\nconst fieldExpr = (field: EntityField<string, string, Schema.Constraint>): FieldExpr<unknown> =>\n node({\n _tag: 'Field',\n owner: field.owner,\n key: field.key,\n schema: field.schema as unknown as Schema.Codec<unknown, unknown>,\n collation: Option.orElse(Collation.declared(field.metadata), () =>\n field.key === 'id' ? Option.some(Collation.binary) : Option.none(),\n ),\n })\n\n/**\n * A `one` relation read as a value: the id of the row it points at, null for\n * none. It is the member the row holds under the relation's key, so it is a\n * field of the owner to every interpreter: a row given to one holds it as that\n * id, and SQL reads the column the relation is stored on.\n */\nconst linkExpr = (relation: OneRelation): FieldExpr<unknown> =>\n node({\n _tag: 'Field',\n owner: relation.owner,\n key: relation.key,\n // A ref's id travels as text, as `Expr.viewer`'s does, so the two compare.\n schema: (relation.optional\n ? Schema.NullOr(Schema.String)\n : Schema.String) as unknown as Schema.Codec<unknown, unknown>,\n // Nothing orders by one: a list refuses it, and a comparison takes an ordered operand.\n collation: Option.none(),\n })\n\nconst predicateTags = new Set([\n 'Eq',\n 'Null',\n 'Contains',\n 'In',\n 'And',\n 'Or',\n 'Not',\n 'Compare',\n 'Test',\n 'Exists',\n])\n\n/** Whether a value is a predicate, and so usable where a boolean is wanted. */\nexport const isPredicate = (value: unknown): value is Predicate =>\n predicateTags.has(tagOf(value) as string)\n\n/**\n * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is\n * itself, and anything else is the constant it is.\n */\nconst toOperand = <T>(value: Operand<T> | T): Operandish => {\n const tag = tagOf(value)\n // An `EntityField` and a `FieldExpr` share the tag. A `FieldExpr` is already\n // built, its collation with it, which its field's metadata no longer holds.\n if (tag === 'Field' && !Object.hasOwn(value as object, 'metadata')) {\n return value as FieldExpr<unknown>\n }\n if (tag === 'Field') {\n return fieldExpr(value as EntityField<string, string, Schema.Constraint>)\n }\n if (tag === 'Relation') {\n const relation = value as EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n if (relation.cardinality !== 'one') {\n throw new Error(\n `[foldkit-entity] ${relation.owner.name}.${relation.key} is a many relation, which holds no one value; ask Expr.exists of the relation that points back`,\n )\n }\n return linkExpr(relation as OneRelation)\n }\n if (\n tag === 'Literal' ||\n tag === 'Input' ||\n tag === 'Next' ||\n tag === 'Call' ||\n tag === 'Viewer' ||\n tag === 'Now' ||\n tag === 'Path' ||\n tag === 'ViewerPath' ||\n predicateTags.has(tag as string)\n ) {\n return value as Operandish\n }\n return literal(value)\n}\n\n/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */\nconst toExpr = <T>(value: Operand<T> | T, step: string): AnyExpr => {\n const operand = toOperand(value)\n if (isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`,\n )\n }\n return operand\n}\n\n/**\n * Every operation the kernel has. An interpreter declares which of them it\n * runs, and a body needing one it does not is refused rather than answered\n * wrongly — see `Query.unsupported`.\n */\nexport type Operation =\n | 'eq'\n | 'isNull'\n | 'isNotNull'\n | 'contains'\n | 'in'\n | 'and'\n | 'or'\n | 'not'\n | 'compare'\n | 'next'\n | 'viewer'\n | 'now'\n | 'path'\n | 'exists'\n\n/** One field an expression reads: its Entity's name and key, and the identity that owns it. */\nexport interface FieldDependency {\n /** The owning Entity's name, for display; two Entities may share one. */\n readonly entity: string\n readonly key: string\n /** Which Entity it is. Two defined with the same name are two entries. */\n readonly owner: EntityIdentity<string>\n}\n\n/** Which fields and inputs an expression reads, and which operations it uses. */\nexport interface Dependencies {\n /** One entry per distinct field of each Entity identity. */\n readonly fields: ReadonlyArray<FieldDependency>\n /** Each field read as the row a write would leave holds it (`Next`), one entry each. */\n readonly next: ReadonlyArray<FieldDependency>\n /** One entry per distinct input key. */\n readonly inputs: ReadonlyArray<string>\n /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */\n readonly operations: ReadonlyArray<Operation>\n /** Each operator it calls, once per descriptor, defined or not. */\n readonly operators: ReadonlyArray<OperatorDescriptor>\n /**\n * Each path, exists and path from the viewer, once each: what it reads lies\n * in other rows, so none of it is in `fields`. An exists' filter's inputs,\n * operations and operators are in the lists above.\n */\n readonly reaches: ReadonlyArray<PathExpr<unknown> | ExistsPredicate | ViewerPathExpr<unknown>>\n}\n\n/**\n * What a query reads, with each field's role. A change to a `predicate` field\n * can move a row into or out of the result; a change to an `order` field can\n * move it within. A field in both is in both; `fields` is their union.\n */\nexport interface QueryDependencies extends Dependencies {\n readonly predicate: ReadonlyArray<FieldDependency>\n readonly order: ReadonlyArray<FieldDependency>\n}\n\n/**\n * A field or scalar whose value orders: a number, text, a date (which orders by\n * its encoded form), or one of those absent. A boolean does not order here.\n * A constraint on the type parameter, as `TextOperand` is, so inference cannot\n * fall back past it.\n */\nexport type OrderedOperand =\n | EntityField<\n string,\n string,\n Schema.Constraint & Schema.Codec<number | string | Date | null, any, any, any>\n >\n | Expr<number>\n | Expr<number | null>\n | Expr<string>\n | Expr<string | null>\n | Expr<Date>\n | Expr<Date | null>\n\n/** How values encoded by `ast` order: as numbers, as text, or not at all. */\nconst orderKindOf = (ast: SchemaAST.AST): 'number' | 'text' | 'none' => {\n if (SchemaAST.isNumber(ast)) return 'number'\n if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return 'text'\n if (SchemaAST.isLiteral(ast)) {\n if (typeof ast.literal === 'number') return 'number'\n if (typeof ast.literal === 'string') return 'text'\n return 'none'\n }\n if (SchemaAST.isUnion(ast)) {\n // A null orders nowhere, as every comparison of it is unknown.\n const kinds = new Set(ast.types.filter(member => !SchemaAST.isNull(member)).map(orderKindOf))\n const [only] = kinds\n return kinds.size === 1 && only !== undefined ? only : 'none'\n }\n return 'none'\n}\n\n/** How a literal orders; a null orders as anything, since comparing it is unknown. */\nconst literalKind = (value: unknown): 'number' | 'text' | 'none' | 'null' => {\n if (value === null) return 'null'\n if (typeof value === 'number') return 'number'\n if (typeof value === 'string') return 'text'\n return 'none'\n}\n\n/** How a side orders, read from its encoded form. */\nconst sideKind = (side: AnyExpr): 'number' | 'text' | 'none' | 'null' =>\n Match.value(side).pipe(\n Match.tagsExhaustive({\n Field: field => orderKindOf(Schema.toEncoded(field.schema).ast),\n Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),\n Input: input => orderKindOf(Schema.toEncoded(input.schema).ast),\n Literal: ({ value }) => literalKind(value),\n Call: ({ operator }) => orderKindOf(Schema.toEncoded(operator.output).ast),\n Viewer: ({ schema }) => orderKindOf(Schema.toEncoded(schema).ast),\n Now: ({ schema }) => orderKindOf(Schema.toEncoded(schema).ast),\n Path: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),\n ViewerPath: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),\n }),\n )\n\n/**\n * How a comparison's text compares: the collation given, else the field's\n * declared one. Text orders differently by backend (SQLite's `BINARY`, the\n * Postgres database's locale, JavaScript's UTF-16 units), so it is compared\n * only under `binary` or `asciiFold`, which every interpreter here agrees on,\n * and only against a field, whose collation it is. Values that order\n * intrinsically, numbers, need none.\n */\nconst collationFor = (\n step: CompareOperator,\n left: AnyExpr,\n right: AnyExpr,\n given: Option.Option<Collation>,\n): Option.Option<Collation> => {\n const kinds = new Set([sideKind(left), sideKind(right)].filter(kind => kind !== 'null'))\n if (kinds.has('none') || kinds.size > 1) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: only numbers with numbers, or text with text, order alike in every interpreter, as stored`,\n )\n }\n if (!kinds.has('text')) return Option.none()\n // The sides that can say how text orders: a field, as declared, or a call, as its\n // operator's rule carries one. A literal or an input says nothing.\n const fields = [left, right].flatMap(side =>\n Match.value(side).pipe(\n Match.tagsExhaustive({\n Field: field => [{ name: `${field.owner.name}.${field.key}`, collation: field.collation }],\n Next: ({ field }) => [\n { name: `${field.owner.name}.${field.key}`, collation: field.collation },\n ],\n Call: call => [{ name: showExpr(call), collation: call.collation }],\n Path: path => [{ name: showExpr(path), collation: path.field.collation }],\n ViewerPath: path => [{ name: showExpr(path), collation: path.field.collation }],\n Literal: () => [],\n Input: () => [],\n Viewer: () => [],\n Now: () => [],\n }),\n ),\n )\n const [first] = fields\n if (first === undefined) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: text compared with no field, nor a call carrying a collation, to say how it orders`,\n )\n }\n const named = fields.map(field => field.name).join(' and ')\n const collations = Option.match(given, {\n onSome: collation => [collation],\n onNone: () =>\n fields.map(field =>\n Option.getOrElse(field.collation, () => {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${field.name} is text with no declared collation, so backends would order it differently; declare Collation.binary or Collation.asciiFold on it, or pass one`,\n )\n }),\n ),\n })\n const [collation] = collations\n if (collation === undefined || collations.some(each => each._tag !== collation._tag)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${named} declare different collations; pass one to compare them by`,\n )\n }\n return Match.value(collation).pipe(\n Match.tagsExhaustive({\n Binary: () => Option.some(collation),\n AsciiFold: () => Option.some(collation),\n Locale: ({ locale }) => {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${named} compares by the backend's \"${locale}\" collation, which only that backend has`,\n )\n },\n }),\n )\n}\n\n/** `Expr.lt` and its three siblings: the operator fixed, the sides typed alike. */\nconst comparison =\n (operator: CompareOperator) =>\n <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(\n left: L,\n right: R,\n options: { readonly collation?: Collation | undefined } = {},\n ): ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>> => {\n const leftSide = toExpr<unknown>(left, operator)\n const rightSide = toExpr<unknown>(right, operator)\n return node({\n _tag: 'Compare',\n operator,\n left: leftSide,\n right: rightSide,\n collation: collationFor(\n operator,\n leftSide,\n rightSide,\n Option.fromUndefinedOr(options.collation),\n ),\n })\n }\n\n/** A connective's operands, each checked to be a predicate, with one of the same kind flattened in. */\nconst connected = (\n step: 'and' | 'or',\n kind: 'And' | 'Or',\n given: ReadonlyArray<unknown>,\n): Arr.NonEmptyReadonlyArray<Predicate> => {\n const operands = given.flatMap((operand): ReadonlyArray<Predicate> => {\n if (!isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: every operand is a predicate; compare a value with Expr.eq first`,\n )\n }\n return Match.value(operand).pipe(\n Match.tags({\n And: and => (kind === 'And' ? and.operands : [and]),\n Or: or => (kind === 'Or' ? or.operands : [or]),\n }),\n Match.orElse(() => [operand]),\n )\n })\n // Flattening copies a shared operand's list, so `or(x, x)` built thirty deep\n // would be 2^30 operands before the budget ever counts them.\n if (operands.length > maxQueryNodes) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: more than ${maxQueryNodes} operands, the most a query's predicates may hold`,\n )\n }\n if (!Arr.isReadonlyArrayNonEmpty(operands)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: no operands, which would match ${step === 'and' ? 'every row' : 'no row'}; check a list is non-empty before spreading it`,\n )\n }\n return operands\n}\n\n/** `Expr.and` and `Expr.or`: one operand is that operand, and two or more are one node. */\ninterface Connective<Node extends Predicate> {\n <P extends Predicate>(only: P): P\n <A extends Predicate, B extends Predicate, Rest extends ReadonlyArray<Predicate>>(\n first: A,\n second: B,\n ...rest: Rest\n ): Node & Reads<ReadsOf<A> | ReadsOf<B> | ReadsOf<Rest[number]>>\n (...operands: Arr.NonEmptyReadonlyArray<Predicate>): Predicate\n}\n\nconst connective =\n <Node extends AndPredicate | OrPredicate>(step: 'and' | 'or', kind: Node['_tag']) =>\n (...given: ReadonlyArray<Predicate>): Predicate => {\n const operands = connected(step, kind, given)\n return operands.length === 1 ? operands[0] : node({ _tag: kind, operands } as Node)\n }\n\n/** A schema's stored form, which is what an operator takes and gives. */\ntype StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>\n\n/**\n * One argument an operator may be called with: a field or scalar stored as the\n * input's stored type, a predicate where it takes a boolean, or a plain value.\n */\nexport type ArgumentOf<S extends Schema.Top> =\n | EntityField<string, string, Schema.Constraint & Schema.Codec<any, StoredOf<S>, any, any>>\n | Expr<StoredOf<S>>\n | (boolean extends StoredOf<S> ? Predicate : never)\n | StoredOf<S>\n\n/** What `definedAs` is handed for one argument: the argument as a node. */\nexport type ParameterOf<S extends Schema.Top> =\n | Expr<StoredOf<S>>\n | (boolean extends StoredOf<S> ? Predicate : never)\n\n/** A call's node: a predicate for a boolean result, a scalar for anything else. */\ntype CallOf<Out extends Schema.Top> = [StoredOf<Out>] extends [boolean]\n ? TestPredicate\n : CallExpr<StoredOf<Out>>\n\n/** What `definedAs` builds: a predicate for a boolean result, a scalar otherwise. */\ntype BodyOf<Out extends Schema.Top> = [StoredOf<Out>] extends [boolean]\n ? Predicate\n : Expr<StoredOf<Out>>\n\n/**\n * An operator: called like a function, it builds a node that holds `descriptor`\n * and its arguments. See `Expr.operator`.\n */\nexport interface Operator<In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top> {\n <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]> }>(\n ...args: A\n ): CallOf<Out> & Reads<ReadsOf<A[number]>>\n /**\n * A call comparing text under the collation given, rather than its text\n * arguments' declared one: for an operator whose `collation` is `operands`\n * or `required`, as `Expr.lt(field, value, { collation })` is.\n */\n <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]> }>(\n ...args: [...A, CallOptions]\n ): CallOf<Out> & Reads<ReadsOf<A[number]>>\n readonly descriptor: OperatorDescriptor\n}\n\n/** What a call may say past its arguments. */\nexport interface CallOptions {\n /** The collation it compares text under, in place of its arguments' declared one. */\n readonly collation: Collation\n}\n\nconst collationTags = new Set(['Binary', 'AsciiFold', 'Locale'])\n\n/** A call's last value, when it is one past the arguments: its options, checked. */\nconst callOptionsOf = (id: string, value: unknown): Collation => {\n const collation =\n typeof value === 'object' && value !== null && Object.hasOwn(value, 'collation')\n ? (value as { readonly collation: unknown }).collation\n : undefined\n if (!collationTags.has(tagOf(collation) as string)) {\n throw new Error(\n `[foldkit-entity] ${id}: a value past its arguments is \\`{ collation }\\`, a Collation`,\n )\n }\n return collation as Collation\n}\n\n/** A collation a call was given: one its operator compares by, and portable where required. */\nconst givenCollation = (\n id: string,\n descriptor: OperatorDescriptor,\n collation: Collation,\n): Option.Option<Collation> => {\n if (Option.isSome(descriptor.definedAs) || descriptor.collation === 'none') {\n throw new Error(`[foldkit-entity] ${id}: takes no collation; it compares no text of its own`)\n }\n // No call carries a locale: the client could not run it, and SQL compiles none.\n if (collation._tag === 'Locale') {\n throw new Error(\n `[foldkit-entity] ${id}: compares by the backend's \"${collation.locale}\" collation, which only that backend has`,\n )\n }\n return Option.some(collation)\n}\n\n/** Namespaced, lower camel case: `cms.published`, `text.startsWith`. */\nconst operatorId = /^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)+$/\n\n/**\n * Why `law` cannot be declared of an operator of this shape, if it cannot: an\n * equation over two arguments of a unary operator, a witness that does not\n * decode as the argument it stands in, or a collation law of an operator\n * whose text keeps none.\n */\nconst lawProblem = (\n law: Law,\n input: ReadonlyArray<Schema.Top>,\n output: Schema.Top,\n collation: OperatorDescriptor['collation'],\n): Option.Option<string> => {\n const name = Law.describe(law).kind\n const binary = (): Option.Option<string> =>\n input.length === 2\n ? Option.none()\n : Option.some(\n `${name} is a law of an operator of two arguments, and this one takes ${input.length}`,\n )\n const decodes = (value: unknown, schema: Schema.Top, what: string): Option.Option<string> =>\n Schema.is(Schema.toEncoded(schema))(value)\n ? Option.none()\n : Option.some(`${name}'s ${what} ${JSON.stringify(value)} does not decode as its schema`)\n const sides = (value: unknown, side: Side): Option.Option<string> =>\n Option.orElse(binary(), () =>\n Option.orElse(\n side === 'right' ? Option.none() : decodes(value, input[0]!, 'left witness'),\n () => (side === 'left' ? Option.none() : decodes(value, input[1]!, 'right witness')),\n ),\n )\n return Law.$match(law, {\n Associative: binary,\n Commutative: binary,\n Idempotent: binary,\n Identity: ({ value, side }) => sides(value, side),\n Absorbing: ({ value, side }) => sides(value, side),\n Inverse: ({ other, identity }) =>\n Option.orElse(binary(), () =>\n other.descriptor.input.length === 1\n ? decodes(identity, output, 'identity')\n : Option.some(`${name}'s other operator takes one argument`),\n ),\n Distributes: ({ over }) =>\n Option.orElse(binary(), () =>\n over.descriptor.input.length === 2\n ? Option.none()\n : Option.some(`${name} is over an operator of two arguments`),\n ),\n Monotonic: ({ position }) =>\n Number.isSafeInteger(position) && position >= 0 && position < input.length\n ? Option.none()\n : Option.some(`${name}'s position ${position} is not an argument's`),\n PreservesCollation: () =>\n collation === 'operands'\n ? Option.none()\n : Option.some(`${name} is a law of an operator declared \\`collation: 'operands'\\``),\n })\n}\n\n/** Whether a schema's stored form is a boolean, which makes its operator a predicate. */\nconst storedAsBoolean = (schema: Schema.Top): boolean =>\n SchemaAST.isBoolean(Schema.toEncoded(schema).ast)\n\n/** What a schema stores, null aside: one kind an argument is checked by, or `other`. */\nconst storedKindOf = (schema: Schema.Top): 'number' | 'text' | 'boolean' | 'other' => {\n const present = SchemaShape.present(Schema.toEncoded(schema).ast)\n if (present.length === 0) return 'other'\n if (present.every(SchemaAST.isNumber)) return 'number'\n if (present.every(SchemaShape.isText)) return 'text'\n if (present.every(SchemaAST.isBoolean)) return 'boolean'\n return 'other'\n}\n\n/** The schema a scalar's values are stored by. */\nconst scalarSchema = (scalar: AnyExpr): Schema.Top =>\n Match.value(scalar).pipe(\n Match.tagsExhaustive({\n Field: field => field.schema,\n Next: ({ field }) => field.schema,\n Input: input => input.schema,\n Literal: () => Schema.Unknown,\n Call: ({ operator }) => operator.output,\n Viewer: ({ schema }) => schema,\n Now: ({ schema }) => schema,\n Path: ({ field }) => field.schema,\n ViewerPath: ({ field }) => field.schema,\n }),\n )\n\n/** Every field, field after a write, and input an expression reads, as keys to compare. */\nconst readKeys = (...nodes: ReadonlyArray<Operandish>): ReadonlySet<string> => {\n const read = dependenciesOf(...nodes)\n const named = (prefix: string, fields: ReadonlyArray<FieldDependency>) =>\n fields.map(field => `${prefix}${field.entity}.${field.key}`)\n return new Set([\n ...named('', read.fields),\n ...named('next ', read.next),\n ...read.inputs.map(key => `$${key}`),\n ])\n}\n\n/** One argument, checked against the schema it is passed for, as a node. */\nconst argumentFor = (\n id: string,\n position: number,\n schema: Schema.Top,\n value: unknown,\n): Operandish => {\n const arg = toOperand(value)\n const fail = (what: string) => {\n throw new Error(`[foldkit-entity] ${id}: argument ${position + 1} ${what}`)\n }\n if (isPredicate(arg)) {\n // As `ArgumentOf` types it: wherever both booleans are stored, null beside them or not.\n const stored = Schema.is(Schema.toEncoded(schema))\n if (!stored(true) || !stored(false))\n fail('is a predicate, but the operator does not take a boolean')\n return arg\n }\n if (arg._tag === 'Literal') {\n if (!Schema.is(Schema.toEncoded(schema))(arg.value)) {\n fail(`is ${JSON.stringify(arg.value)}, which the operator's input schema does not admit`)\n }\n return arg\n }\n const wanted = storedKindOf(schema)\n const given = storedKindOf(scalarSchema(arg))\n if (wanted !== 'other' && given !== 'other' && given !== wanted) {\n fail(`is stored as ${given}, but the operator takes ${wanted}`)\n }\n return arg\n}\n\n/** A scalar's collation: a field's declared one, or a call's. */\nconst collationOf = (scalar: AnyExpr): Option.Option<Collation> =>\n Match.value(scalar).pipe(\n Match.tagsExhaustive({\n Field: field => field.collation,\n Next: ({ field }) => field.collation,\n Call: call => call.collation,\n Literal: () => Option.none<Collation>(),\n Input: () => Option.none<Collation>(),\n Viewer: () => Option.none<Collation>(),\n Now: () => Option.none<Collation>(),\n Path: ({ field }) => field.collation,\n ViewerPath: ({ field }) => field.collation,\n }),\n )\n\n/**\n * The collation a primitive call compares text under: the one its collated\n * text arguments share. A literal or an input carries none and does not vote.\n * `required` refuses a call with none, or with a backend's locale.\n */\nconst callCollation = (\n id: string,\n rule: OperatorDescriptor['collation'],\n args: ReadonlyArray<Operandish>,\n): Option.Option<Collation> => {\n if (rule === 'none') return Option.none()\n const fail = (what: string): never => {\n throw new Error(`[foldkit-entity] ${id}: ${what}`)\n }\n // Named only in a refusal: rendering each voter on every call is exponential in a\n // nesting of calls that share their arguments.\n const voters = args.flatMap(arg =>\n isPredicate(arg) || arg._tag === 'Literal' || arg._tag === 'Input' || sideKind(arg) !== 'text'\n ? []\n : [{ arg, collation: collationOf(arg) }],\n )\n const collations = voters.flatMap(({ arg, collation }) =>\n Option.match(collation, {\n onSome: each => [each],\n onNone: (): ReadonlyArray<Collation> =>\n rule === 'required'\n ? fail(\n `${showExpr(arg)} is text with no declared collation, so backends would compare it differently; declare Collation.binary or Collation.asciiFold on it`,\n )\n : [],\n }),\n )\n const [shared] = collations\n if (shared === undefined) {\n return rule === 'required'\n ? fail('compares text with no field or call holding a collation')\n : Option.none()\n }\n if (collations.some(each => each._tag !== shared._tag)) {\n fail(`${voters.map(voter => showExpr(voter.arg)).join(' and ')} declare different collations`)\n }\n if (shared._tag === 'Locale') {\n fail(`compares by the backend's \"${shared.locale}\" collation, which a call cannot carry`)\n }\n return Option.some(shared)\n}\n\n/** Builds an operator: checks what it is given once, then each call. */\nconst makeOperator = (\n id: string,\n options: {\n readonly input: ReadonlyArray<Schema.Top>\n readonly output: Schema.Top\n readonly version?: number | undefined\n readonly description?: string | undefined\n readonly definedAs?: ((...args: ReadonlyArray<Operandish>) => unknown) | undefined\n readonly nulls?: OperatorDescriptor['nulls'] | undefined\n readonly collation?: OperatorDescriptor['collation'] | undefined\n readonly laws?: ReadonlyArray<Law> | undefined\n },\n): Operator<ReadonlyArray<Schema.Top>, Schema.Top> => {\n const fail = (what: string): never => {\n throw new Error(`[foldkit-entity] Expr.operator(\"${id}\"): ${what}`)\n }\n if (!operatorId.test(id)) {\n fail('an id is namespaced lower camel case, as `cms.published`')\n }\n if (id.startsWith('foldkit.')) fail('ids under `foldkit.` are reserved')\n const version = options.version ?? 1\n if (!Number.isSafeInteger(version) || version < 1) fail('a version is a positive integer')\n if (!Array.isArray(options.input) || !options.input.every(Schema.isSchema)) {\n fail('`input` is one schema per argument')\n }\n if (!Schema.isSchema(options.output)) fail('`output` is a schema')\n const definedAs = Option.fromUndefinedOr(options.definedAs)\n if (Option.isSome(definedAs) && typeof definedAs.value !== 'function') {\n fail('`definedAs` builds what a call means')\n }\n // A defined operator means its body, null and text alike: it declares neither.\n if (\n Option.isSome(definedAs) &&\n (options.nulls !== undefined || options.collation !== undefined)\n ) {\n fail(\"a defined operator means its body, so `nulls` and `collation` are its body's\")\n }\n const nulls = options.nulls ?? 'strict'\n const collation = options.collation ?? 'none'\n if (nulls !== 'strict' && nulls !== 'handled') fail(\"`nulls` is 'strict' or 'handled'\")\n if (collation !== 'none' && collation !== 'operands' && collation !== 'required') {\n fail(\"`collation` is 'none', 'operands' or 'required'\")\n }\n const input = Object.freeze([...options.input])\n const predicate = storedAsBoolean(options.output)\n if (collation === 'operands' && orderKindOf(Schema.toEncoded(options.output).ast) !== 'text') {\n fail(\"`collation: 'operands'` describes a text result, and this one is not text\")\n }\n const laws = Object.freeze([...(options.laws ?? [])])\n for (const law of laws) {\n Option.match(lawProblem(law, input, options.output, collation), {\n onNone: () => undefined,\n onSome: fail,\n })\n }\n const descriptor: OperatorDescriptor = Object.freeze({\n _tag: 'Operator',\n id,\n version,\n description: Option.fromUndefinedOr(options.description),\n input,\n output: options.output,\n definedAs: definedAs as OperatorDescriptor['definedAs'],\n nulls,\n collation,\n laws,\n })\n /** A defined call's expansion, checked: of its output's kind, reading only its arguments. */\n const expand = (\n body: (...args: ReadonlyArray<Operandish>) => Operandish,\n args: ReadonlyArray<Operandish>,\n ): Operandish => {\n const expansion = toOperand(body(...args))\n if (predicate !== isPredicate(expansion)) {\n throw new Error(\n `[foldkit-entity] ${id}: its output is ${predicate ? 'a boolean, so `definedAs` returns a predicate' : 'not a boolean, so `definedAs` returns a scalar'}`,\n )\n }\n // An expansion reading what its arguments do not would hide a read from\n // anyone asking what the call depends on: Guard's checks, Remote's matching.\n const allowed = readKeys(...args)\n const hidden = [...readKeys(expansion)].filter(key => !allowed.has(key))\n if (hidden.length > 0) {\n throw new Error(\n `[foldkit-entity] ${id}: \\`definedAs\\` reads ${hidden.join(', ')}, which no argument holds; pass it as one`,\n )\n }\n return expansion\n }\n const call = (...written: ReadonlyArray<unknown>) => {\n // One value past the arguments is the call's options.\n const explicit =\n written.length === input.length + 1\n ? Option.some(callOptionsOf(id, written[written.length - 1]))\n : Option.none<Collation>()\n const given = Option.isSome(explicit) ? written.slice(0, -1) : written\n if (given.length !== input.length) {\n throw new Error(\n `[foldkit-entity] ${id}: takes ${input.length} argument${input.length === 1 ? '' : 's'}, given ${given.length}`,\n )\n }\n const args = Object.freeze(\n given.map((value, position) => argumentFor(id, position, input[position]!, value)),\n )\n const expansion = Option.map(descriptor.definedAs, body => expand(body, args))\n // A collation given wins; else a defined call's text compares as its body\n // does, and a primitive one's by its rule.\n const carried = Option.match(explicit, {\n onSome: each => givenCollation(id, descriptor, each),\n onNone: () =>\n Option.match(expansion, {\n onSome: body => (isPredicate(body) ? Option.none<Collation>() : collationOf(body)),\n onNone: () => callCollation(id, collation, args),\n }),\n })\n return predicate\n ? node<TestPredicate>({\n _tag: 'Test',\n operator: descriptor,\n args,\n expansion: expansion as Option.Option<Predicate>,\n collation: carried,\n })\n : node<CallExpr<unknown>>({\n _tag: 'Call',\n operator: descriptor,\n args,\n expansion: expansion as Option.Option<AnyExpr>,\n collation: carried,\n })\n }\n return Object.freeze(Object.assign(call, { descriptor })) as unknown as Operator<\n ReadonlyArray<Schema.Top>,\n Schema.Top\n >\n}\n\n/** Each defined call replaced by its expansion, deeply; built once per node. */\nconst expandedCache = new WeakMap<object, AnyExpr | Predicate>()\n\nconst expandedScalar = (scalar: AnyExpr): AnyExpr => {\n const known = expandedCache.get(scalar)\n if (known !== undefined) return known as AnyExpr\n const result =\n scalar._tag === 'Call'\n ? Option.match(scalar.expansion, {\n onSome: expandedScalar,\n // An operator with no definition stays, for an interpreter to run or refuse by\n // name; a defined one among its arguments is expanded all the same.\n onNone: () => node<AnyExpr>({ ...scalar, args: scalar.args.map(expandedSide) }),\n })\n : scalar\n expandedCache.set(scalar, result)\n return result\n}\n\nconst expandedSide = (side: Operandish): Operandish =>\n isPredicate(side) ? expandedPredicate(side) : expandedScalar(side)\n\nconst expandedPredicate = (predicate: Predicate): Predicate => {\n const known = expandedCache.get(predicate)\n if (known !== undefined) return known as Predicate\n const result: Predicate = Match.value(predicate).pipe(\n Match.tagsExhaustive({\n Eq: eq =>\n node<Predicate>({ ...eq, left: expandedSide(eq.left), right: expandedSide(eq.right) }),\n Null: nul => node<Predicate>({ ...nul, operand: expandedScalar(nul.operand) }),\n Contains: contains =>\n node<Predicate>({\n ...contains,\n value: expandedScalar(contains.value),\n search: expandedSide(contains.search),\n }),\n In: inPredicate =>\n node<Predicate>({\n ...inPredicate,\n value: expandedScalar(inPredicate.value),\n among: expandedScalar(inPredicate.among),\n }),\n And: and => node<Predicate>({ ...and, operands: Arr.map(and.operands, expandedPredicate) }),\n Or: or => node<Predicate>({ ...or, operands: Arr.map(or.operands, expandedPredicate) }),\n Not: not => node<Predicate>({ ...not, operand: expandedPredicate(not.operand) }),\n Compare: compare =>\n node<Predicate>({\n ...compare,\n left: expandedScalar(compare.left),\n right: expandedScalar(compare.right),\n }),\n Test: test =>\n Option.match(test.expansion, {\n onSome: expandedPredicate,\n onNone: () => node<Predicate>({ ...test, args: test.args.map(expandedSide) }),\n }),\n Exists: exists =>\n node<Predicate>({ ...exists, where: Option.map(exists.where, expandedPredicate) }),\n }),\n )\n expandedCache.set(predicate, result)\n return result\n}\n\n/** `Expr.path`'s two starts: a relation of the judged row, or the viewer's row. */\ninterface PathOf {\n <Owner extends string, Target extends AnyEntity, E extends PathEnd<Target['name']>>(\n relation: EntityRelation<Owner, string, Target, 'one', boolean>,\n end: E,\n ): (E extends ExistsPredicate ? ExistsPredicate : PathExpr<ValueOf<E> | null>) & Reads<Owner>\n <Name extends string, E extends Exclude<PathEnd<Name>, ExistsPredicate>>(\n viewer: ViewerExpr<any, Name>,\n end: E,\n ): ViewerPathExpr<ValueOf<E> | null>\n}\n\n/**\n * The most relations one path follows. Each is a subquery in SQL and a lookup\n * in memory; the deepest rule a real app here writes follows two.\n */\nexport const maxPathLength = 4\n\n/** What a path may end at on a row of `Name`: a field, a further path, or an exists. */\nexport type PathEnd<Name extends string> =\n | EntityField<Name, string, Schema.Constraint>\n | (PathExpr<any> & Reads<Name>)\n | (ExistsPredicate & Reads<Name>)\n\n/** A value checked to be a `one` relation, or refused with what to write instead. */\nconst oneRelation = (step: 'path' | 'exists', value: unknown): OneRelation => {\n if (tagOf(value) !== 'Relation') {\n throw new Error(\n `[foldkit-entity] Expr.${step}: the first argument is a relation (Post.relations.author)`,\n )\n }\n const relation = value as EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n if (relation.cardinality !== 'one') {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${relation.owner.name}.${relation.key} is a many relation; name the one relation that points back${step === 'path' ? ', with Expr.exists' : ''}`,\n )\n }\n return relation as OneRelation\n}\n\n/** `Expr.path` from the viewer: a field of their row, or what a path from it reads. */\nconst viewerPathOf = (from: ViewerExpr<unknown>, end: unknown): ViewerPathExpr<unknown> => {\n const start = from.target()\n const onStart = (owner: EntityIdentity<string>, what: string): void => {\n if (owner.token !== start.identity.token) {\n throw new Error(\n `[foldkit-entity] Expr.path: the viewer is a ${start.name}, but ${what} is read on a ${owner.name}`,\n )\n }\n }\n return Match.value(toOperand(end)).pipe(\n Match.tag('Field', field => {\n onStart(field.owner, `${field.owner.name}.${field.key}`)\n return node<ViewerPathExpr<unknown>>({ _tag: 'ViewerPath', viewer: from, via: [], field })\n }),\n Match.tag('Path', path => {\n onStart(path.via[0].owner, showExpr(path))\n return node<ViewerPathExpr<unknown>>({\n _tag: 'ViewerPath',\n viewer: from,\n via: path.via,\n field: path.field,\n })\n }),\n Match.orElse(other => {\n throw new Error(\n `[foldkit-entity] Expr.path: a path from the viewer ends at a field or a path, not ${showExpr(other)}`,\n )\n }),\n )\n}\n\n/** `Expr.path`: `relation` followed first, then whatever `end` reads, checked to be on its target. */\nconst pathOf = (relation: unknown, end: unknown): PathExpr<unknown> | ExistsPredicate => {\n if (tagOf(relation) === 'Viewer')\n return viewerPathOf(relation as ViewerExpr<unknown>, end) as never\n const first = oneRelation('path', relation)\n const target = first.target().identity\n const onTarget = (owner: EntityIdentity<string>, what: string): void => {\n if (owner.token !== target.token) {\n throw new Error(\n `[foldkit-entity] Expr.path: ${first.owner.name}.${first.key} reaches a ${target.name}, but ${what} is read on a ${owner.name}`,\n )\n }\n }\n const capped = <P extends PathExpr<unknown> | ExistsPredicate>(path: P): P => {\n if (path.via.length > maxPathLength) {\n throw new Error(\n `[foldkit-entity] Expr.path: ${showExpr(path)} follows more than ${maxPathLength} relations`,\n )\n }\n return node(path)\n }\n return Match.value(toOperand(end)).pipe(\n Match.tag('Field', field => {\n onTarget(field.owner, `${field.owner.name}.${field.key}`)\n return capped<PathExpr<unknown>>({ _tag: 'Path', via: [first], field })\n }),\n Match.tag('Path', path => {\n onTarget(path.via[0].owner, showExpr(path))\n return capped<PathExpr<unknown>>({ ...path, via: [first, ...path.via] })\n }),\n Match.tag('Exists', exists => {\n onTarget(existsStart(exists).owner, showExpr(exists))\n return capped<ExistsPredicate>({ ...exists, via: [first, ...exists.via] })\n }),\n Match.orElse(other => {\n throw new Error(\n `[foldkit-entity] Expr.path: a path ends at a field, a path or an exists, not ${showExpr(other)}`,\n )\n }),\n )\n}\n\n/** `Expr.exists`: the filter checked to read only the pointing row and the input. */\nconst existsOf = (relation: unknown, where: unknown): ExistsPredicate => {\n const pointing = oneRelation('exists', relation)\n const filter = Option.fromUndefinedOr(where)\n Option.map(filter, given => {\n if (!isPredicate(given)) {\n throw new Error('[foldkit-entity] Expr.exists: the filter is a predicate')\n }\n const read = dependenciesOf(given)\n const foreign = read.fields.find(field => field.owner.token !== pointing.owner.token)\n // A filter reading the row asked about, or a further row, would be a\n // correlation each interpreter has to carry: say it with a path instead.\n if (foreign !== undefined || read.next.length > 0 || read.reaches.length > 0) {\n throw new Error(\n `[foldkit-entity] Expr.exists: the filter reads ${foreign === undefined ? 'past its row' : `${foreign.entity}.${foreign.key}`}; it reads the pointing ${pointing.owner.name}'s own fields and the input`,\n )\n }\n })\n return node({\n _tag: 'Exists',\n via: [],\n relation: pointing,\n where: filter as Option.Option<Predicate>,\n })\n}\n\n/** `Expr.field`: an Entity field, or an expression refused with what to write instead. */\ninterface FieldOf {\n <Name extends string, Key extends string, S extends Schema.Constraint>(\n field: EntityField<Name, Key, S>,\n ): FieldExpr<Schema.Schema.Type<S>> & Reads<Name>\n (\n expression: Expr<unknown> &\n Invalid<'foldkit-entity: Expr.field takes an Entity field (Post.fields.title); before.x and after.x are expressions already, so compare them as they are'>,\n ): never\n}\n// The second signature only refuses, at compile time: nothing but a field reaches here.\nconst fieldOf = ((field: EntityField<string, string, Schema.Constraint>) =>\n fieldExpr(field)) as FieldOf\n\nexport const Expr = {\n /**\n * An operator, defined by what a call of it means: `definedAs` builds that\n * expression from the call's arguments, once per call, and every interpreter\n * runs it, so the operator needs no implementation anywhere. What it adds is\n * a name: a query, a guard and an invariant that mean the same thing say so,\n * and print it.\n *\n * ```ts\n * const published = Expr.operator('cms.published', {\n * input: [Schema.Unknown],\n * output: Schema.Boolean,\n * definedAs: publishedAt => Expr.isNotNull(publishedAt),\n * })\n * Query.where(published(Post.fields.publishedAt))\n * ```\n *\n * Arguments are checked by their stored form: a field, scalar or plain value\n * of the input's stored type, or a predicate where it takes a boolean. A\n * boolean output makes a call a predicate. `definedAs` may read only what its\n * arguments hold: a field or input it closes over instead is refused when\n * called, since nothing asking what the call reads would see it. The id is\n * namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)\n * changes when what it means does.\n *\n * **Without `definedAs` it is primitive**: each interpreter implements it\n * (`Operators.implement` in memory), and one without an implementation\n * refuses the body by the operator's id. `nulls` (default `strict`: a null\n * argument gives null, the implementation never sees one) and `collation`\n * (`operands`: a text result carries its text arguments' shared collation;\n * `required`: it compares text itself and needs one) are a primitive\n * operator's; a defined one means its body for both.\n */\n operator: <const In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n id: string,\n options: {\n readonly input: In\n readonly output: Out\n readonly version?: number | undefined\n readonly description?: string | undefined\n /** Equations every implementation keeps (`Law.commutative`, `Law.identity('')`, …). */\n readonly laws?: ReadonlyArray<Law> | undefined\n } & (\n | {\n readonly definedAs: (\n ...args: { readonly [K in keyof In]: ParameterOf<In[K]> }\n ) => BodyOf<Out>\n readonly nulls?: undefined\n readonly collation?: undefined\n }\n | {\n readonly definedAs?: undefined\n readonly nulls?: OperatorDescriptor['nulls'] | undefined\n readonly collation?: OperatorDescriptor['collation'] | undefined\n }\n ),\n ): Operator<In, Out> =>\n makeOperator(id, options as Parameters<typeof makeOperator>[1]) as unknown as Operator<In, Out>,\n\n /**\n * The predicate or scalar (an order term's, say) with every call of a\n * defined operator replaced by what it means, deeply. An interpreter that\n * compiles a body expands it first, and compiles exactly what was written\n * out. A call with no definition stays, for the interpreter to run or refuse\n * by name.\n */\n /**\n * Whether a constant written in these expressions is one no two backends\n * agree on, text holding a NUL or NaN, or a list holding one: SQL refuses\n * such a parameter wherever it compiles, so an interpreter refuses the run,\n * not one row.\n */\n givesUnportable: (...nodes: ReadonlyArray<AnyExpr | Predicate>): boolean => {\n const seen = new Set<object>()\n const nul = (value: unknown) =>\n (typeof value === 'string' && value.includes(String.fromCharCode(0))) ||\n (typeof value === 'number' && Number.isNaN(value))\n const walk = (node: AnyExpr | Predicate): boolean => {\n if (seen.has(node)) return false\n seen.add(node)\n if (node._tag === 'Literal') {\n return Array.isArray(node.value) ? node.value.some(nul) : nul(node.value)\n }\n return childrenOf(node).some(walk)\n }\n return nodes.some(walk)\n },\n\n expanded: <N extends Predicate | AnyExpr>(node: N): N extends Predicate ? Predicate : AnyExpr =>\n (isPredicate(node) ? expandedPredicate(node) : expandedScalar(node)) as never,\n\n /**\n * What these expressions need that an interpreter lacks, as `Query.unsupported`\n * says it for a query: each kernel operation `supported` does not list, then\n * each primitive operator `operators` does not implement, by name (`id`, or\n * `id@version` past the first). For anything holding expressions that is not a\n * query: a guard's rule, an invariant, a write's `when`.\n */\n unsupported: (\n nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>,\n interpreter: {\n readonly operations: ReadonlyArray<Operation>\n readonly operators: OperatorTable\n },\n ): ReadonlyArray<string> => unsupportedIn(nodes, interpreter.operations, interpreter.operators),\n\n /** A constant. Comparisons coerce a plain value, so this is rarely written. */\n literal,\n\n /**\n * A value the query is given when it runs. A definition builds these from its\n * `Input` schema; written by hand only when constructing a body directly.\n */\n input: <T>(key: string, schema: Schema.Codec<T, unknown>): InputExpr<T> =>\n node({ _tag: 'Input', key, schema }),\n\n /**\n * A field as the row a write would leave holds it: what `Entity.invariant`'s\n * builder hands out as `after`.\n */\n next: <Name extends string, Key extends string, S extends Schema.Constraint>(\n field: EntityField<Name, Key, S>,\n ): NextExpr<Schema.Schema.Type<S>> & Reads<Name> =>\n node({ _tag: 'Next', field: fieldExpr(field) }) as NextExpr<Schema.Schema.Type<S>>,\n\n /**\n * One field of one Entity, as a scalar. An expression is one already: an\n * invariant's `before.x` and `after.x` compare as they are, so wrapping one\n * is refused with that sentence.\n */\n field: fieldOf,\n\n /**\n * What the row reached through a `one` relation holds: a field of it, a\n * further path from it, or an exists asked of it. The first relation is the\n * judged row's own.\n *\n * ```ts\n * Expr.eq(Expr.path(Post.relations.author, User.fields.handle), input.handle)\n * Expr.path(Note.relations.project, Expr.path(Project.relations.org, Org.fields.plan))\n * ```\n *\n * A null link, or a row the reader may not see, reaches no row: the field\n * reads null, and an exists at the end is unknown, as SQL's scalar subquery\n * is. At most `maxPathLength` relations.\n */\n path: pathOf as PathOf,\n\n /**\n * Some row points at this one through `relation`, a `one` relation of\n * another Entity, and holds `where`, a predicate over that row's own fields\n * and the input:\n *\n * ```ts\n * // Posts whose author the reader follows.\n * Expr.path(Post.relations.author,\n * Expr.exists(Follow.relations.followee, Expr.eq(Follow.fields.followerId, input.me)))\n * ```\n *\n * Only rows the reader may see are sought. Never unknown in SQL; in memory,\n * unknown when no held row holds and the holder may lack one that would.\n */\n exists: existsOf as <\n Owner extends string,\n Target extends AnyEntity,\n W extends Predicate & Reads<Owner> = never,\n >(\n relation: EntityRelation<Owner, string, Target, 'one', boolean>,\n where?: W,\n ) => ExistsPredicate & Reads<Target['name']>,\n\n /**\n * Whoever asks, as a row of `entity`: `Expr.eq(Like.fields.userId,\n * Expr.viewer(User))`. Shaped as a `one` relation to `entity`. Its value is\n * the row's id, and null for a visitor or a viewer of another Entity, so a\n * comparison with it holds of no row. A server reads it from\n * `RemoteServer.make`'s `viewer`, a client from `Remote.make`'s.\n */\n viewer,\n\n /**\n * The time of the write, in milliseconds since the epoch, as a number field\n * stores it. A server reads its clock. A client judging a list has no\n * reading of the time the server judged it at, so such a list is the\n * server's to say.\n */\n now,\n\n /**\n * Two scalars are the same value: a field (or an expression) on the left,\n * and the value on the right, typed from it. Fields and plain values are\n * coerced, so the common form reads as it means:\n *\n * ```ts\n * Expr.eq(Post.fields.slug, input.slug)\n * Expr.eq(Post.fields.status, 'active')\n * ```\n */\n eq: <\n L extends Operand<any> | PlainValue,\n R extends (L extends PlainValue\n ? Invalid<'foldkit-entity: Expr.eq takes the field on the left and the value on the right'>\n : // A path reads null where it reaches no row, which compares as SQL's unknown.\n | ValueOf<L>\n | Expr<ValueOf<L>>\n | PathExpr<ValueOf<L> | null>\n | ViewerPathExpr<ValueOf<L> | null>\n | (boolean extends ValueOf<L> ? Predicate : never)),\n >(\n left: L,\n // The right side is typed from the left, so a plain value on the left has\n // nothing to type it by: say so, rather than that 3 is no `Operand`.\n right: R,\n ): EqPredicate & Reads<ReadsOf<L> | ReadsOf<R>> =>\n node({ _tag: 'Eq', left: toOperand(left), right: toOperand(right as never) }),\n\n /**\n * Whether a field holds no value. Its opposite is `isNotNull`; both are the\n * one node, since a query asks which of the two it means, and `is not null`\n * has no unknown for a `not` to keep.\n */\n isNull: <L extends Operand<any>>(operand: L): NullPredicate & Reads<ReadsOf<L>> =>\n node({ _tag: 'Null', operand: toExpr(operand, 'isNull'), present: false }),\n\n /** Whether a field holds a value. */\n isNotNull: <L extends Operand<any>>(operand: L): NullPredicate & Reads<ReadsOf<L>> =>\n node({ _tag: 'Null', operand: toExpr(operand, 'isNotNull'), present: true }),\n\n /**\n * Whether a text value contains `search`, anywhere in it. Containing the\n * empty string is everything, so a search box with nothing typed in it is the\n * same query as one with something — no branch, and no second query.\n *\n * **Case-insensitive**, which is what a search means, and which has to be\n * said rather than left to the interpreter: SQLite's `like` ignores case and\n * Postgres's does not, so a body that left it open would mean two things.\n * Folding is ASCII-only, because that is what `lower` does in SQLite without\n * ICU.\n *\n * **Over a column that can be null this is not the same as no filter.** A\n * null contains nothing, not even the empty string, so its rows drop out. A\n * nullable column that should match everything on an empty search says so:\n * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.\n */\n contains: <L extends TextOperand>(\n value: L,\n search: string | LiteralExpr<string> | InputExpr<string> | InputExpr<string | null>,\n ): ContainsPredicate & Reads<ReadsOf<L>> => {\n const operand = toOperand(search as never)\n // A search a row decides would have to be escaped as a pattern in SQL, which\n // no compiler here does: it is a value or an input.\n if (operand._tag !== 'Literal' && operand._tag !== 'Input') {\n throw new Error(\n `[foldkit-entity] Expr.contains: the search is ${showExpr(operand)}; search for a value or an input`,\n )\n }\n return node({ _tag: 'Contains', value: toExpr(value, 'contains'), search: operand })\n },\n\n /**\n * Whether a value is one of `among`: a list written out, or an input whose\n * value is one. Each element is compared as `eq` compares.\n *\n * ```ts\n * Expr.in(Todo.fields.projectId, input.projectIds)\n * Expr.in(Todo.fields.status, ['open', 'blocked'])\n * ```\n *\n * As SQL's `in`: a null value is unknown, as is no match against a list\n * holding a null, and an empty list matches no row. A list written out is\n * copied, so changing the array afterwards does not change the query.\n */\n in: <L extends Operand<any>>(\n value: L,\n among: ReadonlyArray<ValueOf<L>> | Expr<ReadonlyArray<ValueOf<L>>>,\n ): InPredicate & Reads<ReadsOf<L>> =>\n node({\n _tag: 'In',\n value: toExpr(value, 'in'),\n among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, 'in'),\n }),\n\n /**\n * `left` orders before `right`. Numbers compare as numbers; text compares\n * under a collation, the one given or the field's declared one, which must be\n * `binary` or `asciiFold` (so every backend agrees), and text needs a field on\n * one side. A date compares by its encoded form: as text when it is stored as\n * an ISO string, so its field declares `Collation.binary`. A null on either\n * side is unknown, so the row is matched by neither this nor its `not`.\n *\n * ```ts\n * Expr.lt(fields.cents, 1000)\n * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))\n * ```\n */\n lt: comparison('lt'),\n /** `left` orders before `right`, or with it; see `Expr.lt`. */\n lte: comparison('lte'),\n /** `left` orders after `right`; see `Expr.lt`. */\n gt: comparison('gt'),\n /** `left` orders after `right`, or with it; see `Expr.lt`. */\n gte: comparison('gte'),\n\n /**\n * Every operand holds, as one predicate to place inside another: `where`'s\n * list is already a conjunction, so this is for `or(and(a, b), c)`.\n * Unknown as SQL's `and` is: false wins over unknown, which wins over true.\n * Needs an operand; a list built at run time is checked non-empty first\n * (`Array.isReadonlyArrayNonEmpty`), since an empty `and` would match every row.\n */\n and: connective<AndPredicate>('and', 'And') as Connective<AndPredicate>,\n\n /**\n * At least one operand holds:\n *\n * ```ts\n * Expr.or(Expr.contains(fields.description, input.search), Expr.contains(fields.upc, input.search))\n * ```\n *\n * Unknown as SQL's `or` is: true wins over unknown, which wins over false.\n * Needs an operand, since an empty `or` would match no row.\n */\n or: connective<OrPredicate>('or', 'Or') as Connective<OrPredicate>,\n\n /**\n * The operand does not hold. **A null is matched by neither side**:\n * `not(eq(status, 'draft'))` leaves out a row whose `status` is null, since\n * `null = 'draft'` is unknown and so is its `not`, as in SQL. \"Everything\n * but drafts\" over a nullable column is\n * `Expr.or(Expr.isNull(status), Expr.not(Expr.eq(status, 'draft')))`.\n */\n not: <P extends Predicate>(operand: P): NotPredicate & Reads<ReadsOf<P>> => {\n if (!isPredicate(operand)) {\n throw new Error(\n '[foldkit-entity] Expr.not: the operand is a predicate; compare a value with Expr.eq first',\n )\n }\n return node({ _tag: 'Not', operand })\n },\n\n /**\n * A filter that applies only when its input is given: `or(isNull($x), …)`,\n * with the predicate built from the input as never null.\n *\n * ```ts\n * // Every product, or those of the chosen status.\n * Expr.whenGiven(input.status, status => Expr.eq(fields.status, status))\n * ```\n *\n * An interpreter that runs per request, as the Drizzle compiler does, decides\n * `isNull($x)` before writing SQL, so this compiles to `true`, which filters\n * nothing, or to the predicate alone.\n */\n whenGiven: <T, P extends Predicate>(\n input: InputExpr<T>,\n build: (given: InputExpr<NonNullable<T>>) => P,\n ): Predicate & Reads<ReadsOf<P>> =>\n // The predicate only decides a row when the input is not null: when it is,\n // `isNull` is true and so is the `or`. That is what the narrowed type says.\n Expr.or(Expr.isNull(input), build(input as unknown as InputExpr<NonNullable<T>>)),\n\n /** An expression as readable text; see `showExpr` for what it is and is not. */\n show: (node: Operandish): string => showExpr(node),\n\n /**\n * The predicate with each field after a write (`Next`) that `values` names,\n * by key, read as that value: how an invariant is judged where the\n * write's new values are known. A field it does not name stays `Next`, for\n * the interpreter to read as the row after holds it.\n */\n substituteNext: (predicate: Predicate, values: Readonly<Record<string, unknown>>): Predicate =>\n substituted(predicate, operand =>\n Match.value(operand).pipe(\n Match.tag('Next', ({ field }) =>\n Object.hasOwn(values, field.key) ? literal(values[field.key]) : operand,\n ),\n Match.orElse(() => operand),\n ),\n ),\n}\n\n/** Rewrites one operand; the walk below applies it wherever a predicate holds one. */\ntype OperandRewrite = (operand: AnyExpr) => AnyExpr\n\nconst substitutedSide = (side: Operandish, rewrite: OperandRewrite): Operandish =>\n isPredicate(side) ? substituted(side, rewrite) : substitutedScalar(side, rewrite)\n\n/**\n * A scalar rewritten: a call's arguments and expansion each, so a field read\n * under it is rewritten as one read directly is; anything else by `rewrite`.\n */\nconst substitutedScalar = (scalar: AnyExpr, rewrite: OperandRewrite): AnyExpr =>\n scalar._tag === 'Call'\n ? node({\n ...scalar,\n args: Object.freeze(scalar.args.map(arg => substitutedSide(arg, rewrite))),\n expansion: Option.map(scalar.expansion, expansion => substitutedScalar(expansion, rewrite)),\n })\n : rewrite(scalar)\n\nconst substituted = (predicate: Predicate, rewrite: OperandRewrite): Predicate => {\n switch (predicate._tag) {\n case 'Eq':\n return node({\n ...predicate,\n left: substitutedSide(predicate.left, rewrite),\n right: substitutedSide(predicate.right, rewrite),\n })\n case 'Null':\n return node({ ...predicate, operand: substitutedScalar(predicate.operand, rewrite) })\n case 'Contains':\n return node({\n ...predicate,\n value: substitutedScalar(predicate.value, rewrite),\n search: substitutedSide(predicate.search, rewrite),\n })\n case 'In':\n return node({\n ...predicate,\n value: substitutedScalar(predicate.value, rewrite),\n among: substitutedScalar(predicate.among, rewrite),\n })\n case 'And':\n case 'Or':\n return node({\n ...predicate,\n operands: Arr.map(predicate.operands, operand => substituted(operand, rewrite)),\n })\n case 'Not':\n return node({ ...predicate, operand: substituted(predicate.operand, rewrite) })\n case 'Compare':\n return node({\n ...predicate,\n left: substitutedScalar(predicate.left, rewrite),\n right: substitutedScalar(predicate.right, rewrite),\n })\n case 'Test':\n return node({\n ...predicate,\n args: Object.freeze(predicate.args.map(arg => substitutedSide(arg, rewrite))),\n expansion: Option.map(predicate.expansion, expansion => substituted(expansion, rewrite)),\n })\n // Its filter reads the pointing row, never the one a rewrite is about.\n case 'Exists':\n return predicate\n }\n}\n\n/** One term of an ordering: a scalar and the direction to read it in. */\nexport interface OrderTerm {\n readonly _tag: 'Term'\n readonly direction: 'asc' | 'desc'\n readonly expr: AnyExpr\n /**\n * Where rows without a value go, in the term's own direction. Databases\n * disagree when it is left unsaid (Postgres puts them last ascending, SQLite\n * first), so it is always said: last ascending and first descending unless\n * a term asks otherwise, which is Postgres's.\n */\n readonly nulls: 'first' | 'last'\n /**\n * How text compares, when the term orders text: the term's own, or its\n * field's. None leaves it to the backend, which a client cannot match.\n */\n readonly collation: Option.Option<Collation>\n}\n\n/** What a term may say besides its operand. */\nexport interface TermOptions {\n readonly nulls?: 'first' | 'last' | undefined\n /** Overrides the field's declared collation for this term. */\n readonly collation?: Collation | undefined\n}\n\n/** A term, its nulls placed by `options` or by the direction's default. */\nconst term = (direction: 'asc' | 'desc', expr: AnyExpr, options: TermOptions = {}): OrderTerm => {\n // The collation the operand itself carries.\n const carried = Match.value(expr).pipe(\n Match.tagsExhaustive({\n Field: field => field.collation,\n Call: call => call.collation,\n // A client could not place a row by a value another row holds, and a\n // cursor over one would page by what can change under it.\n Path: (path): Option.Option<Collation> => {\n throw new Error(\n `[foldkit-entity] Order: ${showExpr(path)} is a path; a list orders by its own row's fields`,\n )\n },\n ViewerPath: (path): Option.Option<Collation> => {\n throw new Error(\n `[foldkit-entity] Order: ${showExpr(path)} is a path from the viewer; a list orders by its own row's fields`,\n )\n },\n Literal: () => Option.none<Collation>(),\n Input: () => Option.none<Collation>(),\n Next: () => Option.none<Collation>(),\n Viewer: () => Option.none<Collation>(),\n Now: () => Option.none<Collation>(),\n }),\n )\n // A number orders alike everywhere, and Postgres refuses a collation on one: a\n // collation it would inherit from a call's text arguments is dropped.\n const number = sideKind(expr) === 'number'\n if (number && options.collation !== undefined) {\n throw new Error(\n `[foldkit-entity] Order: ${showExpr(expr)} is a number, which needs no collation; a collation orders text`,\n )\n }\n const collation = number\n ? Option.none<Collation>()\n : Option.orElse(Option.fromUndefinedOr(options.collation), () => carried)\n if (expr._tag === 'Call') orderableCall(expr, collation)\n return node({\n _tag: 'Term',\n direction,\n expr,\n nulls: options.nulls ?? (direction === 'asc' ? 'last' : 'first'),\n collation,\n })\n}\n\n/**\n * Refuses a call no interpreter could order alike (expr-operations-DESIGN §8):\n * its result must be a number, or text under a collation every interpreter\n * shares. A field's text may be left to the backend; a call's has no backend\n * column to fall back on.\n */\nconst orderableCall = (call: CallExpr<unknown>, collation: Option.Option<Collation>): void => {\n const fail = (why: string): never => {\n throw new Error(`[foldkit-entity] Order: ${showExpr(call)} ${why}`)\n }\n const kind = sideKind(call)\n if (kind === 'number') return\n if (kind !== 'text') fail('is neither a number nor text, so it orders nowhere alike')\n Option.match(collation, {\n onNone: () =>\n fail(\n 'is text with no collation, so backends would order it differently; give the term or its text Collation.binary or Collation.asciiFold',\n ),\n onSome: each => {\n if (each._tag === 'Locale') {\n fail(`is ordered by the backend's \"${each.locale}\" collation, which a call cannot carry`)\n }\n },\n })\n}\n\n/** How a list is sorted, as its input holds it: one of its named orders, which way, or none. */\nexport type ChosenSort<By extends string> = {\n readonly by: By\n readonly direction: 'asc' | 'desc'\n} | null\n\n/**\n * An ordering the input chooses: one of several named fields, which way, or\n * none. It is how a list sorts by what its reader picked, said in the body, so\n * the server and the client read one declaration of what each name means.\n */\nexport interface ChosenOrder {\n readonly _tag: 'Chosen'\n readonly sort: InputExpr<ChosenSort<string>>\n readonly choices: Readonly<Record<string, FieldExpr<unknown> | CallExpr<unknown>>>\n}\n\n/** One entry of a body's ordering: fixed, or chosen by the input. */\nexport type Ordering = OrderTerm | ChosenOrder\n\n/**\n * What an order term orders by, refusing a link: a client holds a link as a\n * ref, not the id it orders by, so it could not place a row there.\n */\nconst orderOperand = (expr: unknown, step: 'asc' | 'desc' | 'chosen'): AnyExpr => {\n if (tagOf(expr) === 'Relation') {\n throw new Error(\n `[foldkit-entity] Order.${step}: a list orders by its own fields, not by where a relation points`,\n )\n }\n return toExpr(expr as never, step)\n}\n\nexport const Order = {\n /** Smallest first; rows without a value last, unless `nulls` says first. */\n asc: <E extends OwnOperand<any>>(expr: E, options?: TermOptions): OrderTerm & Reads<ReadsOf<E>> =>\n term('asc', orderOperand(expr, 'asc'), options),\n /** Largest first; rows without a value first, unless `nulls` says last. */\n desc: <E extends OwnOperand<any>>(\n expr: E,\n options?: TermOptions,\n ): OrderTerm & Reads<ReadsOf<E>> => term('desc', orderOperand(expr, 'desc'), options),\n\n /**\n * The order the input names, among `choices`: every name the sort can hold\n * maps to a field or a call that orders, so a name left out is a type error\n * here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after\n * it decide.\n *\n * ```ts\n * Query.orderBy(Order.chosen(input.sort, { title: Post.fields.title }))\n * ```\n */\n chosen: <By extends string, const Choices extends { readonly [K in By]: OwnOperand<any> }>(\n sort: InputExpr<ChosenSort<By>>,\n choices: Choices,\n ): ChosenOrder & Reads<ReadsOf<Choices[keyof Choices]>> => {\n const fields: Record<string, FieldExpr<unknown> | CallExpr<unknown>> = Object.create(null)\n for (const [name, choice] of Object.entries<OwnOperand<any>>(choices)) {\n const expr = orderOperand(choice, 'chosen')\n if (expr._tag !== 'Field' && expr._tag !== 'Call') {\n throw new Error(`[foldkit-entity] Order.chosen: \"${name}\" is neither a field nor a call`)\n }\n // Checked as a term now, so an alternative no input has chosen yet is refused where written.\n if (expr._tag === 'Call') orderableCall(expr, expr.collation)\n fields[name] = expr\n }\n return node({\n _tag: 'Chosen',\n sort: sort as InputExpr<ChosenSort<string>>,\n choices: Object.freeze(fields),\n })\n },\n}\n\n/**\n * Whether a client can order rows the way the server does, for one input: the\n * answer `Query.placement` gives, and the reason when it cannot.\n */\nexport type Placement =\n | { readonly _tag: 'Placeable' }\n | { readonly _tag: 'NotPlaceable'; readonly reason: string }\n\nconst placeable: Placement = Object.freeze({ _tag: 'Placeable' })\nconst notPlaceable = (reason: string): Placement => Object.freeze({ _tag: 'NotPlaceable', reason })\n\n/**\n * Whether values encoded by `ast` order the same everywhere: numbers and\n * booleans, never text. A null among them does too: where it goes is said on\n * every order term.\n */\nconst ordersIntrinsically = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNumber(ast) ||\n SchemaAST.isBoolean(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal !== 'string') ||\n (SchemaAST.isUnion(ast) &&\n ast.types.every(member => SchemaAST.isNull(member) || ordersIntrinsically(member)))\n\n/** Why a term cannot be placed by a client running `operators`, if it cannot. */\nconst unplaceable = (orderTerm: OrderTerm, operators: OperatorTable): Option.Option<string> =>\n Match.value(orderTerm.expr).pipe(\n // Checked when the term was made: a number, or text under a shared collation.\n // Left is whether the client runs every primitive operator it calls.\n Match.tag('Call', call => {\n const missing = missingFrom(dependenciesOf(call).operators, operators)\n return missing.length === 0\n ? Option.none<string>()\n : Option.some(\n `it orders by ${showExpr(call)}, and this client does not run ${missing.join(', ')}`,\n )\n }),\n Match.tag('Field', field =>\n Option.match(orderTerm.collation, {\n onNone: () =>\n ordersIntrinsically(Schema.toEncoded(field.schema).ast)\n ? Option.none()\n : Option.some(\n `it orders by ${field.owner.name}.${field.key}, text with no declared collation`,\n ),\n onSome: collation =>\n Match.value(collation).pipe(\n Match.tagsExhaustive({\n Binary: () => Option.none<string>(),\n AsciiFold: () => Option.none<string>(),\n Locale: ({ locale }) =>\n Option.some(\n `it orders ${field.owner.name}.${field.key} by the backend's \"${locale}\" collation`,\n ),\n }),\n ),\n }),\n ),\n Match.tags({\n Literal: neither,\n Input: neither,\n Next: neither,\n Viewer: neither,\n Now: neither,\n // Refused where the term is made; said here too.\n Path: neither,\n ViewerPath: neither,\n }),\n Match.exhaustive,\n )\n\nconst neither = (): Option.Option<string> =>\n Option.some('it orders by something that is neither a field nor a call')\n\n/** Each Entity's id tie-break, made once, so a resolved order reuses one term. */\nconst idTerms = new WeakMap<AnyEntity, OrderTerm>()\nconst idTermOf = (entity: AnyEntity): OrderTerm => {\n const known = idTerms.get(entity)\n if (known !== undefined) return known\n const id = entity.fields.id\n if (id === undefined) {\n throw new Error(`[foldkit-entity] ${entity.name} has no id field to break an order's ties by`)\n }\n const tieBreak = term('asc', fieldExpr(id))\n idTerms.set(entity, tieBreak)\n return tieBreak\n}\n\n/** The fixed term a chosen order is for one input, or none for a `null` sort. */\nconst chosenTerms = (\n chosen: ChosenOrder,\n input: Readonly<Record<string, unknown>>,\n): ReadonlyArray<OrderTerm> => {\n const sort = own(input, chosen.sort.key)\n if (sort === null || sort === undefined) return []\n const picked =\n typeof sort === 'object' && 'by' in sort && typeof sort.by === 'string' ? sort.by : undefined\n const direction = typeof sort === 'object' && 'direction' in sort ? sort.direction : undefined\n if (\n picked === undefined ||\n !Object.hasOwn(chosen.choices, picked) ||\n (direction !== 'asc' && direction !== 'desc')\n ) {\n throw new Error(\n `[foldkit-entity] Order.chosen: $${chosen.sort.key} names no order it offers (${Object.keys(chosen.choices).join(', ')})`,\n )\n }\n return [term(direction, chosen.choices[picked]!)]\n}\n\n/** What a walk has found, and the nodes it has already been through. */\ninterface Found {\n readonly seen: Set<object>\n /** By owner identity, then key: two Entities sharing a name are two entries. */\n readonly fields: Map<symbol, Map<string, FieldDependency>>\n readonly order: Array<FieldDependency>\n readonly inputs: Set<string>\n readonly next: Map<symbol, Map<string, FieldDependency>>\n readonly nextOrder: Array<FieldDependency>\n readonly operations: Set<Operation>\n readonly operators: Set<OperatorDescriptor>\n readonly reaches: Array<PathExpr<unknown> | ExistsPredicate | ViewerPathExpr<unknown>>\n}\n\n/**\n * Visits each node once. A node can be shared by several paths (`eq(n, n)`),\n * and a walk that followed every path would take time exponential in the depth.\n */\nconst walk = (expr: AnyExpr | Predicate | Ordering, found: Found): void => {\n if (found.seen.has(expr)) return\n found.seen.add(expr)\n switch (expr._tag) {\n case 'Literal':\n return\n case 'Field': {\n const byKey = found.fields.get(expr.owner.token) ?? new Map<string, FieldDependency>()\n found.fields.set(expr.owner.token, byKey)\n if (!byKey.has(expr.key)) {\n const field = { entity: expr.owner.name, key: expr.key, owner: expr.owner }\n byKey.set(expr.key, field)\n found.order.push(field)\n }\n return\n }\n case 'Input':\n found.inputs.add(expr.key)\n return\n case 'Viewer':\n found.operations.add('viewer')\n return\n case 'Now':\n found.operations.add('now')\n return\n case 'Next': {\n found.operations.add('next')\n const { field } = expr\n const byKey = found.next.get(field.owner.token) ?? new Map<string, FieldDependency>()\n found.next.set(field.owner.token, byKey)\n if (!byKey.has(field.key)) {\n const read = { entity: field.owner.name, key: field.key, owner: field.owner }\n byKey.set(field.key, read)\n found.nextOrder.push(read)\n }\n return\n }\n case 'Eq':\n found.operations.add('eq')\n walk(expr.left, found)\n walk(expr.right, found)\n return\n case 'Null':\n found.operations.add(expr.present ? 'isNotNull' : 'isNull')\n walk(expr.operand, found)\n return\n case 'Contains':\n found.operations.add('contains')\n walk(expr.value, found)\n walk(expr.search, found)\n return\n case 'In':\n found.operations.add('in')\n walk(expr.value, found)\n walk(expr.among, found)\n return\n case 'And':\n found.operations.add('and')\n for (const operand of expr.operands) walk(operand, found)\n return\n case 'Or':\n found.operations.add('or')\n for (const operand of expr.operands) walk(operand, found)\n return\n case 'Not':\n found.operations.add('not')\n walk(expr.operand, found)\n return\n case 'Compare':\n found.operations.add('compare')\n walk(expr.left, found)\n walk(expr.right, found)\n return\n case 'Term':\n walk(expr.expr, found)\n return\n case 'Chosen':\n walk(expr.sort, found)\n for (const choice of Object.values(expr.choices)) walk(choice, found)\n return\n case 'Path':\n found.operations.add('path')\n found.reaches.push(expr)\n return\n // It needs whoever asks, and the subqueries a path is compiled to.\n case 'ViewerPath':\n found.operations.add('viewer')\n found.operations.add('path')\n found.reaches.push(expr)\n return\n case 'Exists': {\n found.operations.add('exists')\n found.reaches.push(expr)\n // The filter's fields are the pointing row's, so they stay out of `fields`;\n // what else it needs is this expression's need too.\n Option.map(expr.where, where => {\n const inner = dependenciesOf(where)\n inner.inputs.forEach(key => found.inputs.add(key))\n inner.operations.forEach(operation => found.operations.add(operation))\n inner.operators.forEach(operator => found.operators.add(operator))\n })\n return\n }\n case 'Call':\n case 'Test':\n found.operators.add(expr.operator)\n // What an interpreter runs is the expansion: its operations, and the reads its\n // arguments hold. With none, the arguments are all there is to read.\n Option.match(expansionOf(expr), {\n onSome: expansion => walk(expansion, found),\n onNone: () => expr.args.forEach(arg => walk(arg, found)),\n })\n return\n default:\n return absurd(expr)\n }\n}\n\n/**\n * What an expression reads and uses, for the planner and for an interpreter\n * deciding whether it can run this query at all. Distinct entries only, in the\n * order first seen, so the answer is stable enough to assert on.\n */\nexport const dependenciesOf = (\n ...nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>\n): Dependencies => {\n const found: Found = {\n seen: new Set(),\n fields: new Map(),\n order: [],\n inputs: new Set(),\n next: new Map(),\n nextOrder: [],\n operations: new Set(),\n operators: new Set(),\n reaches: [],\n }\n for (const term of nodes) walk(term, found)\n return {\n fields: found.order,\n next: found.nextOrder,\n inputs: [...found.inputs],\n operations: [...found.operations],\n operators: [...found.operators],\n reaches: found.reaches,\n }\n}\n\n/**\n * Which rows a query is about, as a value: an Entity to read, the predicates\n * every row must satisfy, and the order to read them in. It says nothing about\n * which fields to return — that is a Selection — and nothing about pagination,\n * liveness, or whether absence is an error, which belong to the consumer's read\n * rather than to the relation.\n *\n * Composing one performs no work. `Query.from(Post)` names no table and opens\n * no connection; an interpreter turns the value into a query when something\n * asks it to.\n */\nexport interface Query<E extends AnyEntity> extends Pipeable.Pipeable {\n readonly _tag: 'Query'\n readonly entity: E\n /**\n * Every predicate holds: the list *is* the conjunction. Keeping it a list\n * rather than folding it into one `and` is what makes each `where` a reusable\n * fragment, and it means no `Expr.and` exists until a query needs a\n * conjunction nested inside something else.\n */\n readonly where: ReadonlyArray<Predicate>\n /** In order of significance; a later `orderBy` appends less significant terms. */\n readonly orderBy: ReadonlyArray<Ordering>\n}\n\n/** A `Query` over any Entity, for the places that hold one without caring which. */\nexport type AnyQuery = Query<AnyEntity>\n\n/**\n * Every member of the judged row an expression reads, each node visited once:\n * a field, or the relation a path or an exists starts from.\n */\nconst fieldsIn = function* (\n expr: AnyExpr | Predicate | Ordering,\n seen: Set<object>,\n): Generator<{ readonly owner: EntityIdentity<string>; readonly key: string }> {\n if (seen.has(expr)) return\n seen.add(expr)\n switch (expr._tag) {\n case 'Field':\n yield expr\n return\n case 'Next':\n yield expr.field\n return\n case 'Literal':\n case 'Input':\n case 'Viewer':\n case 'Now':\n return\n case 'Eq':\n yield* fieldsIn(expr.left, seen)\n yield* fieldsIn(expr.right, seen)\n return\n case 'Null':\n yield* fieldsIn(expr.operand, seen)\n return\n case 'Contains':\n yield* fieldsIn(expr.value, seen)\n yield* fieldsIn(expr.search, seen)\n return\n case 'In':\n yield* fieldsIn(expr.value, seen)\n yield* fieldsIn(expr.among, seen)\n return\n case 'And':\n case 'Or':\n for (const operand of expr.operands) yield* fieldsIn(operand, seen)\n return\n case 'Not':\n yield* fieldsIn(expr.operand, seen)\n return\n case 'Compare':\n yield* fieldsIn(expr.left, seen)\n yield* fieldsIn(expr.right, seen)\n return\n case 'Term':\n yield* fieldsIn(expr.expr, seen)\n return\n case 'Chosen':\n for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen)\n return\n case 'Path':\n yield expr.via[0]\n return\n // It starts at the viewer's row, not the judged one, so any query may read it.\n case 'ViewerPath':\n return\n case 'Exists':\n yield existsStart(expr)\n return\n // An expansion reads only what its arguments do, which the call checked.\n case 'Call':\n case 'Test':\n for (const arg of expr.args) yield* fieldsIn(arg, seen)\n return\n default:\n return absurd(expr)\n }\n}\n\n/**\n * A query reads one Entity, so a predicate or ordering term naming a different\n * one cannot be answered — an interpreter would be asked for a column of a\n * table it was never told to read. Compared by identity, not by name, because\n * two Entities defined with the same name are two Entities.\n */\nconst checkOwnership = (\n step: string,\n what: string,\n entity: AnyEntity,\n nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>,\n): void => {\n const seen = new Set<object>()\n for (const term of nodes) {\n for (const field of fieldsIn(term, seen)) {\n if (field.owner.token !== entity.identity.token) {\n throw new Error(\n `[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`,\n )\n }\n }\n }\n}\n\n/**\n * The most nodes a query's predicates may hold once every shared node is\n * counted on each path that reaches it. Interpreters read a predicate as a\n * tree: `evaluate` once per row, and the SQL compiler into text that repeats a\n * shared operand wherever it appears. So `eq(n, n)` nested thirty deep is\n * thirty-one objects and a billion nodes of work. Real queries are tens.\n */\nexport const maxQueryNodes = 1_000\n\nconst childrenOf = (expr: AnyExpr | Predicate): ReadonlyArray<AnyExpr | Predicate> => {\n switch (expr._tag) {\n case 'Literal':\n case 'Field':\n case 'Input':\n case 'Next':\n case 'Viewer':\n case 'Now':\n case 'Path':\n case 'ViewerPath':\n return []\n case 'Exists':\n return Option.toArray(expr.where)\n case 'Eq':\n return [expr.left, expr.right]\n case 'Null':\n return [expr.operand]\n case 'Contains':\n return [expr.value, expr.search]\n case 'In':\n return [expr.value, expr.among]\n case 'And':\n case 'Or':\n return expr.operands\n case 'Not':\n return [expr.operand]\n case 'Compare':\n return [expr.left, expr.right]\n // What an interpreter runs is the expansion, so that is what the budget counts.\n case 'Call':\n case 'Test':\n return Option.match(expansionOf(expr), {\n onSome: expansion => [expansion],\n onNone: () => expr.args,\n })\n }\n}\n\n/** A node's size as a tree, each distinct node sized once. */\nconst expandedSize = (expr: AnyExpr | Predicate, sizes: Map<object, number>): number => {\n const known = sizes.get(expr)\n if (known !== undefined) return known\n // Capped, so a graph deep enough to overflow a number still compares as too big.\n const size = Math.min(\n maxQueryNodes + 1,\n childrenOf(expr).reduce((sum, child) => sum + expandedSize(child, sizes), 1),\n )\n sizes.set(expr, size)\n return size\n}\n\nconst QueryProto = {\n _tag: 'Query' as const,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst query = <E extends AnyEntity>(\n entity: E,\n where: ReadonlyArray<Predicate>,\n orderBy: ReadonlyArray<Ordering>,\n): Query<E> =>\n Object.freeze(\n Object.assign(Object.create(QueryProto), {\n entity,\n where: Object.freeze(where),\n orderBy: Object.freeze(orderBy),\n }),\n ) as Query<E>\n\n/**\n * Refuses a query whose predicates and order terms (every chosen alternative\n * among them) expand past `maxQueryNodes`, counting a shared node on every\n * path that reaches it: what an interpreter walks, and SQL writes out.\n */\nconst checkSize = (\n step: 'where' | 'orderBy',\n where: ReadonlyArray<Predicate>,\n orderBy: ReadonlyArray<Ordering>,\n): void => {\n const sizes = new Map<object, number>()\n const terms = orderBy.flatMap(ordering =>\n Match.valueTags(ordering, {\n Term: ({ expr }) => [expr],\n Chosen: ({ choices }) => Object.values(choices),\n }),\n )\n const size = [...where, ...terms].reduce((sum, each) => sum + expandedSize(each, sizes), 0)\n if (size > maxQueryNodes) {\n throw new Error(\n `[foldkit-entity] Query.${step}: the query expands to more than ${maxQueryNodes} nodes, counting a shared node on every path that reaches it`,\n )\n }\n}\n\nexport const Query = {\n /** Every row of an Entity: the query each transformation narrows. */\n from: <E extends AnyEntity>(entity: E): Query<E> => query(entity, [], []),\n\n /**\n * Narrows to the rows the predicate holds for. Two `where`s conjoin — the\n * second never replaces the first — so a fragment can be written once and\n * piped into any query over the same Entity:\n *\n * ```ts\n * const published = Query.where(Expr.eq(Post.fields.published, true))\n * Query.from(Post).pipe(published, Query.where(byTitle))\n * ```\n */\n where:\n <const P extends ReadonlyArray<Predicate>>(...predicates: P) =>\n <E extends AnyEntity>(\n self: Query<E> & OverEntity<ReadsOf<P[number]>, E['name'], 'a predicate'>,\n ): Query<E> => {\n if (predicates.length === 0) return self\n checkOwnership('where', 'a predicate', self.entity, predicates)\n const where = [...self.where, ...predicates]\n checkSize('where', where, self.orderBy)\n return query(self.entity, where, self.orderBy)\n },\n\n /**\n * Reads the rows in this order. Two `orderBy`s append, so an earlier term\n * stays the more significant one and a later call adds a tie-breaker rather\n * than silently winning.\n */\n orderBy:\n <const T extends ReadonlyArray<Ordering>>(...terms: T) =>\n <E extends AnyEntity>(\n self: Query<E> & OverEntity<ReadsOf<T[number]>, E['name'], 'an ordering term'>,\n ): Query<E> => {\n if (terms.length === 0) return self\n checkOwnership('orderBy', 'a term', self.entity, terms)\n const orderBy = [...self.orderBy, ...terms]\n checkSize('orderBy', self.where, orderBy)\n return query(self.entity, self.where, orderBy)\n },\n\n /**\n * The fixed terms this query orders by for one input: each chosen order\n * resolved to the field its input names, or to nothing for a `null` sort,\n * and the Entity's id last, ascending, unless the terms already read it. So\n * the order is total, and every interpreter breaks ties the same way: one\n * that broke them its own way would place rows a step apart from another.\n */\n orderFor: (\n self: AnyQuery,\n input: Readonly<Record<string, unknown>>,\n ): ReadonlyArray<OrderTerm> => {\n const terms = self.orderBy.flatMap(entry =>\n Match.value(entry).pipe(\n Match.tagsExhaustive({\n Term: term => [term],\n Chosen: chosen => chosenTerms(chosen, input),\n }),\n ),\n )\n const id = idTermOf(self.entity)\n // Every field an order reads is this Entity's: `orderBy` refuses another's.\n const endsOnId = terms.some(term => term.expr._tag === 'Field' && term.expr.key === 'id')\n return endsOnId ? terms : [...terms, id]\n },\n\n /**\n * Whether a client can order this query's rows exactly as the server does,\n * for one input: every term over a number or a boolean (a row may lack it), or over text with a\n * portable collation (`binary`, `asciiFold`), or a call whose primitive\n * operators the client's table (`operators`; none when not given) runs. A\n * body that names no order leaves it to the server, and is never placeable.\n */\n placement: (\n self: AnyQuery,\n input: Readonly<Record<string, unknown>>,\n options: { readonly operators?: OperatorTable | undefined } = {},\n ): Placement => {\n if (self.orderBy.length === 0) {\n return notPlaceable(\"its order is the server's: the body names none\")\n }\n const operators = options.operators ?? noOperators\n for (const orderTerm of Query.orderFor(self, input)) {\n const reason = unplaceable(orderTerm, operators)\n if (Option.isSome(reason)) return notPlaceable(reason.value)\n }\n return placeable\n },\n\n /**\n * Each operator the body calls, by name (`id`, or `id@version` past the\n * first), in the order it first calls them: a defined one, and each\n * primitive one its expansion calls.\n */\n operators: (self: AnyQuery): ReadonlyArray<string> =>\n Query.dependencies(self).operators.map(operatorName),\n\n /**\n * What the whole query reads: the fields and inputs of every predicate and\n * every ordering term, and the operations it uses, with the fields also\n * split by role.\n */\n dependencies: (self: AnyQuery): QueryDependencies => ({\n ...dependenciesOf(...self.where, ...self.orderBy),\n predicate: dependenciesOf(...self.where).fields,\n order: dependenciesOf(...self.orderBy).fields,\n }),\n\n /**\n * The operations this query needs that `supported` does not list, in the\n * order the query uses them, then each primitive operator `operators` does\n * not implement, by name. Without `operators`, every primitive operator is\n * named: a list of operations implements none. Empty means an interpreter\n * declaring both can answer it.\n *\n * An interpreter declares what it runs and refuses the rest, rather than\n * ignoring an operation it does not implement — which would answer a\n * different question and say nothing. The refusal is the interpreter's to\n * raise: this only says what is missing, because what to do about it differs\n * between one that compiles at registration and one that runs a body\n * directly.\n *\n * ```ts\n * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])\n * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)\n * ```\n */\n unsupported: (\n self: AnyQuery,\n supported: ReadonlyArray<Operation>,\n operators: OperatorTable = noOperators,\n ): ReadonlyArray<string> => unsupportedIn([...self.where, ...self.orderBy], supported, operators),\n\n /**\n * The whole query as readable text, one clause per line:\n *\n * ```text\n * FROM Post\n * WHERE Post.slug = $slug\n * AND Post.published = true\n * ORDER BY Post.updatedAt DESC\n * ```\n *\n * For an explanation or a diagnostic, never for an interpreter — see\n * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather\n * than printing an empty one, so what is shown is what was written.\n */\n show: (self: AnyQuery): string =>\n [\n `FROM ${self.entity.name}`,\n // Among several, an `or` is parenthesised: `WHERE a or b` over `AND c`\n // would read as `a or (b and c)`.\n ...self.where.map(\n (predicate, index) =>\n `${index === 0 ? 'WHERE' : ' AND'} ${Match.value(predicate).pipe(\n Match.tag('Or', or => (self.where.length > 1 ? `(${Expr.show(or)})` : Expr.show(or))),\n Match.orElse(each => Expr.show(each)),\n )}`,\n ),\n ...(self.orderBy.length === 0\n ? []\n : [\n `ORDER BY ${self.orderBy\n .map(entry =>\n Match.value(entry).pipe(\n Match.tagsExhaustive({\n Term: term => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`,\n Chosen: chosen =>\n `$${chosen.sort.key} among (${Object.entries(chosen.choices)\n .map(([name, field]) => `${name}: ${Expr.show(field)}`)\n .join(', ')})`,\n }),\n ),\n )\n .join(', ')}`,\n ]),\n ].join('\\n'),\n}\n\n/**\n * An expression as readable text, in the IR's own terms.\n *\n * This is for a human — an explanation, a diagnostic, a test that wants to\n * assert on a whole predicate at once — and deliberately **not** for an\n * interpreter. It is close enough to SQL to read at a glance and unlike it\n * everywhere that matters: an input is `$slug` rather than a bound parameter,\n * `contains` is named rather than rendered as somebody's `like`, and no\n * dialect's escaping or collation is implied. What actually ran is whatever\n * that backend compiled, which is not this.\n *\n * A predicate standing where a value is wanted is parenthesised, because\n * `x is not null = $archived` reads as three operands and is two. A predicate\n * that *is* the whole expression is not: nothing encloses it.\n */\nconst showExpr = (node: AnyExpr | Predicate): string => {\n switch (node._tag) {\n case 'Literal':\n return JSON.stringify(node.value) ?? String(node.value)\n case 'Field':\n return `${node.owner.name}.${node.key}`\n case 'Input':\n return `$${node.key}`\n case 'Next':\n return `next ${node.field.owner.name}.${node.field.key}`\n case 'Viewer':\n return `viewer ${node.entity.name}`\n case 'Now':\n return 'now'\n case 'Eq':\n return `${showOperand(node.left)} = ${showOperand(node.right)}`\n case 'Null':\n return `${showOperand(node.operand)} is ${node.present ? 'not null' : 'null'}`\n case 'Contains':\n return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`\n case 'In':\n return `${showOperand(node.value)} in ${showOperand(node.among)}`\n case 'And':\n return node.operands.map(showConnected).join(' and ')\n case 'Or':\n return node.operands.map(showConnected).join(' or ')\n case 'Not':\n return `not (${showExpr(node.operand)})`\n case 'Compare':\n return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`\n case 'Call':\n case 'Test':\n return `${operatorName(node.operator)}(${node.args.map(showOperand).join(', ')})`\n // `Post.author.handle`: the judged row's relation, then each next one, then the field.\n case 'Path':\n return [`${node.via[0].owner.name}`, ...node.via.map(step => step.key), node.field.key].join(\n '.',\n )\n // `viewer Member.team.orgId`: the viewer's row, each relation from it, then the field.\n case 'ViewerPath':\n return `viewer ${[node.viewer.entity.name, ...node.via.map(step => step.key), node.field.key].join('.')}`\n case 'Exists': {\n const sought = `exists ${node.relation.owner.name}.${node.relation.key}${Option.match(\n node.where,\n { onNone: () => '', onSome: where => ` where ${showExpr(where)}` },\n )}`\n const [first] = node.via\n return first === undefined\n ? sought\n : `${[first.owner.name, ...node.via.map(step => step.key)].join('.')}: ${sought}`\n }\n }\n}\n\n/**\n * Where an exists starts on the judged row: the relation its path follows\n * first, or, asked of the row itself, its id, which the pointing rows hold.\n */\nconst existsStart = (\n exists: ExistsPredicate,\n): { readonly owner: EntityIdentity<string>; readonly key: string } =>\n exists.via[0] ?? { owner: exists.relation.target().identity, key: 'id' }\n\n/** A call's expansion, scalar or predicate alike. */\nconst expansionOf = (call: CallExpr<unknown> | TestPredicate): Option.Option<AnyExpr | Predicate> =>\n call.expansion\n\n/**\n * What `nodes` need that an interpreter lacks: each kernel operation it does\n * not list, then each primitive operator its table does not implement, by\n * name. A defined operator needs nothing: what it means is walked instead.\n */\nconst unsupportedIn = (\n nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>,\n supported: ReadonlyArray<Operation>,\n operators: OperatorTable,\n): ReadonlyArray<string> => {\n const read = dependenciesOf(...nodes)\n const runs = new Set(supported)\n return [\n ...read.operations.filter(operation => !runs.has(operation)),\n ...missingFrom(read.operators, operators),\n ]\n}\n\n/**\n * The primitive operators among `read` that `operators` does not implement, by\n * name. A defined one needs nothing: what it means was walked into `read`.\n */\nconst missingFrom = (\n read: ReadonlyArray<OperatorDescriptor>,\n operators: OperatorTable,\n): ReadonlyArray<string> =>\n read\n .filter(operator => Option.isNone(operator.definedAs) && !operators.has(operator))\n .map(operator => missingName(operator, operators))\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\nconst symbols: Readonly<Record<CompareOperator, string>> = {\n lt: '<',\n lte: '<=',\n gt: '>',\n gte: '>=',\n}\n\n/** An operand of `and` or `or`: another connective is parenthesised, so its grouping shows. */\nconst showConnected = (node: Predicate): string =>\n Match.value(node).pipe(\n Match.tags({ And: () => `(${showExpr(node)})`, Or: () => `(${showExpr(node)})` }),\n Match.orElse(() => showExpr(node)),\n )\n\nconst showOperand = (node: Operandish): string =>\n isPredicate(node) ? `(${showExpr(node)})` : showExpr(node)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4HA,MAAa,cAA6B,OAAO,OAAO;CAAE,WAAW;CAAO,gBAAgB,CAAC;AAAE,CAAC;;;;;AAMhG,MAAa,eAAe,UAA8B,cAAqC;CAC7F,MAAM,OAAO,UAAU,SAAS,SAAS,EAAE;CAG3C,IAAI,KAAK,SAAS,SAAS,OAAO,GAChC,OAAO,GAAG,aAAa,QAAQ,EAAE;CAEnC,OAAO,KAAK,WAAW,IACnB,aAAa,QAAQ,IACrB,GAAG,aAAa,QAAQ,EAAE,mBAAmB,KAC1C,KAAI,YAAW,aAAa;EAAE,GAAG;EAAU;CAAQ,CAAC,CAAC,CAAC,CACtD,KAAK,IAAI,EAAE;AACpB;A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C0B;CAC1B,MAAM,OAAO,eAAe,GAAG,KAAK;CACpC,MAAM,OAAO,IAAI,IAAI,SAAS;CAC9B,OAAO,CACL,GAAG,KAAK,WAAW,QAAO,cAAa,CAAC,KAAK,IAAI,SAAS,CAAC,GAC3D,GAAG,YAAY,KAAK,WAAW,SAAS,CAC1C;AACF;;;;;AAMA,MAAM,eACJ,MACA,cAEA,KACG,QAAO,aAAY,OAAO,OAAO,SAAS,SAAS,KAAK,CAAC,UAAU,IAAI,QAAQ,CAAC,CAAC,CACjF,KAAI,aAAY,YAAY,UAAU,SAAS,CAAC;;AAGrD,MAAM,gBAAgB,aACpB,SAAS,YAAY,IAAI,SAAS,KAAK,GAAG,SAAS,GAAG,GAAG,SAAS;AAEpE,MAAM,UAAqD;CACzD,IAAI;CACJ,KAAK;CACL,IAAI;CACJ,KAAK;AACP;;AAGA,MAAM,iBAAiB,SACrB,MAAM,MAAM,IAAI,CAAC,CAAC,KAChB,MAAM,KAAK;CAAE,WAAW,IAAI,SAAS,IAAI,EAAE;CAAI,UAAU,IAAI,SAAS,IAAI,EAAE;AAAG,CAAC,GAChF,MAAM,aAAa,SAAS,IAAI,CAAC,CACnC;AAEF,MAAM,eAAe,SACnB,YAAY,IAAI,IAAI,IAAI,SAAS,IAAI,EAAE,KAAK,SAAS,IAAI"}
1
+ {"version":3,"file":"expr.js","names":["Arr"],"sources":["../src/expr.ts"],"sourcesContent":["/**\n * `Expr` — a query's scalar computations as typed values.\n *\n * An Entity says what a domain has; an `Expr` says something about one row of\n * it. A field reference, an input placeholder, a literal, and comparisons of\n * those are all immutable data: building one performs no work, reads nothing,\n * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`\n * to SQL, an in-memory evaluator to a predicate over rows.\n *\n * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every\n * operation here is one a real query in this repository needs; the set grows\n * from queries, not from what a database could express.\n */\nimport { Array as Arr, Match, Option, Pipeable, Schema, SchemaAST } from 'effect'\nimport { absurd } from 'effect/Function'\nimport { Collation } from './collation.js'\nimport { SchemaShape } from './shape.js'\nimport { Law, type Side } from './law.js'\nimport { now, viewer, type NowExpr, type ViewerExpr, type ViewerPathExpr } from './context.js'\nimport { own, put } from './record.js'\nimport { variantsOf } from './variants.js'\nimport type {\n AnyEntity,\n AnyVariantEntity,\n Cardinality,\n EntityField,\n EntityIdentity,\n EntityRelation,\n IdOf,\n} from './index.js'\n\n/** A constant the query was written with. */\nexport interface LiteralExpr<T> {\n readonly _tag: 'Literal'\n readonly value: T\n}\n\n/**\n * One field of one Entity. `owner` is the Entity's identity rather than its\n * name, so two Entities defined with the same name are not one column.\n */\nexport interface FieldExpr<T> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<string>\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n /**\n * How it compares when ordered by, as the field declares (`Collation.of`).\n * An id is `binary` unless it says otherwise: its order need only be total\n * and agreed, and every order ends on it.\n */\n readonly collation: Option.Option<Collation>\n}\n\n/**\n * A value the query is given when it runs. A definition's body is built once,\n * so inside it an input is this placeholder and never the value: there is\n * nothing yet to branch on, and a query that wants to depend on what was passed\n * says so with an operation over the placeholder.\n */\nexport interface InputExpr<T> {\n readonly _tag: 'Input'\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/**\n * A field as the row a write would leave holds it: what an invariant reads\n * (`after.status`, beside `before.status` over a change). An interpreter that judges stored\n * rows alone refuses it, as the operation `next`.\n */\nexport interface NextExpr<T> {\n readonly _tag: 'Next'\n readonly field: FieldExpr<T>\n}\n\n/**\n * What an operator is, as the nodes that call it hold it: its identity, the\n * stored form of what it takes and gives, and, for an operator defined by an\n * expression, how to build that expression. It computes nothing itself.\n * Identity is this object; `id` and `version` name it.\n */\nexport interface OperatorDescriptor {\n readonly _tag: 'Operator'\n readonly id: string\n readonly version: number\n readonly description: Option.Option<string>\n /** One schema per argument, read as the stored form. */\n readonly input: ReadonlyArray<Schema.Top>\n readonly output: Schema.Top\n /**\n * Builds the expression a call means, from its arguments: an operator defined\n * by an expression. None for a primitive operator, which each interpreter\n * implements (`Operators`).\n */\n readonly definedAs: Option.Option<(...args: ReadonlyArray<Operandish>) => Operandish>\n /**\n * A primitive operator's null rule. `strict`: a null argument gives null, or\n * unknown for a predicate, and the implementation never sees one. `handled`:\n * the implementation is given nulls and answers for them.\n */\n readonly nulls: 'strict' | 'handled'\n /**\n * How a call compares text. `operands`: it carries the collation its collated\n * text arguments share, so its text result compares under it. `required`: the\n * same, refused where none is declared (it compares text itself, as\n * `Text.startsWith` does). `none`: it carries none.\n */\n readonly collation: 'none' | 'operands' | 'required'\n /** The equations every implementation keeps (`Law`), checked where declared, tested by `Conformance.laws`. */\n readonly laws: ReadonlyArray<Law>\n}\n\n/** What an interpreter runs, as far as a check of a body needs to know. */\nexport interface OperatorTable {\n /** Whether this table implements the operator. */\n readonly has: (operator: OperatorDescriptor) => boolean\n /**\n * The versions of the operator `id` it implements: what a refusal of a call\n * to another version names, since a client and a server on different\n * deploys can disagree on one.\n */\n readonly versions: (id: string) => ReadonlyArray<number>\n}\n\n/** A table implementing nothing: every primitive operator is unsupported by it. */\nexport const noOperators: OperatorTable = Object.freeze({ has: () => false, versions: () => [] })\n\n/**\n * An operator `operators` does not implement, by name, with the versions of it\n * the table does implement: `acme.slug@2 (this table has acme.slug)`.\n */\nexport const missingName = (operator: OperatorDescriptor, operators: OperatorTable): string => {\n const held = operators.versions(operator.id)\n // The same name and version from another `Expr.operator` call: a table holds\n // declarations, not names, so it is a different operator.\n if (held.includes(operator.version)) {\n return `${operatorName(operator)} (this table has another declaration of it; declare an operator once and import it)`\n }\n return held.length === 0\n ? operatorName(operator)\n : `${operatorName(operator)} (this table has ${held\n .map(version => operatorName({ ...operator, version }))\n .join(', ')})`\n}\n\n/**\n * A call of an operator whose result is a scalar. `expansion` is the\n * expression it means, built from its arguments when it was called: an\n * interpreter runs that, and needs nothing of its own for the operator.\n */\nexport interface CallExpr<T> {\n readonly _tag: 'Call'\n readonly operator: OperatorDescriptor\n readonly args: ReadonlyArray<Operandish>\n readonly expansion: Option.Option<Expr<T>>\n /** How its text result compares, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/** A `one` relation of any Entity: what a path follows and an exists points through. */\nexport type OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/**\n * A field of the row reached from the row judged by following `one`\n * relations (`Expr.path`). A null link, or a row the reader may not see,\n * reaches no row, and the path reads null.\n */\nexport interface PathExpr<T> {\n readonly _tag: 'Path'\n /** The relations followed, in order, the first one the judged row's own. */\n readonly via: Arr.NonEmptyReadonlyArray<OneRelation>\n /** What is read on the row reached: a field of the last relation's target. */\n readonly field: FieldExpr<T>\n}\n\n/** A typed scalar: what a comparison compares. */\nexport type Expr<T> =\n | LiteralExpr<T>\n | FieldExpr<T>\n | InputExpr<T>\n | NextExpr<T>\n | CallExpr<T>\n | ViewerExpr<T>\n | NowExpr<T>\n | PathExpr<T>\n | ViewerPathExpr<T>\n\n/** Any scalar, for the places that hold operands without caring what they are. */\nexport type AnyExpr = Expr<unknown>\n\n/**\n * `Expr<boolean>`, in the shape the operations that exist can actually take.\n * The design's kernel is all boolean-valued (`eq`, `and`, `isNull`,\n * `contains`, …), so a predicate is its own type rather than a phantom\n * parameter on a general operation node: `Predicate` and `Expr<string>` cannot\n * then be confused, which a structural phantom would allow. A scalar-valued\n * operation, if one is ever needed, joins `Expr` instead.\n */\nexport type Predicate =\n | EqPredicate\n | NullPredicate\n | ContainsPredicate\n | InPredicate\n | AndPredicate\n | OrPredicate\n | NotPredicate\n | ComparePredicate\n | TestPredicate\n | ExistsPredicate\n\n/**\n * Some row points at the row asked about through `relation`, a `one` relation\n * of another Entity, and holds `where` (`Expr.exists`). The row asked about is\n * the one judged, or the one `via` reaches from it; a path that reaches none\n * makes this unknown, as a path's field reads null. Only rows the reader may\n * see are sought.\n */\nexport interface ExistsPredicate {\n readonly _tag: 'Exists'\n /** The relations followed to the row asked about; empty for the row judged itself. */\n readonly via: ReadonlyArray<OneRelation>\n readonly relation: OneRelation\n /** What the pointing row must hold, over its own fields and the input. */\n readonly where: Option.Option<Predicate>\n}\n\n/** Two values are the same. */\nexport interface EqPredicate {\n readonly _tag: 'Eq'\n readonly left: Operandish\n readonly right: Operandish\n}\n\n/**\n * Whether a value is absent. `present` says which answer absence gives, so one\n * node covers `is null` and `is not null` rather than two that differ by a\n * negation nothing else can express.\n */\nexport interface NullPredicate {\n readonly _tag: 'Null'\n readonly operand: AnyExpr\n readonly present: boolean\n}\n\n/**\n * Whether a text value contains another. Containing the empty string is\n * everything, which is what lets a search box with nothing typed in it be the\n * same query as one with something — see `Expr.contains`.\n */\nexport interface ContainsPredicate {\n readonly _tag: 'Contains'\n readonly value: AnyExpr\n readonly search: Operandish\n}\n\n/**\n * Whether a value is one of a list. The list is a scalar whose value is an\n * array: a literal, or an input (a principal's `projectIds`, a picker's\n * chosen ids). Read as SQL's `in`: a null value is unknown, and so is no\n * match against a list holding a null; an empty list matches nothing.\n */\nexport interface InPredicate {\n readonly _tag: 'In'\n readonly value: AnyExpr\n readonly among: AnyExpr\n}\n\n/**\n * Every operand holds. `Query.where`'s list is already a conjunction; this is\n * one inside something else, `or(and(a, b), c)`. Never empty, and never holding\n * another `and`: `Expr.and` flattens one into its parent.\n */\nexport interface AndPredicate {\n readonly _tag: 'And'\n readonly operands: Arr.NonEmptyReadonlyArray<Predicate>\n}\n\n/** At least one operand holds. Never empty, and never holding another `or`. */\nexport interface OrPredicate {\n readonly _tag: 'Or'\n readonly operands: Arr.NonEmptyReadonlyArray<Predicate>\n}\n\n/**\n * The operand does not hold. As SQL's `not`, an unknown stays unknown, so a row\n * whose operand is unknown (a null compared) is matched by neither the operand\n * nor its `not`.\n */\nexport interface NotPredicate {\n readonly _tag: 'Not'\n readonly operand: Predicate\n}\n\n/** Which way a comparison orders its two sides: `left < right` for `lt`. */\nexport type CompareOperator = 'lt' | 'lte' | 'gt' | 'gte'\n\n/**\n * One scalar orders before, or after, the other. A null on either side is\n * unknown. `collation` is how text compares, decided where the comparison is\n * written (see `Expr.lt`); none for values that order intrinsically, numbers.\n */\nexport interface ComparePredicate {\n readonly _tag: 'Compare'\n readonly operator: CompareOperator\n readonly left: AnyExpr\n readonly right: AnyExpr\n readonly collation: Option.Option<Collation>\n}\n\n/**\n * A call of an operator whose result is a boolean, so it stands where any\n * predicate does: in `and`, `or` and `not`, a guard, an invariant. `expansion`\n * is the predicate it means, built when it was called.\n */\nexport interface TestPredicate {\n readonly _tag: 'Test'\n readonly operator: OperatorDescriptor\n readonly args: ReadonlyArray<Operandish>\n readonly expansion: Option.Option<Predicate>\n /** The collation it compares text under, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/**\n * Anything an operation can be given: a scalar, or a predicate where a boolean\n * is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the\n * second case, and it is how a query depends on an input without branching on\n * it.\n */\nexport type Operandish = AnyExpr | Predicate\n\n/**\n * A field, a `one` relation (the id it points at), a scalar already built from\n * one, or a predicate used as a boolean.\n */\ntype Operand<T> = OwnOperand<T> | OneRelation\n\n/** A field, a scalar, or a predicate: what an order term takes, since no list orders by a link. */\ntype OwnOperand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> | Predicate\n\n/**\n * Type-only: the Entities a predicate's fields belong to, by name, so\n * `Query.where` can refuse one over another Entity where it is written. Never\n * set at run time; a predicate built without it (typed plain `Predicate`)\n * reads as unknown and is checked at run time only.\n */\nexport interface Reads<Names extends string> {\n readonly '~reads'?: Names\n}\n\n/**\n * The Entity names an operand reads: a field's own, a marked node's, none for\n * a value or an input. A node with no marker (a `Predicate` typed plainly)\n * reads as `string`, unknown.\n */\nexport type ReadsOf<X> =\n X extends EntityField<infer Name, string, Schema.Constraint>\n ? Name\n : X extends EntityRelation<infer Name, string, AnyEntity, 'one', boolean>\n ? Name\n : X extends PlainValue | { readonly _tag: 'Literal' | 'Input' | 'Viewer' | 'Now' }\n ? never\n : X extends { readonly '~reads'?: infer Names }\n ? unknown extends Names\n ? string\n : Names extends string\n ? Names\n : never\n : never\n\n/**\n * Nothing when a query's predicates read its own Entity, none, or one unknown\n * to the type (checked at run time instead); else a failure naming both.\n */\ntype OverEntity<\n Names extends string,\n Name extends string,\n What extends string,\n> = string extends Names\n ? unknown\n : [Names] extends [Name]\n ? unknown\n : Invalid<`foldkit-entity: ${What} reads ${Exclude<Names, Name>}, but the query is from ${Name}`>\n\n/** A plain value, which `Expr.eq` takes on the right only. */\ntype PlainValue = string | number | boolean | bigint | null\n\n/** A compile-time failure whose type is the sentence that says what to do. */\nexport interface Invalid<Message extends string> {\n readonly '~invalid': Message\n}\n\n/** What an operand is worth, so a comparison's other side is checked against it. */\nexport type ValueOf<E> =\n E extends EntityField<string, string, infer S>\n ? Schema.Schema.Type<S>\n : E extends EntityRelation<string, string, infer Target, 'one', infer Optional>\n ? IdOf<Target> | (Optional extends true ? null : never)\n : E extends Predicate\n ? boolean\n : E extends Expr<infer T>\n ? T\n : never\n\n/**\n * A field or scalar whose value is text, or absent text.\n *\n * `Expr.contains` is a case-insensitive **text** search that compiles to\n * `lower(column) like lower(?)`. Over a number that is nonsense which reaches\n * the database — SQLite coerces and answers something, Postgres raises — so\n * the operand is constrained here rather than discovered there.\n *\n * Null belongs in the type, because a nullable text column is a real and\n * documented case: a null contains nothing, not even the empty string, so its\n * rows drop out of a search that would otherwise match everything.\n *\n * Written as a **constraint on the type parameter** rather than as a check\n * intersected onto the parameter (the `Invalid` idiom `foldkit-remote` uses for\n * an unregistered descriptor). That idiom compares an already-resolved indexed\n * access; here the check would be a conditional over the type being inferred,\n * and inference falls back to the constraint — whose `Expr<any>` branch makes\n * the check vacuously true, so every operand passes. A constraint cannot be\n * defeated that way.\n */\nexport type TextOperand =\n | EntityField<string, string, Schema.Constraint & Schema.Codec<string | null, any, any, any>>\n | Expr<string>\n | Expr<string | null>\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && '_tag' in value ? value._tag : undefined\n\n/**\n * An Entity's field and a `FieldExpr` are the same three members under the same\n * tag — the Entity's carries `metadata` besides — so this reads either and is\n * idempotent on its own output. Nothing needs to tell them apart, which is\n * better than telling them apart by which extra member happens to be present.\n */\n/**\n * Every node is frozen as it is made, so a query built from it stays the value\n * it was when `Query.where` checked it: nothing can swap a field or a literal\n * in afterwards. It also means no node can come to contain itself. A literal's\n * own payload is the caller's; the kernel compares scalars.\n */\nconst node = <T extends object>(value: T): T => Object.freeze(value)\n\nconst literal = <T>(value: T): LiteralExpr<T> => node({ _tag: 'Literal', value })\n\nconst fieldExpr = (field: EntityField<string, string, Schema.Constraint>): FieldExpr<unknown> =>\n node({\n _tag: 'Field',\n owner: field.owner,\n key: field.key,\n schema: field.schema as unknown as Schema.Codec<unknown, unknown>,\n collation: Option.orElse(Collation.declared(field.metadata), () =>\n field.key === 'id' ? Option.some(Collation.binary) : Option.none(),\n ),\n })\n\n/**\n * A `one` relation read as a value: the id of the row it points at, null for\n * none. It is the member the row holds under the relation's key, so it is a\n * field of the owner to every interpreter: a row given to one holds it as that\n * id, and SQL reads the column the relation is stored on.\n */\nconst linkExpr = (relation: OneRelation): FieldExpr<unknown> =>\n node({\n _tag: 'Field',\n owner: relation.owner,\n key: relation.key,\n // A ref's id travels as text, as `Expr.viewer`'s does, so the two compare.\n schema: (relation.optional\n ? Schema.NullOr(Schema.String)\n : Schema.String) as unknown as Schema.Codec<unknown, unknown>,\n // Nothing orders by one: a list refuses it, and a comparison takes an ordered operand.\n collation: Option.none(),\n })\n\nconst predicateTags = new Set([\n 'Eq',\n 'Null',\n 'Contains',\n 'In',\n 'And',\n 'Or',\n 'Not',\n 'Compare',\n 'Test',\n 'Exists',\n])\n\n/** Whether a value is a predicate, and so usable where a boolean is wanted. */\nexport const isPredicate = (value: unknown): value is Predicate =>\n predicateTags.has(tagOf(value) as string)\n\n/**\n * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is\n * itself, and anything else is the constant it is.\n */\nconst toOperand = <T>(value: Operand<T> | T): Operandish => {\n const tag = tagOf(value)\n // An `EntityField` and a `FieldExpr` share the tag. A `FieldExpr` is already\n // built, its collation with it, which its field's metadata no longer holds.\n if (tag === 'Field' && !Object.hasOwn(value as object, 'metadata')) {\n return value as FieldExpr<unknown>\n }\n if (tag === 'Field') {\n return fieldExpr(value as EntityField<string, string, Schema.Constraint>)\n }\n if (tag === 'Relation') {\n const relation = value as EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n if (relation.cardinality !== 'one') {\n throw new Error(\n `[foldkit-entity] ${relation.owner.name}.${relation.key} is a many relation, which holds no one value; ask Expr.exists of the relation that points back`,\n )\n }\n return linkExpr(relation as OneRelation)\n }\n if (\n tag === 'Literal' ||\n tag === 'Input' ||\n tag === 'Next' ||\n tag === 'Call' ||\n tag === 'Viewer' ||\n tag === 'Now' ||\n tag === 'Path' ||\n tag === 'ViewerPath' ||\n predicateTags.has(tag as string)\n ) {\n return value as Operandish\n }\n return literal(value)\n}\n\n/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */\nconst toExpr = <T>(value: Operand<T> | T, step: string): AnyExpr => {\n const operand = toOperand(value)\n if (isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`,\n )\n }\n return operand\n}\n\n/**\n * Every operation the kernel has. An interpreter declares which of them it\n * runs, and a body needing one it does not is refused rather than answered\n * wrongly — see `Query.unsupported`.\n */\nexport type Operation =\n | 'eq'\n | 'isNull'\n | 'isNotNull'\n | 'contains'\n | 'in'\n | 'and'\n | 'or'\n | 'not'\n | 'compare'\n | 'next'\n | 'viewer'\n | 'now'\n | 'path'\n | 'exists'\n\n/** One field an expression reads: its Entity's name and key, and the identity that owns it. */\nexport interface FieldDependency {\n /** The owning Entity's name, for display; two Entities may share one. */\n readonly entity: string\n readonly key: string\n /** Which Entity it is. Two defined with the same name are two entries. */\n readonly owner: EntityIdentity<string>\n}\n\n/** Which fields and inputs an expression reads, and which operations it uses. */\nexport interface Dependencies {\n /** One entry per distinct field of each Entity identity. */\n readonly fields: ReadonlyArray<FieldDependency>\n /** Each field read as the row a write would leave holds it (`Next`), one entry each. */\n readonly next: ReadonlyArray<FieldDependency>\n /** One entry per distinct input key. */\n readonly inputs: ReadonlyArray<string>\n /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */\n readonly operations: ReadonlyArray<Operation>\n /** Each operator it calls, once per descriptor, defined or not. */\n readonly operators: ReadonlyArray<OperatorDescriptor>\n /**\n * Each path, exists and path from the viewer, once each: what it reads lies\n * in other rows, so none of it is in `fields`. An exists' filter's inputs,\n * operations and operators are in the lists above.\n */\n readonly reaches: ReadonlyArray<PathExpr<unknown> | ExistsPredicate | ViewerPathExpr<unknown>>\n}\n\n/**\n * What a query reads, with each field's role. A change to a `predicate` field\n * can move a row into or out of the result; a change to an `order` field can\n * move it within. A field in both is in both; `fields` is their union.\n */\nexport interface QueryDependencies extends Dependencies {\n readonly predicate: ReadonlyArray<FieldDependency>\n readonly order: ReadonlyArray<FieldDependency>\n}\n\n/**\n * A field or scalar whose value orders: a number, text, a date (which orders by\n * its encoded form), or one of those absent. A boolean does not order here.\n * A constraint on the type parameter, as `TextOperand` is, so inference cannot\n * fall back past it.\n */\nexport type OrderedOperand =\n | EntityField<\n string,\n string,\n Schema.Constraint & Schema.Codec<number | string | Date | null, any, any, any>\n >\n | Expr<number>\n | Expr<number | null>\n | Expr<string>\n | Expr<string | null>\n | Expr<Date>\n | Expr<Date | null>\n\n/** How values encoded by `ast` order: as numbers, as text, or not at all. */\nconst orderKindOf = (ast: SchemaAST.AST): 'number' | 'text' | 'none' => {\n if (SchemaAST.isNumber(ast)) return 'number'\n if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return 'text'\n if (SchemaAST.isLiteral(ast)) {\n if (typeof ast.literal === 'number') return 'number'\n if (typeof ast.literal === 'string') return 'text'\n return 'none'\n }\n if (SchemaAST.isUnion(ast)) {\n // A null orders nowhere, as every comparison of it is unknown.\n const kinds = new Set(ast.types.filter(member => !SchemaAST.isNull(member)).map(orderKindOf))\n const [only] = kinds\n return kinds.size === 1 && only !== undefined ? only : 'none'\n }\n return 'none'\n}\n\n/** How a literal orders; a null orders as anything, since comparing it is unknown. */\nconst literalKind = (value: unknown): 'number' | 'text' | 'none' | 'null' => {\n if (value === null) return 'null'\n if (typeof value === 'number') return 'number'\n if (typeof value === 'string') return 'text'\n return 'none'\n}\n\n/** How a side orders, read from its encoded form. */\nconst sideKind = (side: AnyExpr): 'number' | 'text' | 'none' | 'null' =>\n Match.value(side).pipe(\n Match.tagsExhaustive({\n Field: field => orderKindOf(Schema.toEncoded(field.schema).ast),\n Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),\n Input: input => orderKindOf(Schema.toEncoded(input.schema).ast),\n Literal: ({ value }) => literalKind(value),\n Call: ({ operator }) => orderKindOf(Schema.toEncoded(operator.output).ast),\n Viewer: ({ schema }) => orderKindOf(Schema.toEncoded(schema).ast),\n Now: ({ schema }) => orderKindOf(Schema.toEncoded(schema).ast),\n Path: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),\n ViewerPath: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),\n }),\n )\n\n/**\n * How a comparison's text compares: the collation given, else the field's\n * declared one. Text orders differently by backend (SQLite's `BINARY`, the\n * Postgres database's locale, JavaScript's UTF-16 units), so it is compared\n * only under `binary` or `asciiFold`, which every interpreter here agrees on,\n * and only against a field, whose collation it is. Values that order\n * intrinsically, numbers, need none.\n */\nconst collationFor = (\n step: CompareOperator,\n left: AnyExpr,\n right: AnyExpr,\n given: Option.Option<Collation>,\n): Option.Option<Collation> => {\n const kinds = new Set([sideKind(left), sideKind(right)].filter(kind => kind !== 'null'))\n if (kinds.has('none') || kinds.size > 1) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: only numbers with numbers, or text with text, order alike in every interpreter, as stored`,\n )\n }\n if (!kinds.has('text')) return Option.none()\n // The sides that can say how text orders: a field, as declared, or a call, as its\n // operator's rule carries one. A literal or an input says nothing.\n const fields = [left, right].flatMap(side =>\n Match.value(side).pipe(\n Match.tagsExhaustive({\n Field: field => [{ name: `${field.owner.name}.${field.key}`, collation: field.collation }],\n Next: ({ field }) => [\n { name: `${field.owner.name}.${field.key}`, collation: field.collation },\n ],\n Call: call => [{ name: showExpr(call), collation: call.collation }],\n Path: path => [{ name: showExpr(path), collation: path.field.collation }],\n ViewerPath: path => [{ name: showExpr(path), collation: path.field.collation }],\n Literal: () => [],\n Input: () => [],\n Viewer: () => [],\n Now: () => [],\n }),\n ),\n )\n const [first] = fields\n if (first === undefined) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: text compared with no field, nor a call carrying a collation, to say how it orders`,\n )\n }\n const named = fields.map(field => field.name).join(' and ')\n const collations = Option.match(given, {\n onSome: collation => [collation],\n onNone: () =>\n fields.map(field =>\n Option.getOrElse(field.collation, () => {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${field.name} is text with no declared collation, so backends would order it differently; declare Collation.binary or Collation.asciiFold on it, or pass one`,\n )\n }),\n ),\n })\n const [collation] = collations\n if (collation === undefined || collations.some(each => each._tag !== collation._tag)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${named} declare different collations; pass one to compare them by`,\n )\n }\n return Match.value(collation).pipe(\n Match.tagsExhaustive({\n Binary: () => Option.some(collation),\n AsciiFold: () => Option.some(collation),\n Locale: ({ locale }) => {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${named} compares by the backend's \"${locale}\" collation, which only that backend has`,\n )\n },\n }),\n )\n}\n\n/** `Expr.lt` and its three siblings: the operator fixed, the sides typed alike. */\nconst comparison =\n (operator: CompareOperator) =>\n <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(\n left: L,\n right: R,\n options: { readonly collation?: Collation | undefined } = {},\n ): ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>> => {\n const leftSide = toExpr<unknown>(left, operator)\n const rightSide = toExpr<unknown>(right, operator)\n return node({\n _tag: 'Compare',\n operator,\n left: leftSide,\n right: rightSide,\n collation: collationFor(\n operator,\n leftSide,\n rightSide,\n Option.fromUndefinedOr(options.collation),\n ),\n })\n }\n\n/** A connective's operands, each checked to be a predicate, with one of the same kind flattened in. */\nconst connected = (\n step: 'and' | 'or',\n kind: 'And' | 'Or',\n given: ReadonlyArray<unknown>,\n): Arr.NonEmptyReadonlyArray<Predicate> => {\n const operands = given.flatMap((operand): ReadonlyArray<Predicate> => {\n if (!isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: every operand is a predicate; compare a value with Expr.eq first`,\n )\n }\n return Match.value(operand).pipe(\n Match.tags({\n And: and => (kind === 'And' ? and.operands : [and]),\n Or: or => (kind === 'Or' ? or.operands : [or]),\n }),\n Match.orElse(() => [operand]),\n )\n })\n // Flattening copies a shared operand's list, so `or(x, x)` built thirty deep\n // would be 2^30 operands before the budget ever counts them.\n if (operands.length > maxQueryNodes) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: more than ${maxQueryNodes} operands, the most a query's predicates may hold`,\n )\n }\n if (!Arr.isReadonlyArrayNonEmpty(operands)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: no operands, which would match ${step === 'and' ? 'every row' : 'no row'}; check a list is non-empty before spreading it`,\n )\n }\n return operands\n}\n\n/** `Expr.and` and `Expr.or`: one operand is that operand, and two or more are one node. */\ninterface Connective<Node extends Predicate> {\n <P extends Predicate>(only: P): P\n <A extends Predicate, B extends Predicate, Rest extends ReadonlyArray<Predicate>>(\n first: A,\n second: B,\n ...rest: Rest\n ): Node & Reads<ReadsOf<A> | ReadsOf<B> | ReadsOf<Rest[number]>>\n (...operands: Arr.NonEmptyReadonlyArray<Predicate>): Predicate\n}\n\nconst connective =\n <Node extends AndPredicate | OrPredicate>(step: 'and' | 'or', kind: Node['_tag']) =>\n (...given: ReadonlyArray<Predicate>): Predicate => {\n const operands = connected(step, kind, given)\n return operands.length === 1 ? operands[0] : node({ _tag: kind, operands } as Node)\n }\n\n/** A schema's stored form, which is what an operator takes and gives. */\ntype StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>\n\n/**\n * One argument an operator may be called with: a field or scalar stored as the\n * input's stored type, a predicate where it takes a boolean, or a plain value.\n */\nexport type ArgumentOf<S extends Schema.Top> =\n | EntityField<string, string, Schema.Constraint & Schema.Codec<any, StoredOf<S>, any, any>>\n | Expr<StoredOf<S>>\n | (boolean extends StoredOf<S> ? Predicate : never)\n | StoredOf<S>\n\n/** What `definedAs` is handed for one argument: the argument as a node. */\nexport type ParameterOf<S extends Schema.Top> =\n | Expr<StoredOf<S>>\n | (boolean extends StoredOf<S> ? Predicate : never)\n\n/** A call's node: a predicate for a boolean result, a scalar for anything else. */\ntype CallOf<Out extends Schema.Top> = [StoredOf<Out>] extends [boolean]\n ? TestPredicate\n : CallExpr<StoredOf<Out>>\n\n/** What `definedAs` builds: a predicate for a boolean result, a scalar otherwise. */\ntype BodyOf<Out extends Schema.Top> = [StoredOf<Out>] extends [boolean]\n ? Predicate\n : Expr<StoredOf<Out>>\n\n/**\n * An operator: called like a function, it builds a node that holds `descriptor`\n * and its arguments. See `Expr.operator`.\n */\nexport interface Operator<In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top> {\n <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]> }>(\n ...args: A\n ): CallOf<Out> & Reads<ReadsOf<A[number]>>\n /**\n * A call comparing text under the collation given, rather than its text\n * arguments' declared one: for an operator whose `collation` is `operands`\n * or `required`, as `Expr.lt(field, value, { collation })` is.\n */\n <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]> }>(\n ...args: [...A, CallOptions]\n ): CallOf<Out> & Reads<ReadsOf<A[number]>>\n readonly descriptor: OperatorDescriptor\n}\n\n/** What a call may say past its arguments. */\nexport interface CallOptions {\n /** The collation it compares text under, in place of its arguments' declared one. */\n readonly collation: Collation\n}\n\nconst collationTags = new Set(['Binary', 'AsciiFold', 'Locale'])\n\n/** A call's last value, when it is one past the arguments: its options, checked. */\nconst callOptionsOf = (id: string, value: unknown): Collation => {\n const collation =\n typeof value === 'object' && value !== null && Object.hasOwn(value, 'collation')\n ? (value as { readonly collation: unknown }).collation\n : undefined\n if (!collationTags.has(tagOf(collation) as string)) {\n throw new Error(\n `[foldkit-entity] ${id}: a value past its arguments is \\`{ collation }\\`, a Collation`,\n )\n }\n return collation as Collation\n}\n\n/** A collation a call was given: one its operator compares by, and portable where required. */\nconst givenCollation = (\n id: string,\n descriptor: OperatorDescriptor,\n collation: Collation,\n): Option.Option<Collation> => {\n if (Option.isSome(descriptor.definedAs) || descriptor.collation === 'none') {\n throw new Error(`[foldkit-entity] ${id}: takes no collation; it compares no text of its own`)\n }\n // No call carries a locale: the client could not run it, and SQL compiles none.\n if (collation._tag === 'Locale') {\n throw new Error(\n `[foldkit-entity] ${id}: compares by the backend's \"${collation.locale}\" collation, which only that backend has`,\n )\n }\n return Option.some(collation)\n}\n\n/** Namespaced, lower camel case: `cms.published`, `text.startsWith`. */\nconst operatorId = /^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)+$/\n\n/**\n * Why `law` cannot be declared of an operator of this shape, if it cannot: an\n * equation over two arguments of a unary operator, a witness that does not\n * decode as the argument it stands in, or a collation law of an operator\n * whose text keeps none.\n */\nconst lawProblem = (\n law: Law,\n input: ReadonlyArray<Schema.Top>,\n output: Schema.Top,\n collation: OperatorDescriptor['collation'],\n): Option.Option<string> => {\n const name = Law.describe(law).kind\n const binary = (): Option.Option<string> =>\n input.length === 2\n ? Option.none()\n : Option.some(\n `${name} is a law of an operator of two arguments, and this one takes ${input.length}`,\n )\n const decodes = (value: unknown, schema: Schema.Top, what: string): Option.Option<string> =>\n Schema.is(Schema.toEncoded(schema))(value)\n ? Option.none()\n : Option.some(`${name}'s ${what} ${JSON.stringify(value)} does not decode as its schema`)\n const sides = (value: unknown, side: Side): Option.Option<string> =>\n Option.orElse(binary(), () =>\n Option.orElse(\n side === 'right' ? Option.none() : decodes(value, input[0]!, 'left witness'),\n () => (side === 'left' ? Option.none() : decodes(value, input[1]!, 'right witness')),\n ),\n )\n return Law.$match(law, {\n Associative: binary,\n Commutative: binary,\n Idempotent: binary,\n Identity: ({ value, side }) => sides(value, side),\n Absorbing: ({ value, side }) => sides(value, side),\n Inverse: ({ other, identity }) =>\n Option.orElse(binary(), () =>\n other.descriptor.input.length === 1\n ? decodes(identity, output, 'identity')\n : Option.some(`${name}'s other operator takes one argument`),\n ),\n Distributes: ({ over }) =>\n Option.orElse(binary(), () =>\n over.descriptor.input.length === 2\n ? Option.none()\n : Option.some(`${name} is over an operator of two arguments`),\n ),\n Monotonic: ({ position }) =>\n Number.isSafeInteger(position) && position >= 0 && position < input.length\n ? Option.none()\n : Option.some(`${name}'s position ${position} is not an argument's`),\n PreservesCollation: () =>\n collation === 'operands'\n ? Option.none()\n : Option.some(`${name} is a law of an operator declared \\`collation: 'operands'\\``),\n })\n}\n\n/** Whether a schema's stored form is a boolean, which makes its operator a predicate. */\nconst storedAsBoolean = (schema: Schema.Top): boolean =>\n SchemaAST.isBoolean(Schema.toEncoded(schema).ast)\n\n/** What a schema stores, null aside: one kind an argument is checked by, or `other`. */\nconst storedKindOf = (schema: Schema.Top): 'number' | 'text' | 'boolean' | 'other' => {\n const present = SchemaShape.present(Schema.toEncoded(schema).ast)\n if (present.length === 0) return 'other'\n if (present.every(SchemaAST.isNumber)) return 'number'\n if (present.every(SchemaShape.isText)) return 'text'\n if (present.every(SchemaAST.isBoolean)) return 'boolean'\n return 'other'\n}\n\n/** The schema a scalar's values are stored by. */\nconst scalarSchema = (scalar: AnyExpr): Schema.Top =>\n Match.value(scalar).pipe(\n Match.tagsExhaustive({\n Field: field => field.schema,\n Next: ({ field }) => field.schema,\n Input: input => input.schema,\n Literal: () => Schema.Unknown,\n Call: ({ operator }) => operator.output,\n Viewer: ({ schema }) => schema,\n Now: ({ schema }) => schema,\n Path: ({ field }) => field.schema,\n ViewerPath: ({ field }) => field.schema,\n }),\n )\n\n/** Every field, field after a write, and input an expression reads, as keys to compare. */\nconst readKeys = (...nodes: ReadonlyArray<Operandish>): ReadonlySet<string> => {\n const read = dependenciesOf(...nodes)\n const named = (prefix: string, fields: ReadonlyArray<FieldDependency>) =>\n fields.map(field => `${prefix}${field.entity}.${field.key}`)\n return new Set([\n ...named('', read.fields),\n ...named('next ', read.next),\n ...read.inputs.map(key => `$${key}`),\n ])\n}\n\n/** One argument, checked against the schema it is passed for, as a node. */\nconst argumentFor = (\n id: string,\n position: number,\n schema: Schema.Top,\n value: unknown,\n): Operandish => {\n const arg = toOperand(value)\n const fail = (what: string) => {\n throw new Error(`[foldkit-entity] ${id}: argument ${position + 1} ${what}`)\n }\n if (isPredicate(arg)) {\n // As `ArgumentOf` types it: wherever both booleans are stored, null beside them or not.\n const stored = Schema.is(Schema.toEncoded(schema))\n if (!stored(true) || !stored(false))\n fail('is a predicate, but the operator does not take a boolean')\n return arg\n }\n if (arg._tag === 'Literal') {\n if (!Schema.is(Schema.toEncoded(schema))(arg.value)) {\n fail(`is ${JSON.stringify(arg.value)}, which the operator's input schema does not admit`)\n }\n return arg\n }\n const wanted = storedKindOf(schema)\n const given = storedKindOf(scalarSchema(arg))\n if (wanted !== 'other' && given !== 'other' && given !== wanted) {\n fail(`is stored as ${given}, but the operator takes ${wanted}`)\n }\n return arg\n}\n\n/** A scalar's collation: a field's declared one, or a call's. */\nconst collationOf = (scalar: AnyExpr): Option.Option<Collation> =>\n Match.value(scalar).pipe(\n Match.tagsExhaustive({\n Field: field => field.collation,\n Next: ({ field }) => field.collation,\n Call: call => call.collation,\n Literal: () => Option.none<Collation>(),\n Input: () => Option.none<Collation>(),\n Viewer: () => Option.none<Collation>(),\n Now: () => Option.none<Collation>(),\n Path: ({ field }) => field.collation,\n ViewerPath: ({ field }) => field.collation,\n }),\n )\n\n/**\n * The collation a primitive call compares text under: the one its collated\n * text arguments share. A literal or an input carries none and does not vote.\n * `required` refuses a call with none, or with a backend's locale.\n */\nconst callCollation = (\n id: string,\n rule: OperatorDescriptor['collation'],\n args: ReadonlyArray<Operandish>,\n): Option.Option<Collation> => {\n if (rule === 'none') return Option.none()\n const fail = (what: string): never => {\n throw new Error(`[foldkit-entity] ${id}: ${what}`)\n }\n // Named only in a refusal: rendering each voter on every call is exponential in a\n // nesting of calls that share their arguments.\n const voters = args.flatMap(arg =>\n isPredicate(arg) || arg._tag === 'Literal' || arg._tag === 'Input' || sideKind(arg) !== 'text'\n ? []\n : [{ arg, collation: collationOf(arg) }],\n )\n const collations = voters.flatMap(({ arg, collation }) =>\n Option.match(collation, {\n onSome: each => [each],\n onNone: (): ReadonlyArray<Collation> =>\n rule === 'required'\n ? fail(\n `${showExpr(arg)} is text with no declared collation, so backends would compare it differently; declare Collation.binary or Collation.asciiFold on it`,\n )\n : [],\n }),\n )\n const [shared] = collations\n if (shared === undefined) {\n return rule === 'required'\n ? fail('compares text with no field or call holding a collation')\n : Option.none()\n }\n if (collations.some(each => each._tag !== shared._tag)) {\n fail(`${voters.map(voter => showExpr(voter.arg)).join(' and ')} declare different collations`)\n }\n if (shared._tag === 'Locale') {\n fail(`compares by the backend's \"${shared.locale}\" collation, which a call cannot carry`)\n }\n return Option.some(shared)\n}\n\n/** Builds an operator: checks what it is given once, then each call. */\nconst makeOperator = (\n id: string,\n options: {\n readonly input: ReadonlyArray<Schema.Top>\n readonly output: Schema.Top\n readonly version?: number | undefined\n readonly description?: string | undefined\n readonly definedAs?: ((...args: ReadonlyArray<Operandish>) => unknown) | undefined\n readonly nulls?: OperatorDescriptor['nulls'] | undefined\n readonly collation?: OperatorDescriptor['collation'] | undefined\n readonly laws?: ReadonlyArray<Law> | undefined\n },\n): Operator<ReadonlyArray<Schema.Top>, Schema.Top> => {\n const fail = (what: string): never => {\n throw new Error(`[foldkit-entity] Expr.operator(\"${id}\"): ${what}`)\n }\n if (!operatorId.test(id)) {\n fail('an id is namespaced lower camel case, as `cms.published`')\n }\n if (id.startsWith('foldkit.')) fail('ids under `foldkit.` are reserved')\n const version = options.version ?? 1\n if (!Number.isSafeInteger(version) || version < 1) fail('a version is a positive integer')\n if (!Array.isArray(options.input) || !options.input.every(Schema.isSchema)) {\n fail('`input` is one schema per argument')\n }\n if (!Schema.isSchema(options.output)) fail('`output` is a schema')\n const definedAs = Option.fromUndefinedOr(options.definedAs)\n if (Option.isSome(definedAs) && typeof definedAs.value !== 'function') {\n fail('`definedAs` builds what a call means')\n }\n // A defined operator means its body, null and text alike: it declares neither.\n if (\n Option.isSome(definedAs) &&\n (options.nulls !== undefined || options.collation !== undefined)\n ) {\n fail(\"a defined operator means its body, so `nulls` and `collation` are its body's\")\n }\n const nulls = options.nulls ?? 'strict'\n const collation = options.collation ?? 'none'\n if (nulls !== 'strict' && nulls !== 'handled') fail(\"`nulls` is 'strict' or 'handled'\")\n if (collation !== 'none' && collation !== 'operands' && collation !== 'required') {\n fail(\"`collation` is 'none', 'operands' or 'required'\")\n }\n const input = Object.freeze([...options.input])\n const predicate = storedAsBoolean(options.output)\n if (collation === 'operands' && orderKindOf(Schema.toEncoded(options.output).ast) !== 'text') {\n fail(\"`collation: 'operands'` describes a text result, and this one is not text\")\n }\n const laws = Object.freeze([...(options.laws ?? [])])\n for (const law of laws) {\n Option.match(lawProblem(law, input, options.output, collation), {\n onNone: () => undefined,\n onSome: fail,\n })\n }\n const descriptor: OperatorDescriptor = Object.freeze({\n _tag: 'Operator',\n id,\n version,\n description: Option.fromUndefinedOr(options.description),\n input,\n output: options.output,\n definedAs: definedAs as OperatorDescriptor['definedAs'],\n nulls,\n collation,\n laws,\n })\n /** A defined call's expansion, checked: of its output's kind, reading only its arguments. */\n const expand = (\n body: (...args: ReadonlyArray<Operandish>) => Operandish,\n args: ReadonlyArray<Operandish>,\n ): Operandish => {\n const expansion = toOperand(body(...args))\n if (predicate !== isPredicate(expansion)) {\n throw new Error(\n `[foldkit-entity] ${id}: its output is ${predicate ? 'a boolean, so `definedAs` returns a predicate' : 'not a boolean, so `definedAs` returns a scalar'}`,\n )\n }\n // An expansion reading what its arguments do not would hide a read from\n // anyone asking what the call depends on: Guard's checks, Remote's matching.\n const allowed = readKeys(...args)\n const hidden = [...readKeys(expansion)].filter(key => !allowed.has(key))\n if (hidden.length > 0) {\n throw new Error(\n `[foldkit-entity] ${id}: \\`definedAs\\` reads ${hidden.join(', ')}, which no argument holds; pass it as one`,\n )\n }\n return expansion\n }\n const call = (...written: ReadonlyArray<unknown>) => {\n // One value past the arguments is the call's options.\n const explicit =\n written.length === input.length + 1\n ? Option.some(callOptionsOf(id, written[written.length - 1]))\n : Option.none<Collation>()\n const given = Option.isSome(explicit) ? written.slice(0, -1) : written\n if (given.length !== input.length) {\n throw new Error(\n `[foldkit-entity] ${id}: takes ${input.length} argument${input.length === 1 ? '' : 's'}, given ${given.length}`,\n )\n }\n const args = Object.freeze(\n given.map((value, position) => argumentFor(id, position, input[position]!, value)),\n )\n const expansion = Option.map(descriptor.definedAs, body => expand(body, args))\n // A collation given wins; else a defined call's text compares as its body\n // does, and a primitive one's by its rule.\n const carried = Option.match(explicit, {\n onSome: each => givenCollation(id, descriptor, each),\n onNone: () =>\n Option.match(expansion, {\n onSome: body => (isPredicate(body) ? Option.none<Collation>() : collationOf(body)),\n onNone: () => callCollation(id, collation, args),\n }),\n })\n return predicate\n ? node<TestPredicate>({\n _tag: 'Test',\n operator: descriptor,\n args,\n expansion: expansion as Option.Option<Predicate>,\n collation: carried,\n })\n : node<CallExpr<unknown>>({\n _tag: 'Call',\n operator: descriptor,\n args,\n expansion: expansion as Option.Option<AnyExpr>,\n collation: carried,\n })\n }\n return Object.freeze(Object.assign(call, { descriptor })) as unknown as Operator<\n ReadonlyArray<Schema.Top>,\n Schema.Top\n >\n}\n\n/** Each defined call replaced by its expansion, deeply; built once per node. */\nconst expandedCache = new WeakMap<object, AnyExpr | Predicate>()\n\nconst expandedScalar = (scalar: AnyExpr): AnyExpr => {\n const known = expandedCache.get(scalar)\n if (known !== undefined) return known as AnyExpr\n const result =\n scalar._tag === 'Call'\n ? Option.match(scalar.expansion, {\n onSome: expandedScalar,\n // An operator with no definition stays, for an interpreter to run or refuse by\n // name; a defined one among its arguments is expanded all the same.\n onNone: () => node<AnyExpr>({ ...scalar, args: scalar.args.map(expandedSide) }),\n })\n : scalar\n expandedCache.set(scalar, result)\n return result\n}\n\nconst expandedSide = (side: Operandish): Operandish =>\n isPredicate(side) ? expandedPredicate(side) : expandedScalar(side)\n\nconst expandedPredicate = (predicate: Predicate): Predicate => {\n const known = expandedCache.get(predicate)\n if (known !== undefined) return known as Predicate\n const result: Predicate = Match.value(predicate).pipe(\n Match.tagsExhaustive({\n Eq: eq =>\n node<Predicate>({ ...eq, left: expandedSide(eq.left), right: expandedSide(eq.right) }),\n Null: nul => node<Predicate>({ ...nul, operand: expandedScalar(nul.operand) }),\n Contains: contains =>\n node<Predicate>({\n ...contains,\n value: expandedScalar(contains.value),\n search: expandedSide(contains.search),\n }),\n In: inPredicate =>\n node<Predicate>({\n ...inPredicate,\n value: expandedScalar(inPredicate.value),\n among: expandedScalar(inPredicate.among),\n }),\n And: and => node<Predicate>({ ...and, operands: Arr.map(and.operands, expandedPredicate) }),\n Or: or => node<Predicate>({ ...or, operands: Arr.map(or.operands, expandedPredicate) }),\n Not: not => node<Predicate>({ ...not, operand: expandedPredicate(not.operand) }),\n Compare: compare =>\n node<Predicate>({\n ...compare,\n left: expandedScalar(compare.left),\n right: expandedScalar(compare.right),\n }),\n Test: test =>\n Option.match(test.expansion, {\n onSome: expandedPredicate,\n onNone: () => node<Predicate>({ ...test, args: test.args.map(expandedSide) }),\n }),\n Exists: exists =>\n node<Predicate>({ ...exists, where: Option.map(exists.where, expandedPredicate) }),\n }),\n )\n expandedCache.set(predicate, result)\n return result\n}\n\n/** `Expr.path`'s two starts: a relation of the judged row, or the viewer's row. */\ninterface PathOf {\n <Owner extends string, Target extends AnyEntity, E extends PathEnd<Target['name']>>(\n relation: EntityRelation<Owner, string, Target, 'one', boolean>,\n end: E,\n ): (E extends ExistsPredicate ? ExistsPredicate : PathExpr<ValueOf<E> | null>) & Reads<Owner>\n <Name extends string, E extends Exclude<PathEnd<Name>, ExistsPredicate>>(\n viewer: ViewerExpr<any, Name>,\n end: E,\n ): ViewerPathExpr<ValueOf<E> | null>\n}\n\n/**\n * The most relations one path follows. Each is a subquery in SQL and a lookup\n * in memory; the deepest rule a real app here writes follows two.\n */\nexport const maxPathLength = 4\n\n/** What a path may end at on a row of `Name`: a field, a further path, or an exists. */\nexport type PathEnd<Name extends string> =\n | EntityField<Name, string, Schema.Constraint>\n | (PathExpr<any> & Reads<Name>)\n | (ExistsPredicate & Reads<Name>)\n\n/** A value checked to be a `one` relation, or refused with what to write instead. */\nconst oneRelation = (step: 'path' | 'exists', value: unknown): OneRelation => {\n if (tagOf(value) !== 'Relation') {\n throw new Error(\n `[foldkit-entity] Expr.${step}: the first argument is a relation (Post.relations.author)`,\n )\n }\n const relation = value as EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n if (relation.cardinality !== 'one') {\n throw new Error(\n `[foldkit-entity] Expr.${step}: ${relation.owner.name}.${relation.key} is a many relation; name the one relation that points back${step === 'path' ? ', with Expr.exists' : ''}`,\n )\n }\n return relation as OneRelation\n}\n\n/** `Expr.path` from the viewer: a field of their row, or what a path from it reads. */\nconst viewerPathOf = (from: ViewerExpr<unknown>, end: unknown): ViewerPathExpr<unknown> => {\n const start = from.target()\n const onStart = (owner: EntityIdentity<string>, what: string): void => {\n if (owner.token !== start.identity.token) {\n throw new Error(\n `[foldkit-entity] Expr.path: the viewer is a ${start.name}, but ${what} is read on a ${owner.name}`,\n )\n }\n }\n return Match.value(toOperand(end)).pipe(\n Match.tag('Field', field => {\n onStart(field.owner, `${field.owner.name}.${field.key}`)\n return node<ViewerPathExpr<unknown>>({ _tag: 'ViewerPath', viewer: from, via: [], field })\n }),\n Match.tag('Path', path => {\n onStart(path.via[0].owner, showExpr(path))\n return node<ViewerPathExpr<unknown>>({\n _tag: 'ViewerPath',\n viewer: from,\n via: path.via,\n field: path.field,\n })\n }),\n Match.orElse(other => {\n throw new Error(\n `[foldkit-entity] Expr.path: a path from the viewer ends at a field or a path, not ${showExpr(other)}`,\n )\n }),\n )\n}\n\n/** `Expr.path`: `relation` followed first, then whatever `end` reads, checked to be on its target. */\nconst pathOf = (relation: unknown, end: unknown): PathExpr<unknown> | ExistsPredicate => {\n if (tagOf(relation) === 'Viewer')\n return viewerPathOf(relation as ViewerExpr<unknown>, end) as never\n const first = oneRelation('path', relation)\n const target = first.target().identity\n const onTarget = (owner: EntityIdentity<string>, what: string): void => {\n if (owner.token !== target.token) {\n throw new Error(\n `[foldkit-entity] Expr.path: ${first.owner.name}.${first.key} reaches a ${target.name}, but ${what} is read on a ${owner.name}`,\n )\n }\n }\n const capped = <P extends PathExpr<unknown> | ExistsPredicate>(path: P): P => {\n if (path.via.length > maxPathLength) {\n throw new Error(\n `[foldkit-entity] Expr.path: ${showExpr(path)} follows more than ${maxPathLength} relations`,\n )\n }\n return node(path)\n }\n return Match.value(toOperand(end)).pipe(\n Match.tag('Field', field => {\n onTarget(field.owner, `${field.owner.name}.${field.key}`)\n return capped<PathExpr<unknown>>({ _tag: 'Path', via: [first], field })\n }),\n Match.tag('Path', path => {\n onTarget(path.via[0].owner, showExpr(path))\n return capped<PathExpr<unknown>>({ ...path, via: [first, ...path.via] })\n }),\n Match.tag('Exists', exists => {\n onTarget(existsStart(exists).owner, showExpr(exists))\n return capped<ExistsPredicate>({ ...exists, via: [first, ...exists.via] })\n }),\n Match.orElse(other => {\n throw new Error(\n `[foldkit-entity] Expr.path: a path ends at a field, a path or an exists, not ${showExpr(other)}`,\n )\n }),\n )\n}\n\n/** `Expr.exists`: the filter checked to read only the pointing row and the input. */\nconst existsOf = (relation: unknown, where: unknown): ExistsPredicate => {\n const pointing = oneRelation('exists', relation)\n const filter = Option.fromUndefinedOr(where)\n Option.map(filter, given => {\n if (!isPredicate(given)) {\n throw new Error('[foldkit-entity] Expr.exists: the filter is a predicate')\n }\n const read = dependenciesOf(given)\n const foreign = read.fields.find(field => field.owner.token !== pointing.owner.token)\n // A filter reading the row asked about, or a further row, would be a\n // correlation each interpreter has to carry: say it with a path instead.\n if (foreign !== undefined || read.next.length > 0 || read.reaches.length > 0) {\n throw new Error(\n `[foldkit-entity] Expr.exists: the filter reads ${foreign === undefined ? 'past its row' : `${foreign.entity}.${foreign.key}`}; it reads the pointing ${pointing.owner.name}'s own fields and the input`,\n )\n }\n })\n return node({\n _tag: 'Exists',\n via: [],\n relation: pointing,\n where: filter as Option.Option<Predicate>,\n })\n}\n\n/** The case names of an Entity with variants. */\ntype TagOf<E extends AnyVariantEntity> = keyof E['variants']['cases'] & string\n\n/** A case's schemas, `_tag` aside. */\ntype CaseSchemas<E extends AnyVariantEntity, T extends string> = Omit<\n E['variants']['cases'][T]['fields'],\n '_tag'\n>\n\n/** A case's fields as `Expr.is` hands them out: typed as the case holds them, never null. */\nexport type CaseFields<E extends AnyVariantEntity, T extends string> = {\n readonly [K in keyof CaseSchemas<E, T> & string]: EntityField<E['name'], K, CaseSchemas<E, T>[K]>\n}\n\n/** A case's fields as read through a `one` relation to its Entity: a path to each. */\nexport type CasePaths<Owner extends string, E extends AnyVariantEntity, T extends string> = {\n readonly [K in keyof CaseSchemas<E, T> & string]: PathExpr<\n Schema.Schema.Type<CaseSchemas<E, T>[K]>\n > &\n Reads<Owner>\n}\n\n/** `Expr.is`'s two subjects: the row judged, or the row a `one` relation of it reaches. */\ninterface IsOf {\n <E extends AnyVariantEntity, const T extends TagOf<E>, P extends Predicate = never>(\n entity: E,\n tag: T,\n build?: (fields: CaseFields<E, T>) => P,\n ): Predicate & Reads<E['name'] | ReadsOf<P>>\n <\n Owner extends string,\n Target extends AnyVariantEntity,\n const T extends TagOf<Target>,\n P extends Predicate = never,\n >(\n relation: EntityRelation<Owner, string, Target, 'one', boolean>,\n tag: T,\n build?: (fields: CasePaths<Owner, Target, T>) => P,\n ): Predicate & Reads<Owner | ReadsOf<P>>\n}\n\nconst isOf = (\n subject: unknown,\n tag: string,\n build?: (fields: Readonly<Record<string, unknown>>) => unknown,\n): Predicate => {\n const relation =\n tagOf(subject) === 'Relation'\n ? (subject as EntityRelation<string, string, AnyEntity, Cardinality, boolean>)\n : undefined\n if (relation !== undefined && relation.cardinality !== 'one') {\n throw new Error(\n `[foldkit-entity] Expr.is: ${relation.owner.name}.${relation.key} is a many relation, which reaches no one row`,\n )\n }\n const entity = relation === undefined ? (subject as AnyEntity) : relation.target()\n const variants = Option.getOrThrowWith(\n typeof entity === 'object' && entity !== null && 'identity' in entity\n ? variantsOf(entity.identity)\n : Option.none(),\n () =>\n new Error(\n '[foldkit-entity] Expr.is: the first argument is an Entity declared with Entity.defineVariants, or a one relation to one',\n ),\n )\n if (!variants.tags.includes(tag)) {\n throw new Error(\n `[foldkit-entity] Expr.is: ${entity.name} has no case \"${tag}\"; its cases are ${variants.tags.join(', ')}`,\n )\n }\n const stored = entity.fields as Readonly<\n Record<string, EntityField<string, string, Schema.Constraint>>\n >\n // Through a relation, each field is read on the row it reaches.\n const read = (field: EntityField<string, string, Schema.Constraint>): unknown =>\n relation === undefined ? field : pathOf(relation, field)\n const is = Expr.eq(read(stored._tag!) as AnyExpr, tag as never)\n if (build === undefined) return is\n const caseFields: Record<string, unknown> = {}\n for (const [key, schema] of Object.entries(variants.cases[tag]!)) {\n // The stored field, whatever a descriptor annotated on it, typed as the case holds it.\n put(caseFields, key, read(Object.freeze({ ...stored[key]!, schema })))\n }\n const asked = build(Object.freeze(caseFields))\n if (!isPredicate(asked)) {\n throw new Error(`[foldkit-entity] Expr.is: what is asked of a ${tag} is a predicate`)\n }\n return Expr.and(is, asked)\n}\n\n/** `Expr.field`: an Entity field, or an expression refused with what to write instead. */\ninterface FieldOf {\n <Name extends string, Key extends string, S extends Schema.Constraint>(\n field: EntityField<Name, Key, S>,\n ): FieldExpr<Schema.Schema.Type<S>> & Reads<Name>\n (\n expression: Expr<unknown> &\n Invalid<'foldkit-entity: Expr.field takes an Entity field (Post.fields.title); before.x and after.x are expressions already, so compare them as they are'>,\n ): never\n}\n// The second signature only refuses, at compile time: nothing but a field reaches here.\nconst fieldOf = ((field: EntityField<string, string, Schema.Constraint>) =>\n fieldExpr(field)) as FieldOf\n\ninterface NextOf {\n <Name extends string, Key extends string, S extends Schema.Constraint>(\n field: EntityField<Name, Key, S>,\n ): NextExpr<Schema.Schema.Type<S>> & Reads<Name>\n <Name extends string, Key extends string, Optional extends boolean>(\n relation: EntityRelation<Name, Key, AnyEntity, 'one', Optional>,\n ): NextExpr<Optional extends true ? string | null : string> & Reads<Name>\n}\n// A `one` relation is the id it points at, as everywhere else it is an operand.\nconst nextOf = ((member: EntityField<string, string, Schema.Constraint> | OneRelation) =>\n node({ _tag: 'Next', field: toOperand(member) as FieldExpr<unknown> })) as NextOf\n\nexport const Expr = {\n /**\n * An operator, defined by what a call of it means: `definedAs` builds that\n * expression from the call's arguments, once per call, and every interpreter\n * runs it, so the operator needs no implementation anywhere. What it adds is\n * a name: a query, a guard and an invariant that mean the same thing say so,\n * and print it.\n *\n * ```ts\n * const published = Expr.operator('cms.published', {\n * input: [Schema.Unknown],\n * output: Schema.Boolean,\n * definedAs: publishedAt => Expr.isNotNull(publishedAt),\n * })\n * Query.where(published(Post.fields.publishedAt))\n * ```\n *\n * Arguments are checked by their stored form: a field, scalar or plain value\n * of the input's stored type, or a predicate where it takes a boolean. A\n * boolean output makes a call a predicate. `definedAs` may read only what its\n * arguments hold: a field or input it closes over instead is refused when\n * called, since nothing asking what the call reads would see it. The id is\n * namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)\n * changes when what it means does.\n *\n * **Without `definedAs` it is primitive**: each interpreter implements it\n * (`Operators.implement` in memory), and one without an implementation\n * refuses the body by the operator's id. `nulls` (default `strict`: a null\n * argument gives null, the implementation never sees one) and `collation`\n * (`operands`: a text result carries its text arguments' shared collation;\n * `required`: it compares text itself and needs one) are a primitive\n * operator's; a defined one means its body for both.\n */\n operator: <const In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n id: string,\n options: {\n readonly input: In\n readonly output: Out\n readonly version?: number | undefined\n readonly description?: string | undefined\n /** Equations every implementation keeps (`Law.commutative`, `Law.identity('')`, …). */\n readonly laws?: ReadonlyArray<Law> | undefined\n } & (\n | {\n readonly definedAs: (\n ...args: { readonly [K in keyof In]: ParameterOf<In[K]> }\n ) => BodyOf<Out>\n readonly nulls?: undefined\n readonly collation?: undefined\n }\n | {\n readonly definedAs?: undefined\n readonly nulls?: OperatorDescriptor['nulls'] | undefined\n readonly collation?: OperatorDescriptor['collation'] | undefined\n }\n ),\n ): Operator<In, Out> =>\n makeOperator(id, options as Parameters<typeof makeOperator>[1]) as unknown as Operator<In, Out>,\n\n /**\n * The predicate or scalar (an order term's, say) with every call of a\n * defined operator replaced by what it means, deeply. An interpreter that\n * compiles a body expands it first, and compiles exactly what was written\n * out. A call with no definition stays, for the interpreter to run or refuse\n * by name.\n */\n /**\n * Whether a constant written in these expressions is one no two backends\n * agree on, text holding a NUL or NaN, or a list holding one: SQL refuses\n * such a parameter wherever it compiles, so an interpreter refuses the run,\n * not one row.\n */\n givesUnportable: (...nodes: ReadonlyArray<AnyExpr | Predicate>): boolean => {\n const seen = new Set<object>()\n const nul = (value: unknown) =>\n (typeof value === 'string' && value.includes(String.fromCharCode(0))) ||\n (typeof value === 'number' && Number.isNaN(value))\n const walk = (node: AnyExpr | Predicate): boolean => {\n if (seen.has(node)) return false\n seen.add(node)\n if (node._tag === 'Literal') {\n return Array.isArray(node.value) ? node.value.some(nul) : nul(node.value)\n }\n return childrenOf(node).some(walk)\n }\n return nodes.some(walk)\n },\n\n expanded: <N extends Predicate | AnyExpr>(node: N): N extends Predicate ? Predicate : AnyExpr =>\n (isPredicate(node) ? expandedPredicate(node) : expandedScalar(node)) as never,\n\n /**\n * What these expressions need that an interpreter lacks, as `Query.unsupported`\n * says it for a query: each kernel operation `supported` does not list, then\n * each primitive operator `operators` does not implement, by name (`id`, or\n * `id@version` past the first). For anything holding expressions that is not a\n * query: a guard's rule, an invariant, a write's `when`.\n */\n unsupported: (\n nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>,\n interpreter: {\n readonly operations: ReadonlyArray<Operation>\n readonly operators: OperatorTable\n },\n ): ReadonlyArray<string> => unsupportedIn(nodes, interpreter.operations, interpreter.operators),\n\n /** A constant. Comparisons coerce a plain value, so this is rarely written. */\n literal,\n\n /**\n * A value the query is given when it runs. A definition builds these from its\n * `Input` schema; written by hand only when constructing a body directly.\n */\n input: <T>(key: string, schema: Schema.Codec<T, unknown>): InputExpr<T> =>\n node({ _tag: 'Input', key, schema }),\n\n /**\n * A field, or a `one` relation as the id it points at, as the row a write\n * would leave holds it: what `Entity.invariant`'s builder hands out as `after`.\n */\n next: nextOf,\n\n /**\n * One field of one Entity, as a scalar. An expression is one already: an\n * invariant's `before.x` and `after.x` compare as they are, so wrapping one\n * is refused with that sentence.\n */\n field: fieldOf,\n\n /**\n * What the row reached through a `one` relation holds: a field of it, a\n * further path from it, or an exists asked of it. The first relation is the\n * judged row's own.\n *\n * ```ts\n * Expr.eq(Expr.path(Post.relations.author, User.fields.handle), input.handle)\n * Expr.path(Note.relations.project, Expr.path(Project.relations.org, Org.fields.plan))\n * ```\n *\n * A null link, or a row the reader may not see, reaches no row: the field\n * reads null, and an exists at the end is unknown, as SQL's scalar subquery\n * is. At most `maxPathLength` relations.\n */\n path: pathOf as PathOf,\n\n /**\n * Some row points at this one through `relation`, a `one` relation of\n * another Entity, and holds `where`, a predicate over that row's own fields\n * and the input:\n *\n * ```ts\n * // Posts whose author the reader follows.\n * Expr.path(Post.relations.author,\n * Expr.exists(Follow.relations.followee, Expr.eq(Follow.fields.followerId, input.me)))\n * ```\n *\n * Only rows the reader may see are sought. Never unknown in SQL; in memory,\n * unknown when no held row holds and the holder may lack one that would.\n */\n exists: existsOf as <\n Owner extends string,\n Target extends AnyEntity,\n W extends Predicate & Reads<Owner> = never,\n >(\n relation: EntityRelation<Owner, string, Target, 'one', boolean>,\n where?: W,\n ) => ExistsPredicate & Reads<Target['name']>,\n\n /**\n * The row is of case `tag` of an Entity declared with\n * `Entity.defineVariants`, and holds what `build` asks of that case's\n * fields, each typed as the case holds it:\n *\n * ```ts\n * Expr.is(Domain, 'Unconfirmed')\n * Expr.is(Domain, 'Available', ({ price }) => Expr.lt(price, 20))\n * // Through a one relation, the row it reaches.\n * Expr.is(Order.relations.domain, 'Available', ({ price }) => Expr.lt(price, 20))\n * ```\n *\n * It is `_tag = tag` and the predicate, so a row of another case is false,\n * never unknown, and `Expr.not` of it holds there. Through a relation, a null\n * link reaches no row and the test is unknown, as a path's field reads null.\n * Use the fields inside `build`: outside it a case's field is the stored\n * column, null on rows of other cases.\n */\n is: isOf as IsOf,\n\n /**\n * Whoever asks, as a row of `entity`: `Expr.eq(Like.fields.userId,\n * Expr.viewer(User))`. Shaped as a `one` relation to `entity`. Its value is\n * the row's id, and null for a visitor or a viewer of another Entity, so a\n * comparison with it holds of no row. A server reads it from\n * `RemoteServer.make`'s `viewer`, a client from `Remote.make`'s.\n */\n viewer,\n\n /**\n * The time of the write, in milliseconds since the epoch, as a number field\n * stores it. A server reads its clock. A client judging a list has no\n * reading of the time the server judged it at, so such a list is the\n * server's to say.\n */\n now,\n\n /**\n * Two scalars are the same value: a field (or an expression) on the left,\n * and the value on the right, typed from it. Fields and plain values are\n * coerced, so the common form reads as it means:\n *\n * ```ts\n * Expr.eq(Post.fields.slug, input.slug)\n * Expr.eq(Post.fields.status, 'active')\n * ```\n */\n eq: <\n L extends Operand<any> | PlainValue,\n R extends (L extends PlainValue\n ? Invalid<'foldkit-entity: Expr.eq takes the field on the left and the value on the right'>\n : // A path reads null where it reaches no row, which compares as SQL's unknown.\n | ValueOf<L>\n | Expr<ValueOf<L>>\n | PathExpr<ValueOf<L> | null>\n | ViewerPathExpr<ValueOf<L> | null>\n | (boolean extends ValueOf<L> ? Predicate : never)),\n >(\n left: L,\n // The right side is typed from the left, so a plain value on the left has\n // nothing to type it by: say so, rather than that 3 is no `Operand`.\n right: R,\n ): EqPredicate & Reads<ReadsOf<L> | ReadsOf<R>> =>\n node({ _tag: 'Eq', left: toOperand(left), right: toOperand(right as never) }),\n\n /**\n * Whether a field holds no value. Its opposite is `isNotNull`; both are the\n * one node, since a query asks which of the two it means, and `is not null`\n * has no unknown for a `not` to keep.\n */\n isNull: <L extends Operand<any>>(operand: L): NullPredicate & Reads<ReadsOf<L>> =>\n node({ _tag: 'Null', operand: toExpr(operand, 'isNull'), present: false }),\n\n /** Whether a field holds a value. */\n isNotNull: <L extends Operand<any>>(operand: L): NullPredicate & Reads<ReadsOf<L>> =>\n node({ _tag: 'Null', operand: toExpr(operand, 'isNotNull'), present: true }),\n\n /**\n * Whether a text value contains `search`, anywhere in it. Containing the\n * empty string is everything, so a search box with nothing typed in it is the\n * same query as one with something — no branch, and no second query.\n *\n * **Case-insensitive**, which is what a search means, and which has to be\n * said rather than left to the interpreter: SQLite's `like` ignores case and\n * Postgres's does not, so a body that left it open would mean two things.\n * Folding is ASCII-only, because that is what `lower` does in SQLite without\n * ICU.\n *\n * **Over a column that can be null this is not the same as no filter.** A\n * null contains nothing, not even the empty string, so its rows drop out. A\n * nullable column that should match everything on an empty search says so:\n * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.\n */\n contains: <L extends TextOperand>(\n value: L,\n search: string | LiteralExpr<string> | InputExpr<string> | InputExpr<string | null>,\n ): ContainsPredicate & Reads<ReadsOf<L>> => {\n const operand = toOperand(search as never)\n // A search a row decides would have to be escaped as a pattern in SQL, which\n // no compiler here does: it is a value or an input.\n if (operand._tag !== 'Literal' && operand._tag !== 'Input') {\n throw new Error(\n `[foldkit-entity] Expr.contains: the search is ${showExpr(operand)}; search for a value or an input`,\n )\n }\n return node({ _tag: 'Contains', value: toExpr(value, 'contains'), search: operand })\n },\n\n /**\n * Whether a value is one of `among`: a list written out, or an input whose\n * value is one. Each element is compared as `eq` compares.\n *\n * ```ts\n * Expr.in(Todo.fields.projectId, input.projectIds)\n * Expr.in(Todo.fields.status, ['open', 'blocked'])\n * ```\n *\n * As SQL's `in`: a null value is unknown, as is no match against a list\n * holding a null, and an empty list matches no row. A list written out is\n * copied, so changing the array afterwards does not change the query.\n */\n in: <L extends Operand<any>>(\n value: L,\n among: ReadonlyArray<ValueOf<L>> | Expr<ReadonlyArray<ValueOf<L>>>,\n ): InPredicate & Reads<ReadsOf<L>> =>\n node({\n _tag: 'In',\n value: toExpr(value, 'in'),\n among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, 'in'),\n }),\n\n /**\n * `left` orders before `right`. Numbers compare as numbers; text compares\n * under a collation, the one given or the field's declared one, which must be\n * `binary` or `asciiFold` (so every backend agrees), and text needs a field on\n * one side. A date compares by its encoded form: as text when it is stored as\n * an ISO string, so its field declares `Collation.binary`. A null on either\n * side is unknown, so the row is matched by neither this nor its `not`.\n *\n * ```ts\n * Expr.lt(fields.cents, 1000)\n * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))\n * ```\n */\n lt: comparison('lt'),\n /** `left` orders before `right`, or with it; see `Expr.lt`. */\n lte: comparison('lte'),\n /** `left` orders after `right`; see `Expr.lt`. */\n gt: comparison('gt'),\n /** `left` orders after `right`, or with it; see `Expr.lt`. */\n gte: comparison('gte'),\n\n /**\n * Every operand holds, as one predicate to place inside another: `where`'s\n * list is already a conjunction, so this is for `or(and(a, b), c)`.\n * Unknown as SQL's `and` is: false wins over unknown, which wins over true.\n * Needs an operand; a list built at run time is checked non-empty first\n * (`Array.isReadonlyArrayNonEmpty`), since an empty `and` would match every row.\n */\n and: connective<AndPredicate>('and', 'And') as Connective<AndPredicate>,\n\n /**\n * At least one operand holds:\n *\n * ```ts\n * Expr.or(Expr.contains(fields.description, input.search), Expr.contains(fields.upc, input.search))\n * ```\n *\n * Unknown as SQL's `or` is: true wins over unknown, which wins over false.\n * Needs an operand, since an empty `or` would match no row.\n */\n or: connective<OrPredicate>('or', 'Or') as Connective<OrPredicate>,\n\n /**\n * The operand does not hold. **A null is matched by neither side**:\n * `not(eq(status, 'draft'))` leaves out a row whose `status` is null, since\n * `null = 'draft'` is unknown and so is its `not`, as in SQL. \"Everything\n * but drafts\" over a nullable column is\n * `Expr.or(Expr.isNull(status), Expr.not(Expr.eq(status, 'draft')))`.\n */\n not: <P extends Predicate>(operand: P): NotPredicate & Reads<ReadsOf<P>> => {\n if (!isPredicate(operand)) {\n throw new Error(\n '[foldkit-entity] Expr.not: the operand is a predicate; compare a value with Expr.eq first',\n )\n }\n return node({ _tag: 'Not', operand })\n },\n\n /**\n * A filter that applies only when its input is given: `or(isNull($x), …)`,\n * with the predicate built from the input as never null.\n *\n * ```ts\n * // Every product, or those of the chosen status.\n * Expr.whenGiven(input.status, status => Expr.eq(fields.status, status))\n * ```\n *\n * An interpreter that runs per request, as the Drizzle compiler does, decides\n * `isNull($x)` before writing SQL, so this compiles to `true`, which filters\n * nothing, or to the predicate alone.\n */\n whenGiven: <T, P extends Predicate>(\n input: InputExpr<T>,\n build: (given: InputExpr<NonNullable<T>>) => P,\n ): Predicate & Reads<ReadsOf<P>> =>\n // The predicate only decides a row when the input is not null: when it is,\n // `isNull` is true and so is the `or`. That is what the narrowed type says.\n Expr.or(Expr.isNull(input), build(input as unknown as InputExpr<NonNullable<T>>)),\n\n /** An expression as readable text; see `showExpr` for what it is and is not. */\n show: (node: Operandish): string => showExpr(node),\n\n /**\n * The predicate with each field after a write (`Next`) that `values` names,\n * by key, read as that value: how an invariant is judged where the\n * write's new values are known. A field it does not name stays `Next`, for\n * the interpreter to read as the row after holds it.\n */\n substituteNext: (predicate: Predicate, values: Readonly<Record<string, unknown>>): Predicate =>\n substituted(predicate, operand =>\n Match.value(operand).pipe(\n Match.tag('Next', ({ field }) =>\n Object.hasOwn(values, field.key) ? literal(values[field.key]) : operand,\n ),\n Match.orElse(() => operand),\n ),\n ),\n}\n\n/** Rewrites one operand; the walk below applies it wherever a predicate holds one. */\ntype OperandRewrite = (operand: AnyExpr) => AnyExpr\n\nconst substitutedSide = (side: Operandish, rewrite: OperandRewrite): Operandish =>\n isPredicate(side) ? substituted(side, rewrite) : substitutedScalar(side, rewrite)\n\n/**\n * A scalar rewritten: a call's arguments and expansion each, so a field read\n * under it is rewritten as one read directly is; anything else by `rewrite`.\n */\nconst substitutedScalar = (scalar: AnyExpr, rewrite: OperandRewrite): AnyExpr =>\n scalar._tag === 'Call'\n ? node({\n ...scalar,\n args: Object.freeze(scalar.args.map(arg => substitutedSide(arg, rewrite))),\n expansion: Option.map(scalar.expansion, expansion => substitutedScalar(expansion, rewrite)),\n })\n : rewrite(scalar)\n\nconst substituted = (predicate: Predicate, rewrite: OperandRewrite): Predicate => {\n switch (predicate._tag) {\n case 'Eq':\n return node({\n ...predicate,\n left: substitutedSide(predicate.left, rewrite),\n right: substitutedSide(predicate.right, rewrite),\n })\n case 'Null':\n return node({ ...predicate, operand: substitutedScalar(predicate.operand, rewrite) })\n case 'Contains':\n return node({\n ...predicate,\n value: substitutedScalar(predicate.value, rewrite),\n search: substitutedSide(predicate.search, rewrite),\n })\n case 'In':\n return node({\n ...predicate,\n value: substitutedScalar(predicate.value, rewrite),\n among: substitutedScalar(predicate.among, rewrite),\n })\n case 'And':\n case 'Or':\n return node({\n ...predicate,\n operands: Arr.map(predicate.operands, operand => substituted(operand, rewrite)),\n })\n case 'Not':\n return node({ ...predicate, operand: substituted(predicate.operand, rewrite) })\n case 'Compare':\n return node({\n ...predicate,\n left: substitutedScalar(predicate.left, rewrite),\n right: substitutedScalar(predicate.right, rewrite),\n })\n case 'Test':\n return node({\n ...predicate,\n args: Object.freeze(predicate.args.map(arg => substitutedSide(arg, rewrite))),\n expansion: Option.map(predicate.expansion, expansion => substituted(expansion, rewrite)),\n })\n // Its filter reads the pointing row, never the one a rewrite is about.\n case 'Exists':\n return predicate\n }\n}\n\n/** One term of an ordering: a scalar and the direction to read it in. */\nexport interface OrderTerm {\n readonly _tag: 'Term'\n readonly direction: 'asc' | 'desc'\n readonly expr: AnyExpr\n /**\n * Where rows without a value go, in the term's own direction. Databases\n * disagree when it is left unsaid (Postgres puts them last ascending, SQLite\n * first), so it is always said: last ascending and first descending unless\n * a term asks otherwise, which is Postgres's.\n */\n readonly nulls: 'first' | 'last'\n /**\n * How text compares, when the term orders text: the term's own, or its\n * field's. None leaves it to the backend, which a client cannot match.\n */\n readonly collation: Option.Option<Collation>\n}\n\n/** What a term may say besides its operand. */\nexport interface TermOptions {\n readonly nulls?: 'first' | 'last' | undefined\n /** Overrides the field's declared collation for this term. */\n readonly collation?: Collation | undefined\n}\n\n/** A term, its nulls placed by `options` or by the direction's default. */\nconst term = (direction: 'asc' | 'desc', expr: AnyExpr, options: TermOptions = {}): OrderTerm => {\n // The collation the operand itself carries.\n const carried = Match.value(expr).pipe(\n Match.tagsExhaustive({\n Field: field => field.collation,\n Call: call => call.collation,\n // A client could not place a row by a value another row holds, and a\n // cursor over one would page by what can change under it.\n Path: (path): Option.Option<Collation> => {\n throw new Error(\n `[foldkit-entity] Order: ${showExpr(path)} is a path; a list orders by its own row's fields`,\n )\n },\n ViewerPath: (path): Option.Option<Collation> => {\n throw new Error(\n `[foldkit-entity] Order: ${showExpr(path)} is a path from the viewer; a list orders by its own row's fields`,\n )\n },\n Literal: () => Option.none<Collation>(),\n Input: () => Option.none<Collation>(),\n Next: () => Option.none<Collation>(),\n Viewer: () => Option.none<Collation>(),\n Now: () => Option.none<Collation>(),\n }),\n )\n // A number orders alike everywhere, and Postgres refuses a collation on one: a\n // collation it would inherit from a call's text arguments is dropped.\n const number = sideKind(expr) === 'number'\n if (number && options.collation !== undefined) {\n throw new Error(\n `[foldkit-entity] Order: ${showExpr(expr)} is a number, which needs no collation; a collation orders text`,\n )\n }\n const collation = number\n ? Option.none<Collation>()\n : Option.orElse(Option.fromUndefinedOr(options.collation), () => carried)\n if (expr._tag === 'Call') orderableCall(expr, collation)\n return node({\n _tag: 'Term',\n direction,\n expr,\n nulls: options.nulls ?? (direction === 'asc' ? 'last' : 'first'),\n collation,\n })\n}\n\n/**\n * Refuses a call no interpreter could order alike (expr-operations-DESIGN §8):\n * its result must be a number, or text under a collation every interpreter\n * shares. A field's text may be left to the backend; a call's has no backend\n * column to fall back on.\n */\nconst orderableCall = (call: CallExpr<unknown>, collation: Option.Option<Collation>): void => {\n const fail = (why: string): never => {\n throw new Error(`[foldkit-entity] Order: ${showExpr(call)} ${why}`)\n }\n const kind = sideKind(call)\n if (kind === 'number') return\n if (kind !== 'text') fail('is neither a number nor text, so it orders nowhere alike')\n Option.match(collation, {\n onNone: () =>\n fail(\n 'is text with no collation, so backends would order it differently; give the term or its text Collation.binary or Collation.asciiFold',\n ),\n onSome: each => {\n if (each._tag === 'Locale') {\n fail(`is ordered by the backend's \"${each.locale}\" collation, which a call cannot carry`)\n }\n },\n })\n}\n\n/** How a list is sorted, as its input holds it: one of its named orders, which way, or none. */\nexport type ChosenSort<By extends string> = {\n readonly by: By\n readonly direction: 'asc' | 'desc'\n} | null\n\n/**\n * An ordering the input chooses: one of several named fields, which way, or\n * none. It is how a list sorts by what its reader picked, said in the body, so\n * the server and the client read one declaration of what each name means.\n */\nexport interface ChosenOrder {\n readonly _tag: 'Chosen'\n readonly sort: InputExpr<ChosenSort<string>>\n readonly choices: Readonly<Record<string, FieldExpr<unknown> | CallExpr<unknown>>>\n}\n\n/** One entry of a body's ordering: fixed, or chosen by the input. */\nexport type Ordering = OrderTerm | ChosenOrder\n\n/**\n * What an order term orders by, refusing a link: a client holds a link as a\n * ref, not the id it orders by, so it could not place a row there.\n */\nconst orderOperand = (expr: unknown, step: 'asc' | 'desc' | 'chosen'): AnyExpr => {\n if (tagOf(expr) === 'Relation') {\n throw new Error(\n `[foldkit-entity] Order.${step}: a list orders by its own fields, not by where a relation points`,\n )\n }\n return toExpr(expr as never, step)\n}\n\nexport const Order = {\n /** Smallest first; rows without a value last, unless `nulls` says first. */\n asc: <E extends OwnOperand<any>>(expr: E, options?: TermOptions): OrderTerm & Reads<ReadsOf<E>> =>\n term('asc', orderOperand(expr, 'asc'), options),\n /** Largest first; rows without a value first, unless `nulls` says last. */\n desc: <E extends OwnOperand<any>>(\n expr: E,\n options?: TermOptions,\n ): OrderTerm & Reads<ReadsOf<E>> => term('desc', orderOperand(expr, 'desc'), options),\n\n /**\n * The order the input names, among `choices`: every name the sort can hold\n * maps to a field or a call that orders, so a name left out is a type error\n * here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after\n * it decide.\n *\n * ```ts\n * Query.orderBy(Order.chosen(input.sort, { title: Post.fields.title }))\n * ```\n */\n chosen: <By extends string, const Choices extends { readonly [K in By]: OwnOperand<any> }>(\n sort: InputExpr<ChosenSort<By>>,\n choices: Choices,\n ): ChosenOrder & Reads<ReadsOf<Choices[keyof Choices]>> => {\n const fields: Record<string, FieldExpr<unknown> | CallExpr<unknown>> = Object.create(null)\n for (const [name, choice] of Object.entries<OwnOperand<any>>(choices)) {\n const expr = orderOperand(choice, 'chosen')\n if (expr._tag !== 'Field' && expr._tag !== 'Call') {\n throw new Error(`[foldkit-entity] Order.chosen: \"${name}\" is neither a field nor a call`)\n }\n // Checked as a term now, so an alternative no input has chosen yet is refused where written.\n if (expr._tag === 'Call') orderableCall(expr, expr.collation)\n fields[name] = expr\n }\n return node({\n _tag: 'Chosen',\n sort: sort as InputExpr<ChosenSort<string>>,\n choices: Object.freeze(fields),\n })\n },\n}\n\n/**\n * Whether a client can order rows the way the server does, for one input: the\n * answer `Query.placement` gives, and the reason when it cannot.\n */\nexport type Placement =\n | { readonly _tag: 'Placeable' }\n | { readonly _tag: 'NotPlaceable'; readonly reason: string }\n\nconst placeable: Placement = Object.freeze({ _tag: 'Placeable' })\nconst notPlaceable = (reason: string): Placement => Object.freeze({ _tag: 'NotPlaceable', reason })\n\n/**\n * Whether values encoded by `ast` order the same everywhere: numbers and\n * booleans, never text. A null among them does too: where it goes is said on\n * every order term.\n */\nconst ordersIntrinsically = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNumber(ast) ||\n SchemaAST.isBoolean(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal !== 'string') ||\n (SchemaAST.isUnion(ast) &&\n ast.types.every(member => SchemaAST.isNull(member) || ordersIntrinsically(member)))\n\n/** Why a term cannot be placed by a client running `operators`, if it cannot. */\nconst unplaceable = (orderTerm: OrderTerm, operators: OperatorTable): Option.Option<string> =>\n Match.value(orderTerm.expr).pipe(\n // Checked when the term was made: a number, or text under a shared collation.\n // Left is whether the client runs every primitive operator it calls.\n Match.tag('Call', call => {\n const missing = missingFrom(dependenciesOf(call).operators, operators)\n return missing.length === 0\n ? Option.none<string>()\n : Option.some(\n `it orders by ${showExpr(call)}, and this client does not run ${missing.join(', ')}`,\n )\n }),\n Match.tag('Field', field =>\n Option.match(orderTerm.collation, {\n onNone: () =>\n ordersIntrinsically(Schema.toEncoded(field.schema).ast)\n ? Option.none()\n : Option.some(\n `it orders by ${field.owner.name}.${field.key}, text with no declared collation`,\n ),\n onSome: collation =>\n Match.value(collation).pipe(\n Match.tagsExhaustive({\n Binary: () => Option.none<string>(),\n AsciiFold: () => Option.none<string>(),\n Locale: ({ locale }) =>\n Option.some(\n `it orders ${field.owner.name}.${field.key} by the backend's \"${locale}\" collation`,\n ),\n }),\n ),\n }),\n ),\n Match.tags({\n Literal: neither,\n Input: neither,\n Next: neither,\n Viewer: neither,\n Now: neither,\n // Refused where the term is made; said here too.\n Path: neither,\n ViewerPath: neither,\n }),\n Match.exhaustive,\n )\n\nconst neither = (): Option.Option<string> =>\n Option.some('it orders by something that is neither a field nor a call')\n\n/** Each Entity's id tie-break, made once, so a resolved order reuses one term. */\nconst idTerms = new WeakMap<AnyEntity, OrderTerm>()\nconst idTermOf = (entity: AnyEntity): OrderTerm => {\n const known = idTerms.get(entity)\n if (known !== undefined) return known\n const id = entity.fields.id\n if (id === undefined) {\n throw new Error(`[foldkit-entity] ${entity.name} has no id field to break an order's ties by`)\n }\n const tieBreak = term('asc', fieldExpr(id))\n idTerms.set(entity, tieBreak)\n return tieBreak\n}\n\n/** The fixed term a chosen order is for one input, or none for a `null` sort. */\nconst chosenTerms = (\n chosen: ChosenOrder,\n input: Readonly<Record<string, unknown>>,\n): ReadonlyArray<OrderTerm> => {\n const sort = own(input, chosen.sort.key)\n if (sort === null || sort === undefined) return []\n const picked =\n typeof sort === 'object' && 'by' in sort && typeof sort.by === 'string' ? sort.by : undefined\n const direction = typeof sort === 'object' && 'direction' in sort ? sort.direction : undefined\n if (\n picked === undefined ||\n !Object.hasOwn(chosen.choices, picked) ||\n (direction !== 'asc' && direction !== 'desc')\n ) {\n throw new Error(\n `[foldkit-entity] Order.chosen: $${chosen.sort.key} names no order it offers (${Object.keys(chosen.choices).join(', ')})`,\n )\n }\n return [term(direction, chosen.choices[picked]!)]\n}\n\n/** What a walk has found, and the nodes it has already been through. */\ninterface Found {\n readonly seen: Set<object>\n /** By owner identity, then key: two Entities sharing a name are two entries. */\n readonly fields: Map<symbol, Map<string, FieldDependency>>\n readonly order: Array<FieldDependency>\n readonly inputs: Set<string>\n readonly next: Map<symbol, Map<string, FieldDependency>>\n readonly nextOrder: Array<FieldDependency>\n readonly operations: Set<Operation>\n readonly operators: Set<OperatorDescriptor>\n readonly reaches: Array<PathExpr<unknown> | ExistsPredicate | ViewerPathExpr<unknown>>\n}\n\n/**\n * Visits each node once. A node can be shared by several paths (`eq(n, n)`),\n * and a walk that followed every path would take time exponential in the depth.\n */\nconst walk = (expr: AnyExpr | Predicate | Ordering, found: Found): void => {\n if (found.seen.has(expr)) return\n found.seen.add(expr)\n switch (expr._tag) {\n case 'Literal':\n return\n case 'Field': {\n const byKey = found.fields.get(expr.owner.token) ?? new Map<string, FieldDependency>()\n found.fields.set(expr.owner.token, byKey)\n if (!byKey.has(expr.key)) {\n const field = { entity: expr.owner.name, key: expr.key, owner: expr.owner }\n byKey.set(expr.key, field)\n found.order.push(field)\n }\n return\n }\n case 'Input':\n found.inputs.add(expr.key)\n return\n case 'Viewer':\n found.operations.add('viewer')\n return\n case 'Now':\n found.operations.add('now')\n return\n case 'Next': {\n found.operations.add('next')\n const { field } = expr\n const byKey = found.next.get(field.owner.token) ?? new Map<string, FieldDependency>()\n found.next.set(field.owner.token, byKey)\n if (!byKey.has(field.key)) {\n const read = { entity: field.owner.name, key: field.key, owner: field.owner }\n byKey.set(field.key, read)\n found.nextOrder.push(read)\n }\n return\n }\n case 'Eq':\n found.operations.add('eq')\n walk(expr.left, found)\n walk(expr.right, found)\n return\n case 'Null':\n found.operations.add(expr.present ? 'isNotNull' : 'isNull')\n walk(expr.operand, found)\n return\n case 'Contains':\n found.operations.add('contains')\n walk(expr.value, found)\n walk(expr.search, found)\n return\n case 'In':\n found.operations.add('in')\n walk(expr.value, found)\n walk(expr.among, found)\n return\n case 'And':\n found.operations.add('and')\n for (const operand of expr.operands) walk(operand, found)\n return\n case 'Or':\n found.operations.add('or')\n for (const operand of expr.operands) walk(operand, found)\n return\n case 'Not':\n found.operations.add('not')\n walk(expr.operand, found)\n return\n case 'Compare':\n found.operations.add('compare')\n walk(expr.left, found)\n walk(expr.right, found)\n return\n case 'Term':\n walk(expr.expr, found)\n return\n case 'Chosen':\n walk(expr.sort, found)\n for (const choice of Object.values(expr.choices)) walk(choice, found)\n return\n case 'Path':\n found.operations.add('path')\n found.reaches.push(expr)\n return\n // It needs whoever asks, and the subqueries a path is compiled to.\n case 'ViewerPath':\n found.operations.add('viewer')\n found.operations.add('path')\n found.reaches.push(expr)\n return\n case 'Exists': {\n found.operations.add('exists')\n found.reaches.push(expr)\n // The filter's fields are the pointing row's, so they stay out of `fields`;\n // what else it needs is this expression's need too.\n Option.map(expr.where, where => {\n const inner = dependenciesOf(where)\n inner.inputs.forEach(key => found.inputs.add(key))\n inner.operations.forEach(operation => found.operations.add(operation))\n inner.operators.forEach(operator => found.operators.add(operator))\n })\n return\n }\n case 'Call':\n case 'Test':\n found.operators.add(expr.operator)\n // What an interpreter runs is the expansion: its operations, and the reads its\n // arguments hold. With none, the arguments are all there is to read.\n Option.match(expansionOf(expr), {\n onSome: expansion => walk(expansion, found),\n onNone: () => expr.args.forEach(arg => walk(arg, found)),\n })\n return\n default:\n return absurd(expr)\n }\n}\n\n/**\n * What an expression reads and uses, for the planner and for an interpreter\n * deciding whether it can run this query at all. Distinct entries only, in the\n * order first seen, so the answer is stable enough to assert on.\n */\nexport const dependenciesOf = (\n ...nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>\n): Dependencies => {\n const found: Found = {\n seen: new Set(),\n fields: new Map(),\n order: [],\n inputs: new Set(),\n next: new Map(),\n nextOrder: [],\n operations: new Set(),\n operators: new Set(),\n reaches: [],\n }\n for (const term of nodes) walk(term, found)\n return {\n fields: found.order,\n next: found.nextOrder,\n inputs: [...found.inputs],\n operations: [...found.operations],\n operators: [...found.operators],\n reaches: found.reaches,\n }\n}\n\n/**\n * Which rows a query is about, as a value: an Entity to read, the predicates\n * every row must satisfy, and the order to read them in. It says nothing about\n * which fields to return — that is a Selection — and nothing about pagination,\n * liveness, or whether absence is an error, which belong to the consumer's read\n * rather than to the relation.\n *\n * Composing one performs no work. `Query.from(Post)` names no table and opens\n * no connection; an interpreter turns the value into a query when something\n * asks it to.\n */\nexport interface Query<E extends AnyEntity> extends Pipeable.Pipeable {\n readonly _tag: 'Query'\n readonly entity: E\n /**\n * Every predicate holds: the list *is* the conjunction. Keeping it a list\n * rather than folding it into one `and` is what makes each `where` a reusable\n * fragment, and it means no `Expr.and` exists until a query needs a\n * conjunction nested inside something else.\n */\n readonly where: ReadonlyArray<Predicate>\n /** In order of significance; a later `orderBy` appends less significant terms. */\n readonly orderBy: ReadonlyArray<Ordering>\n}\n\n/** A `Query` over any Entity, for the places that hold one without caring which. */\nexport type AnyQuery = Query<AnyEntity>\n\n/**\n * Every member of the judged row an expression reads, each node visited once:\n * a field, or the relation a path or an exists starts from.\n */\nconst fieldsIn = function* (\n expr: AnyExpr | Predicate | Ordering,\n seen: Set<object>,\n): Generator<{ readonly owner: EntityIdentity<string>; readonly key: string }> {\n if (seen.has(expr)) return\n seen.add(expr)\n switch (expr._tag) {\n case 'Field':\n yield expr\n return\n case 'Next':\n yield expr.field\n return\n case 'Literal':\n case 'Input':\n case 'Viewer':\n case 'Now':\n return\n case 'Eq':\n yield* fieldsIn(expr.left, seen)\n yield* fieldsIn(expr.right, seen)\n return\n case 'Null':\n yield* fieldsIn(expr.operand, seen)\n return\n case 'Contains':\n yield* fieldsIn(expr.value, seen)\n yield* fieldsIn(expr.search, seen)\n return\n case 'In':\n yield* fieldsIn(expr.value, seen)\n yield* fieldsIn(expr.among, seen)\n return\n case 'And':\n case 'Or':\n for (const operand of expr.operands) yield* fieldsIn(operand, seen)\n return\n case 'Not':\n yield* fieldsIn(expr.operand, seen)\n return\n case 'Compare':\n yield* fieldsIn(expr.left, seen)\n yield* fieldsIn(expr.right, seen)\n return\n case 'Term':\n yield* fieldsIn(expr.expr, seen)\n return\n case 'Chosen':\n for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen)\n return\n case 'Path':\n yield expr.via[0]\n return\n // It starts at the viewer's row, not the judged one, so any query may read it.\n case 'ViewerPath':\n return\n case 'Exists':\n yield existsStart(expr)\n return\n // An expansion reads only what its arguments do, which the call checked.\n case 'Call':\n case 'Test':\n for (const arg of expr.args) yield* fieldsIn(arg, seen)\n return\n default:\n return absurd(expr)\n }\n}\n\n/**\n * A query reads one Entity, so a predicate or ordering term naming a different\n * one cannot be answered — an interpreter would be asked for a column of a\n * table it was never told to read. Compared by identity, not by name, because\n * two Entities defined with the same name are two Entities.\n */\nconst checkOwnership = (\n step: string,\n what: string,\n entity: AnyEntity,\n nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>,\n): void => {\n const seen = new Set<object>()\n for (const term of nodes) {\n for (const field of fieldsIn(term, seen)) {\n if (field.owner.token !== entity.identity.token) {\n throw new Error(\n `[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`,\n )\n }\n }\n }\n}\n\n/**\n * The most nodes a query's predicates may hold once every shared node is\n * counted on each path that reaches it. Interpreters read a predicate as a\n * tree: `evaluate` once per row, and the SQL compiler into text that repeats a\n * shared operand wherever it appears. So `eq(n, n)` nested thirty deep is\n * thirty-one objects and a billion nodes of work. Real queries are tens.\n */\nexport const maxQueryNodes = 1_000\n\nconst childrenOf = (expr: AnyExpr | Predicate): ReadonlyArray<AnyExpr | Predicate> => {\n switch (expr._tag) {\n case 'Literal':\n case 'Field':\n case 'Input':\n case 'Next':\n case 'Viewer':\n case 'Now':\n case 'Path':\n case 'ViewerPath':\n return []\n case 'Exists':\n return Option.toArray(expr.where)\n case 'Eq':\n return [expr.left, expr.right]\n case 'Null':\n return [expr.operand]\n case 'Contains':\n return [expr.value, expr.search]\n case 'In':\n return [expr.value, expr.among]\n case 'And':\n case 'Or':\n return expr.operands\n case 'Not':\n return [expr.operand]\n case 'Compare':\n return [expr.left, expr.right]\n // What an interpreter runs is the expansion, so that is what the budget counts.\n case 'Call':\n case 'Test':\n return Option.match(expansionOf(expr), {\n onSome: expansion => [expansion],\n onNone: () => expr.args,\n })\n }\n}\n\n/** A node's size as a tree, each distinct node sized once. */\nconst expandedSize = (expr: AnyExpr | Predicate, sizes: Map<object, number>): number => {\n const known = sizes.get(expr)\n if (known !== undefined) return known\n // Capped, so a graph deep enough to overflow a number still compares as too big.\n const size = Math.min(\n maxQueryNodes + 1,\n childrenOf(expr).reduce((sum, child) => sum + expandedSize(child, sizes), 1),\n )\n sizes.set(expr, size)\n return size\n}\n\nconst QueryProto = {\n _tag: 'Query' as const,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst query = <E extends AnyEntity>(\n entity: E,\n where: ReadonlyArray<Predicate>,\n orderBy: ReadonlyArray<Ordering>,\n): Query<E> =>\n Object.freeze(\n Object.assign(Object.create(QueryProto), {\n entity,\n where: Object.freeze(where),\n orderBy: Object.freeze(orderBy),\n }),\n ) as Query<E>\n\n/**\n * Refuses a query whose predicates and order terms (every chosen alternative\n * among them) expand past `maxQueryNodes`, counting a shared node on every\n * path that reaches it: what an interpreter walks, and SQL writes out.\n */\nconst checkSize = (\n step: 'where' | 'orderBy',\n where: ReadonlyArray<Predicate>,\n orderBy: ReadonlyArray<Ordering>,\n): void => {\n const sizes = new Map<object, number>()\n const terms = orderBy.flatMap(ordering =>\n Match.valueTags(ordering, {\n Term: ({ expr }) => [expr],\n Chosen: ({ choices }) => Object.values(choices),\n }),\n )\n const size = [...where, ...terms].reduce((sum, each) => sum + expandedSize(each, sizes), 0)\n if (size > maxQueryNodes) {\n throw new Error(\n `[foldkit-entity] Query.${step}: the query expands to more than ${maxQueryNodes} nodes, counting a shared node on every path that reaches it`,\n )\n }\n}\n\nexport const Query = {\n /** Every row of an Entity: the query each transformation narrows. */\n from: <E extends AnyEntity>(entity: E): Query<E> => query(entity, [], []),\n\n /**\n * Narrows to the rows the predicate holds for. Two `where`s conjoin — the\n * second never replaces the first — so a fragment can be written once and\n * piped into any query over the same Entity:\n *\n * ```ts\n * const published = Query.where(Expr.eq(Post.fields.published, true))\n * Query.from(Post).pipe(published, Query.where(byTitle))\n * ```\n */\n where:\n <const P extends ReadonlyArray<Predicate>>(...predicates: P) =>\n <E extends AnyEntity>(\n self: Query<E> & OverEntity<ReadsOf<P[number]>, E['name'], 'a predicate'>,\n ): Query<E> => {\n if (predicates.length === 0) return self\n checkOwnership('where', 'a predicate', self.entity, predicates)\n const where = [...self.where, ...predicates]\n checkSize('where', where, self.orderBy)\n return query(self.entity, where, self.orderBy)\n },\n\n /**\n * Reads the rows in this order. Two `orderBy`s append, so an earlier term\n * stays the more significant one and a later call adds a tie-breaker rather\n * than silently winning.\n */\n orderBy:\n <const T extends ReadonlyArray<Ordering>>(...terms: T) =>\n <E extends AnyEntity>(\n self: Query<E> & OverEntity<ReadsOf<T[number]>, E['name'], 'an ordering term'>,\n ): Query<E> => {\n if (terms.length === 0) return self\n checkOwnership('orderBy', 'a term', self.entity, terms)\n const orderBy = [...self.orderBy, ...terms]\n checkSize('orderBy', self.where, orderBy)\n return query(self.entity, self.where, orderBy)\n },\n\n /**\n * The fixed terms this query orders by for one input: each chosen order\n * resolved to the field its input names, or to nothing for a `null` sort,\n * and the Entity's id last, ascending, unless the terms already read it. So\n * the order is total, and every interpreter breaks ties the same way: one\n * that broke them its own way would place rows a step apart from another.\n */\n orderFor: (\n self: AnyQuery,\n input: Readonly<Record<string, unknown>>,\n ): ReadonlyArray<OrderTerm> => {\n const terms = self.orderBy.flatMap(entry =>\n Match.value(entry).pipe(\n Match.tagsExhaustive({\n Term: term => [term],\n Chosen: chosen => chosenTerms(chosen, input),\n }),\n ),\n )\n const id = idTermOf(self.entity)\n // Every field an order reads is this Entity's: `orderBy` refuses another's.\n const endsOnId = terms.some(term => term.expr._tag === 'Field' && term.expr.key === 'id')\n return endsOnId ? terms : [...terms, id]\n },\n\n /**\n * Whether a client can order this query's rows exactly as the server does,\n * for one input: every term over a number or a boolean (a row may lack it), or over text with a\n * portable collation (`binary`, `asciiFold`), or a call whose primitive\n * operators the client's table (`operators`; none when not given) runs. A\n * body that names no order leaves it to the server, and is never placeable.\n */\n placement: (\n self: AnyQuery,\n input: Readonly<Record<string, unknown>>,\n options: { readonly operators?: OperatorTable | undefined } = {},\n ): Placement => {\n if (self.orderBy.length === 0) {\n return notPlaceable(\"its order is the server's: the body names none\")\n }\n const operators = options.operators ?? noOperators\n for (const orderTerm of Query.orderFor(self, input)) {\n const reason = unplaceable(orderTerm, operators)\n if (Option.isSome(reason)) return notPlaceable(reason.value)\n }\n return placeable\n },\n\n /**\n * Each operator the body calls, by name (`id`, or `id@version` past the\n * first), in the order it first calls them: a defined one, and each\n * primitive one its expansion calls.\n */\n operators: (self: AnyQuery): ReadonlyArray<string> =>\n Query.dependencies(self).operators.map(operatorName),\n\n /**\n * What the whole query reads: the fields and inputs of every predicate and\n * every ordering term, and the operations it uses, with the fields also\n * split by role.\n */\n dependencies: (self: AnyQuery): QueryDependencies => ({\n ...dependenciesOf(...self.where, ...self.orderBy),\n predicate: dependenciesOf(...self.where).fields,\n order: dependenciesOf(...self.orderBy).fields,\n }),\n\n /**\n * The operations this query needs that `supported` does not list, in the\n * order the query uses them, then each primitive operator `operators` does\n * not implement, by name. Without `operators`, every primitive operator is\n * named: a list of operations implements none. Empty means an interpreter\n * declaring both can answer it.\n *\n * An interpreter declares what it runs and refuses the rest, rather than\n * ignoring an operation it does not implement — which would answer a\n * different question and say nothing. The refusal is the interpreter's to\n * raise: this only says what is missing, because what to do about it differs\n * between one that compiles at registration and one that runs a body\n * directly.\n *\n * ```ts\n * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])\n * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)\n * ```\n */\n unsupported: (\n self: AnyQuery,\n supported: ReadonlyArray<Operation>,\n operators: OperatorTable = noOperators,\n ): ReadonlyArray<string> => unsupportedIn([...self.where, ...self.orderBy], supported, operators),\n\n /**\n * The whole query as readable text, one clause per line:\n *\n * ```text\n * FROM Post\n * WHERE Post.slug = $slug\n * AND Post.published = true\n * ORDER BY Post.updatedAt DESC\n * ```\n *\n * For an explanation or a diagnostic, never for an interpreter — see\n * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather\n * than printing an empty one, so what is shown is what was written.\n */\n show: (self: AnyQuery): string =>\n [\n `FROM ${self.entity.name}`,\n // Among several, an `or` is parenthesised: `WHERE a or b` over `AND c`\n // would read as `a or (b and c)`.\n ...self.where.map(\n (predicate, index) =>\n `${index === 0 ? 'WHERE' : ' AND'} ${Match.value(predicate).pipe(\n Match.tag('Or', or => (self.where.length > 1 ? `(${Expr.show(or)})` : Expr.show(or))),\n Match.orElse(each => Expr.show(each)),\n )}`,\n ),\n ...(self.orderBy.length === 0\n ? []\n : [\n `ORDER BY ${self.orderBy\n .map(entry =>\n Match.value(entry).pipe(\n Match.tagsExhaustive({\n Term: term => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`,\n Chosen: chosen =>\n `$${chosen.sort.key} among (${Object.entries(chosen.choices)\n .map(([name, field]) => `${name}: ${Expr.show(field)}`)\n .join(', ')})`,\n }),\n ),\n )\n .join(', ')}`,\n ]),\n ].join('\\n'),\n}\n\n/**\n * An expression as readable text, in the IR's own terms.\n *\n * This is for a human — an explanation, a diagnostic, a test that wants to\n * assert on a whole predicate at once — and deliberately **not** for an\n * interpreter. It is close enough to SQL to read at a glance and unlike it\n * everywhere that matters: an input is `$slug` rather than a bound parameter,\n * `contains` is named rather than rendered as somebody's `like`, and no\n * dialect's escaping or collation is implied. What actually ran is whatever\n * that backend compiled, which is not this.\n *\n * A predicate standing where a value is wanted is parenthesised, because\n * `x is not null = $archived` reads as three operands and is two. A predicate\n * that *is* the whole expression is not: nothing encloses it.\n */\nconst showExpr = (node: AnyExpr | Predicate): string => {\n switch (node._tag) {\n case 'Literal':\n return JSON.stringify(node.value) ?? String(node.value)\n case 'Field':\n return `${node.owner.name}.${node.key}`\n case 'Input':\n return `$${node.key}`\n case 'Next':\n return `next ${node.field.owner.name}.${node.field.key}`\n case 'Viewer':\n return `viewer ${node.entity.name}`\n case 'Now':\n return 'now'\n case 'Eq':\n return `${showOperand(node.left)} = ${showOperand(node.right)}`\n case 'Null':\n return `${showOperand(node.operand)} is ${node.present ? 'not null' : 'null'}`\n case 'Contains':\n return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`\n case 'In':\n return `${showOperand(node.value)} in ${showOperand(node.among)}`\n case 'And':\n return node.operands.map(showConnected).join(' and ')\n case 'Or':\n return node.operands.map(showConnected).join(' or ')\n case 'Not':\n return `not (${showExpr(node.operand)})`\n case 'Compare':\n return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`\n case 'Call':\n case 'Test':\n return `${operatorName(node.operator)}(${node.args.map(showOperand).join(', ')})`\n // `Post.author.handle`: the judged row's relation, then each next one, then the field.\n case 'Path':\n return [`${node.via[0].owner.name}`, ...node.via.map(step => step.key), node.field.key].join(\n '.',\n )\n // `viewer Member.team.orgId`: the viewer's row, each relation from it, then the field.\n case 'ViewerPath':\n return `viewer ${[node.viewer.entity.name, ...node.via.map(step => step.key), node.field.key].join('.')}`\n case 'Exists': {\n const sought = `exists ${node.relation.owner.name}.${node.relation.key}${Option.match(\n node.where,\n { onNone: () => '', onSome: where => ` where ${showExpr(where)}` },\n )}`\n const [first] = node.via\n return first === undefined\n ? sought\n : `${[first.owner.name, ...node.via.map(step => step.key)].join('.')}: ${sought}`\n }\n }\n}\n\n/**\n * Where an exists starts on the judged row: the relation its path follows\n * first, or, asked of the row itself, its id, which the pointing rows hold.\n */\nconst existsStart = (\n exists: ExistsPredicate,\n): { readonly owner: EntityIdentity<string>; readonly key: string } =>\n exists.via[0] ?? { owner: exists.relation.target().identity, key: 'id' }\n\n/** A call's expansion, scalar or predicate alike. */\nconst expansionOf = (call: CallExpr<unknown> | TestPredicate): Option.Option<AnyExpr | Predicate> =>\n call.expansion\n\n/**\n * What `nodes` need that an interpreter lacks: each kernel operation it does\n * not list, then each primitive operator its table does not implement, by\n * name. A defined operator needs nothing: what it means is walked instead.\n */\nconst unsupportedIn = (\n nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>,\n supported: ReadonlyArray<Operation>,\n operators: OperatorTable,\n): ReadonlyArray<string> => {\n const read = dependenciesOf(...nodes)\n const runs = new Set(supported)\n return [\n ...read.operations.filter(operation => !runs.has(operation)),\n ...missingFrom(read.operators, operators),\n ]\n}\n\n/**\n * The primitive operators among `read` that `operators` does not implement, by\n * name. A defined one needs nothing: what it means was walked into `read`.\n */\nconst missingFrom = (\n read: ReadonlyArray<OperatorDescriptor>,\n operators: OperatorTable,\n): ReadonlyArray<string> =>\n read\n .filter(operator => Option.isNone(operator.definedAs) && !operators.has(operator))\n .map(operator => missingName(operator, operators))\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\nconst symbols: Readonly<Record<CompareOperator, string>> = {\n lt: '<',\n lte: '<=',\n gt: '>',\n gte: '>=',\n}\n\n/** An operand of `and` or `or`: another connective is parenthesised, so its grouping shows. */\nconst showConnected = (node: Predicate): string =>\n Match.value(node).pipe(\n Match.tags({ And: () => `(${showExpr(node)})`, Or: () => `(${showExpr(node)})` }),\n Match.orElse(() => showExpr(node)),\n )\n\nconst showOperand = (node: Operandish): string =>\n isPredicate(node) ? `(${showExpr(node)})` : showExpr(node)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8HA,MAAa,cAA6B,OAAO,OAAO;CAAE,WAAW;CAAO,gBAAgB,CAAC;AAAE,CAAC;;;;;AAMhG,MAAa,eAAe,UAA8B,cAAqC;CAC7F,MAAM,OAAO,UAAU,SAAS,SAAS,EAAE;CAG3C,IAAI,KAAK,SAAS,SAAS,OAAO,GAChC,OAAO,GAAG,aAAa,QAAQ,EAAE;CAEnC,OAAO,KAAK,WAAW,IACnB,aAAa,QAAQ,IACrB,GAAG,aAAa,QAAQ,EAAE,mBAAmB,KAC1C,KAAI,YAAW,aAAa;EAAE,GAAG;EAAU;CAAQ,CAAC,CAAC,CAAC,CACtD,KAAK,IAAI,EAAE;AACpB;AA8RA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO,KAAA;;;;;;;;;;;;;AAchF,MAAM,QAA0B,UAAgB,OAAO,OAAO,KAAK;AAEnE,MAAM,WAAc,UAA6B,KAAK;CAAE,MAAM;CAAW;AAAM,CAAC;AAEhF,MAAM,aAAa,UACjB,KAAK;CACH,MAAM;CACN,OAAO,MAAM;CACb,KAAK,MAAM;CACX,QAAQ,MAAM;CACd,WAAW,OAAO,OAAO,UAAU,SAAS,MAAM,QAAQ,SACxD,MAAM,QAAQ,OAAO,OAAO,KAAK,UAAU,MAAM,IAAI,OAAO,KAAK,CACnE;AACF,CAAC;;;;;;;AAQH,MAAM,YAAY,aAChB,KAAK;CACH,MAAM;CACN,OAAO,S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