foldkit-entity 0.12.0 → 0.13.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-DBAilaDV.mjs","names":["key","nameOf","operatorName","Arr","fail","fail","fail"],"sources":["../src/collation.ts","../src/shape.ts","../src/jsonSchema.ts","../src/law.ts","../src/expr.ts","../src/tested.ts","../src/text.ts","../src/operators.ts","../src/evaluate.ts","../src/invariant.ts","../src/readFilter.ts","../src/words.ts","../src/write.ts","../src/index.ts"],"sourcesContent":["/**\n * How text compares when a query orders by it, declared rather than left to\n * the backend. Left unsaid, SQLite compares bytes, Postgres follows the\n * database's locale and a JavaScript sort follows UTF-16 code units, so the\n * same body could order the same rows three ways. A declared collation is one\n * every interpreter that can honour it compiles to the same order, and one\n * that cannot refuses.\n *\n * It is a trait of a field (`Entity.annotateMembers({ title: Collation.of(\n * Collation.binary) })`), so most queries declare nothing; an order term may\n * override it (`Order.asc(field, { collation })`).\n */\nimport { Option } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\n\nexport type Collation =\n /** By code point: SQLite `BINARY`, Postgres `COLLATE \"C\"`. */\n | { readonly _tag: 'Binary' }\n /** ASCII letters folded to lower case, then by code point: SQLite `NOCASE`, Postgres `lower(x COLLATE \"C\")`. */\n | { readonly _tag: 'AsciiFold' }\n /** The backend's collation by this name: ordered by the server, never by a client. */\n | { readonly _tag: 'Locale'; readonly locale: string }\n\nconst key = Metadata.key<Collation>('foldkit-entity/collation', {\n // The last collation attached wins: a later annotation refines an earlier one.\n merge: collations => collations.slice(-1),\n summarize: collation => collation._tag,\n})\n\n/** A collation name a backend can be told, and nothing that could be read as SQL. */\nconst localeName = /^[A-Za-z0-9_.@-]{1,64}$/\n\nexport const Collation = {\n binary: Object.freeze({ _tag: 'Binary' }) as Collation,\n asciiFold: Object.freeze({ _tag: 'AsciiFold' }) as Collation,\n locale: (locale: string): Collation => {\n if (!localeName.test(locale)) {\n throw new Error(`[foldkit-entity] Collation.locale: \"${locale}\" is not a collation name`)\n }\n return Object.freeze({ _tag: 'Locale', locale })\n },\n\n /** Member metadata: how a text field orders, wherever a query orders by it. */\n of: (collation: Collation): Metadata => key.of(collation),\n\n /** The collation a member's metadata declares, if any. */\n declared: (metadata: Metadata): Option.Option<Collation> =>\n Option.fromUndefinedOr(key.get(metadata)[0]),\n\n /**\n * Text as `asciiFold` compares it: ASCII letters lowercased, every other\n * character as it is, which is what SQLite's `lower` does without ICU and so\n * what compiled SQL folds to. `toLowerCase` would fold `É` to `é` here and not\n * there. An operator implementing `asciiFold` folds with this.\n */\n foldAscii: (text: string): string => text.replace(/[A-Z]+/g, upper => upper.toLowerCase()),\n}\n","import { Match, SchemaAST } from 'effect'\n\nconst isNullish = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast)\n\nconst isText = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isString(ast) ||\n SchemaAST.isTemplateLiteral(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal === 'string') ||\n (SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText))\n\n/** Whether any of these checks is `Schema.isInt`, alone or inside a group (`isInt32`). */\nconst checksInteger = (checks: ReadonlyArray<SchemaAST.Check<unknown>>): boolean =>\n checks.some(check =>\n Match.value(check).pipe(\n Match.tagsExhaustive({\n Filter: filter => filter.annotations?.representation?.id === 'effect/schema/isInt',\n FilterGroup: group => checksInteger(group.checks),\n }),\n ),\n )\n\n/** What a schema's AST holds, read through Effect's own guards. */\nexport const SchemaShape = {\n /** True for the `null` and `undefined` members that make a schema optional. */\n isNullish,\n\n /**\n * The members of a schema with `null` and `undefined` set aside, so optional\n * text is still text; a schema that is not a union is its one member.\n */\n present: (ast: SchemaAST.AST): ReadonlyArray<SchemaAST.AST> =>\n SchemaAST.isUnion(ast) ? ast.types.filter(member => !isNullish(member)) : [ast],\n\n /** True when every value the schema admits is a string. */\n isText,\n\n /**\n * True when the AST is checked to hold integers (`Schema.isInt`, alone or in\n * a group such as `isInt32`). Read it from a schema's encoded side to ask\n * what the store holds.\n */\n holdsIntegers: (ast: SchemaAST.AST): boolean => checksInteger(ast.checks ?? []),\n}\n","/**\n * A schema's JSON Schema, of what it encodes to as JSON carries it, its\n * definitions kept under `$defs` so a `$ref` in it resolves. Not exported from\n * the package.\n */\nimport { Schema } from 'effect'\n\nexport const jsonSchemaOf = (schema: Schema.Top): Readonly<Record<string, unknown>> => {\n const document = Schema.toJsonSchemaDocument(schema)\n return Object.keys(document.definitions).length === 0\n ? document.schema\n : { ...document.schema, $defs: document.definitions }\n}\n","/**\n * Laws an operator declares (expr-operations-DESIGN §10): equations every\n * implementation of it keeps over a domain. A law describes; nothing rewrites a\n * body by one. `Conformance.laws` tests an implementation against them, and\n * what it finds is evidence recorded in that implementation's table.\n */\nimport { Data, Option, Schema } from 'effect'\nimport type { Operator } from './expr.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\n\n/** An operator a law names as a witness: the inverse, or the operator distributed over. */\ntype AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>\n\n/** Which argument a witness stands in. */\nexport type Side = 'left' | 'right' | 'both'\n\n/**\n * A law, over its domain: by default every non-null value of the operator's\n * input schemas; narrowed by `Law.within`.\n */\nexport type Law = Data.TaggedEnum<{\n /** `op(op(a, b), c) = op(a, op(b, c))` */\n Associative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, b) = op(b, a)` */\n Commutative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, a) = a` */\n Idempotent: { readonly domain: Option.Option<Schema.Top> }\n /** `op(e, a) = a` (left), `op(a, e) = a` (right), or both. */\n Identity: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(z, a) = z` (left), `op(a, z) = z` (right), or both. */\n Absorbing: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(a, other(a)) = identity` */\n Inverse: {\n readonly domain: Option.Option<Schema.Top>\n readonly other: AnyOperator\n readonly identity: unknown\n }\n /** `op(a, over(b, c)) = over(op(a, b), op(a, c))` */\n Distributes: { readonly domain: Option.Option<Schema.Top>; readonly over: AnyOperator }\n /** `a ≤ b` at `position` implies `op(…a…) ≤ op(…b…)`, or `≥` when decreasing. */\n Monotonic: {\n readonly domain: Option.Option<Schema.Top>\n readonly direction: 'increasing' | 'decreasing'\n readonly position: number\n }\n /** Folding the result equals folding the arguments first: its text keeps their collation (§7). */\n PreservesCollation: { readonly domain: Option.Option<Schema.Top> }\n}>\n\nconst Laws = Data.taggedEnum<Law>()\nconst unnarrowed = { domain: Option.none<Schema.Top>() }\n\n/**\n * A law as JSON says it: what `Operators.describe` lists and evidence names.\n * Its witnesses are values as stored and operators by name; its domain is a\n * JSON Schema, or `null` for the operator's whole input.\n */\nexport const LawDescription = Schema.Struct({\n kind: Schema.String,\n witnesses: Schema.Record(Schema.String, Schema.Unknown),\n domain: Schema.Unknown,\n})\nexport type LawDescription = typeof LawDescription.Type\n\n/** An operator by its id, and its version when that is not the first. */\nconst nameOf = (operator: AnyOperator): string =>\n operator.descriptor.version === 1\n ? operator.descriptor.id\n : `${operator.descriptor.id}@${operator.descriptor.version}`\n\nexport const Law = {\n associative: Laws.Associative(unnarrowed),\n commutative: Laws.Commutative(unnarrowed),\n idempotent: Laws.Idempotent(unnarrowed),\n preservesCollation: Laws.PreservesCollation(unnarrowed),\n /** `value` leaves the other argument as it is, from `side` (both by default). */\n identity: (value: unknown, side: Side = 'both'): Law =>\n Laws.Identity({ ...unnarrowed, value, side }),\n /** `value` is the answer whatever the other argument, from `side` (both by default). */\n absorbing: (value: unknown, side: Side = 'both'): Law =>\n Laws.Absorbing({ ...unnarrowed, value, side }),\n /** `other` undoes the operator: `op(a, other(a))` is `identity`. */\n inverse: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n other: Operator<In, Out>,\n identity: unknown,\n ): Law => Laws.Inverse({ ...unnarrowed, other, identity }),\n /** The operator distributes over `over`, from the left. */\n distributes: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n over: Operator<In, Out>,\n ): Law => Laws.Distributes({ ...unnarrowed, over }),\n /** Moving the argument at `position` up moves the result up (or down, decreasing). */\n monotonic: (direction: 'increasing' | 'decreasing', position: number): Law =>\n Laws.Monotonic({ ...unnarrowed, direction, position }),\n /**\n * The law over the values `domain` accepts only: a law that holds of the\n * integers and not of every number, say, narrowed so it is tested where it\n * is claimed.\n */\n within: (law: Law, domain: Schema.Top): Law =>\n Object.freeze({ ...law, domain: Option.some(domain) }),\n\n $match: Laws.$match,\n\n /**\n * The operators a law, as JSON, calls besides its own (`inverse`'s and\n * `distributes`' witnesses), by name: evidence of it is of their\n * implementations too, and goes when one of them is replaced.\n */\n witnessesNamed: (law: LawDescription): ReadonlyArray<string> =>\n [law.witnesses['other'], law.witnesses['over']].filter(\n (name): name is string => typeof name === 'string',\n ),\n\n /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */\n describe: (law: Law): LawDescription => {\n const witnesses: Record<string, unknown> = Laws.$match(law, {\n Associative: () => ({}),\n Commutative: () => ({}),\n Idempotent: () => ({}),\n PreservesCollation: () => ({}),\n Identity: ({ value, side }) => ({ value, side }),\n Absorbing: ({ value, side }) => ({ value, side }),\n Inverse: ({ other, identity }) => ({ other: nameOf(other), identity }),\n Distributes: ({ over }) => ({ over: nameOf(over) }),\n Monotonic: ({ direction, position }) => ({ direction, position }),\n })\n return {\n kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),\n witnesses,\n domain: Option.match(law.domain, {\n onNone: () => null,\n onSome: jsonSchemaOf,\n }),\n }\n },\n}\n","/**\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 type { AnyEntity, EntityField, EntityIdentity } 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 typed scalar: what a comparison compares. */\nexport type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T> | NextExpr<T> | CallExpr<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\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/** A field, a scalar already built from one, or a predicate used as a boolean. */\ntype Operand<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 PlainValue | { readonly _tag: 'Literal' | 'Input' }\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 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\nconst predicateTags = new Set([\n 'Eq',\n 'Null',\n 'Contains',\n 'In',\n 'And',\n 'Or',\n 'Not',\n 'Compare',\n 'Test',\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 (\n tag === 'Literal' ||\n tag === 'Input' ||\n tag === 'Next' ||\n tag === 'Call' ||\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\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\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 }),\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.tag('Field', field => [\n { name: `${field.owner.name}.${field.key}`, collation: field.collation },\n ]),\n Match.tag('Next', ({ field }) => [\n { name: `${field.owner.name}.${field.key}`, collation: field.collation },\n ]),\n Match.tag('Call', call => [{ name: showExpr(call), collation: call.collation }]),\n Match.orElse(() => []),\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 }),\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 if (!storedAsBoolean(schema)) 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 }),\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 }),\n )\n expandedCache.set(predicate, result)\n return result\n}\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 text holding a NUL, or\n * a list holding one: SQL refuses such a parameter wherever it compiles, so\n * an interpreter refuses the run, not one row.\n */\n givesNul: (...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 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 /** One field of one Entity, as a scalar. */\n field: <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 fieldExpr(field) as FieldExpr<Schema.Schema.Type<S>>,\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 : ValueOf<L> | Expr<ValueOf<L>> | (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 }\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 // 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), () =>\n Match.value(expr).pipe(\n Match.tag('Field', field => field.collation),\n Match.tag('Call', call => call.collation),\n Match.orElse(() => Option.none<Collation>()),\n ),\n )\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\nexport const Order = {\n /** Smallest first; rows without a value last, unless `nulls` says first. */\n asc: <E extends Operand<any>>(expr: E, options?: TermOptions): OrderTerm & Reads<ReadsOf<E>> =>\n term('asc', toExpr(expr as never, 'asc'), options),\n /** Largest first; rows without a value first, unless `nulls` says last. */\n desc: <E extends Operand<any>>(expr: E, options?: TermOptions): OrderTerm & Reads<ReadsOf<E>> =>\n term('desc', toExpr(expr as never, '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]: Operand<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<Operand<any>>(choices)) {\n const expr = toExpr(choice as never, '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.orElse(() => Option.some('it orders by something that is neither a field nor a call')),\n )\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 = 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}\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 '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 '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 }\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 }\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/** Every field an expression reads, as the nodes themselves, each node visited once. */\nconst fieldsIn = function* (\n expr: AnyExpr | Predicate | Ordering,\n seen: Set<object>,\n): Generator<FieldExpr<unknown>> {\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 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 // 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 return []\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 '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 }\n}\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","/**\n * What made each `Tested` record: `Conformance.laws` over one memory\n * implementation, or `Conformance.lawsBy` through a runner. A table records\n * only evidence of its own kind, so a record built by hand, copied, or tested\n * on another implementation is refused. Kept beside the records rather than in\n * them: a record is JSON a server publishes, and an implementation is a\n * function. Not exported from the package.\n */\nimport { Option } from 'effect'\nimport type { Evidence, MemoryImplementation } from './operators.js'\n\nconst testedOn = new WeakMap<Evidence, MemoryImplementation>()\nconst ranByRunner = new WeakSet<Evidence>()\n\nexport const stampTested = (record: Evidence, implementation: MemoryImplementation): void => {\n testedOn.set(record, implementation)\n}\n\nexport const stampRun = (record: Evidence): void => {\n ranByRunner.add(record)\n}\n\nexport const implementationTested = (record: Evidence): Option.Option<MemoryImplementation> =>\n Option.fromUndefinedOr(testedOn.get(record))\n\nexport const testedByRunner = (record: Evidence): boolean => ranByRunner.has(record)\n","/**\n * The kernel's text operators: primitive, so each interpreter implements them,\n * and each states what it means here, where data-query §6.0.1 holds the rest.\n */\nimport { Schema } from 'effect'\nimport { Expr } from './expr.js'\n\nexport const Text = {\n /**\n * Whether the first text begins with the second, under the first's collation.\n *\n * | Case | Answer |\n * | --- | --- |\n * | either is null | unknown |\n * | the prefix is `''` | true |\n * | otherwise | whether it begins so, compared under the collation |\n *\n * The collation is the one its text operands share (a field's declared one,\n * or a call's), or one given to the call. `binary` compares exactly;\n * `asciiFold` folds ASCII letters on both sides. Operands declaring\n * different collations, text with none, or a backend's locale are refused\n * where the call is written.\n * Prefixes are by character, so non-ASCII and astral text begin as they read.\n *\n * ```ts\n * Query.where(Text.startsWith(Product.fields.upc, input.search))\n * ```\n */\n startsWith: Expr.operator('text.startsWith', {\n input: [Schema.NullOr(Schema.String), Schema.NullOr(Schema.String)],\n output: Schema.Boolean,\n collation: 'required',\n description: \"Whether the first text begins with the second, under the first's collation.\",\n }),\n}\n","/**\n * How the in-memory interpreter runs primitive operators: a table of\n * implementations, passed to `evaluate` and every judge as a value. A table is\n * immutable and implements each operator once; nothing registers anything\n * globally. See `docs/design/expr-operations-DESIGN.md` §5.4.\n */\nimport { Data, Option, Schema } from 'effect'\nimport { Collation } from './collation.js'\nimport type { Operator, OperatorDescriptor, OperatorTable } from './expr.js'\nimport { Law, LawDescription } from './law.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\nimport { implementationTested, testedByRunner } from './tested.js'\nimport { Text } from './text.js'\n\n/** What an implementation is told besides its arguments. */\nexport interface OperatorContext {\n /** The collation the call compares text under, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/** One operator's in-memory implementation: a pure function of stored values. */\nexport interface MemoryImplementation {\n readonly operator: OperatorDescriptor\n readonly run: (args: ReadonlyArray<unknown>, context: OperatorContext) => unknown\n}\n\n/**\n * What is known of a law of an implementation, past its operator claiming it\n * (expr-operations-DESIGN §10.3): `Tested`, it passed `Conformance.laws`'\n * cases; `Proven`, a proof elsewhere says so under its assumptions, recorded\n * and never checked here.\n */\nexport type Evidence = Data.TaggedEnum<{\n Tested: {\n readonly operator: string\n readonly law: LawDescription\n readonly implementation: string\n readonly cases: number\n readonly seed: number\n }\n Proven: {\n readonly operator: string\n readonly law: LawDescription\n readonly reference: string\n readonly assumptions: ReadonlyArray<string>\n }\n}>\nexport const Evidence = Data.taggedEnum<Evidence>()\n\n/** A record of a law passing `Conformance.laws`' cases. */\nexport type TestedEvidence = Extract<Evidence, { readonly _tag: 'Tested' }>\n\n/** A JSON Schema document's root: an object (`$defs` holds what it refers to). */\nconst JsonSchema = Schema.Record(Schema.String, Schema.Unknown)\n\n/**\n * An operator as JSON, by its signature and never its body (a defined\n * operator says `defined`, not what it means): what a server can publish of\n * what a body may call, and a client compare with what it runs. Its schemas\n * are each argument's and the result's stored side, as JSON Schemas.\n */\nexport const OperatorDescription = Schema.Struct({\n /** By id, and `@version` past the first: what tables, evidence and refusals name. */\n name: Schema.String,\n id: Schema.String,\n version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n description: Schema.NullOr(Schema.String),\n input: Schema.Array(JsonSchema),\n output: JsonSchema,\n nulls: Schema.Literals(['strict', 'handled']),\n collation: Schema.Literals(['none', 'operands', 'required']),\n laws: Schema.Array(LawDescription),\n defined: Schema.Boolean,\n})\nexport type OperatorDescription = typeof OperatorDescription.Type\n\n/** One operator a table implements, as `Operators.describeTable` lists it: described, with its evidence. */\nexport interface ImplementedOperator extends OperatorDescription {\n readonly evidence: ReadonlyArray<Evidence>\n}\n\nconst described = (operator: OperatorDescriptor): OperatorDescription => ({\n name: nameOf(operator),\n id: operator.id,\n version: operator.version,\n description: Option.getOrNull(operator.description),\n input: operator.input.map(jsonSchemaOf),\n output: jsonSchemaOf(operator.output),\n nulls: operator.nulls,\n collation: operator.collation,\n laws: operator.laws.map(Law.describe),\n defined: Option.isSome(operator.definedAs),\n})\n\n/** The in-memory interpreter's implementations, by operator. */\nexport interface MemoryOperators extends OperatorTable {\n readonly _tag: 'MemoryOperators'\n readonly get: (operator: OperatorDescriptor) => Option.Option<MemoryImplementation['run']>\n /**\n * The operator it implements under a name (`id`, or `id@version` past the\n * first): how a computed assignment carried as data finds what to run.\n */\n readonly named: (name: string) => Option.Option<OperatorDescriptor>\n /** Whether each answer is checked against its operator's output schema: for tests. */\n readonly checked: boolean\n readonly implementations: ReadonlyArray<MemoryImplementation>\n /** What is known of its implementations' laws: `Operators.withEvidence`. */\n readonly evidence: ReadonlyArray<Evidence>\n}\n\ntype StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>\n\n/** An operator by its id, and its version when that is not the first. */\nconst nameOf = (operator: OperatorDescriptor): string =>\n operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`\n\nconst fail = (what: string): never => {\n throw new Error(`[foldkit-entity] Operators: ${what}`)\n}\n\nconst table = (\n implementations: ReadonlyArray<MemoryImplementation>,\n checked: boolean,\n evidence: ReadonlyArray<Evidence>,\n): MemoryOperators => {\n const byOperator = new Map<OperatorDescriptor, MemoryImplementation['run']>()\n const byName = new Map<string, OperatorDescriptor>()\n for (const { operator, run } of implementations) {\n if (byOperator.has(operator)) {\n fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`)\n }\n // Two descriptors under one name would leave a body's call ambiguous.\n const named = byName.get(nameOf(operator))\n if (named !== undefined && named !== operator) {\n fail(`two operators are named ${nameOf(operator)}; give one another id or version`)\n }\n byName.set(nameOf(operator), operator)\n byOperator.set(operator, run)\n }\n return Object.freeze({\n _tag: 'MemoryOperators',\n has: (operator: OperatorDescriptor) => byOperator.has(operator),\n versions: (id: string) =>\n implementations\n .filter(({ operator }) => operator.id === id)\n .map(({ operator }) => operator.version),\n get: (operator: OperatorDescriptor) => Option.fromUndefinedOr(byOperator.get(operator)),\n named: (name: string) => Option.fromUndefinedOr(byName.get(name)),\n checked,\n implementations: Object.freeze([...implementations]),\n evidence: Object.freeze([...evidence]),\n })\n}\n\n/** Whether two laws, as JSON, are the same law. */\nconst sameLaw = (left: LawDescription, right: LawDescription): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** An implementation, its operator's null rule checked against the function chosen for it. */\nconst implementation = (\n operator: OperatorDescriptor,\n nulls: OperatorDescriptor['nulls'],\n run: (...args: ReadonlyArray<unknown>) => unknown,\n): MemoryImplementation => {\n // SQL compiles what a defined operator means, so an implementation here would\n // be a second meaning that only memory runs.\n if (Option.isSome(operator.definedAs)) {\n fail(\n `${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`,\n )\n }\n if (operator.nulls !== nulls) {\n fail(\n nulls === 'strict'\n ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls`\n : `${nameOf(operator)} is strict about null; implement it with Operators.implement`,\n )\n }\n return Object.freeze({\n operator,\n run: (args: ReadonlyArray<unknown>, context: OperatorContext) => run(...args, context),\n })\n}\n\nconst startsWith = implementation(Text.startsWith.descriptor, 'strict', (...given) => {\n const [text, prefix, { collation }] = given as [string, string, OperatorContext]\n const folded = Option.exists(collation, each => each._tag === 'AsciiFold')\n return folded\n ? Collation.foldAscii(text).startsWith(Collation.foldAscii(prefix))\n : text.startsWith(prefix)\n})\n\nexport const Operators = {\n /**\n * An implementation of a strict operator: a pure function of its arguments'\n * stored values, never given a null (the kernel answers null, or unknown, for\n * one first), and told the call's collation last.\n *\n * ```ts\n * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))\n * ```\n */\n implement: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: NonNullable<StoredOf<In[K]>> }, OperatorContext]\n ) => StoredOf<Out>,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'strict',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /**\n * An implementation of an operator declared `nulls: 'handled'`: given nulls\n * as they are, it answers for them; a predicate answers `null` for unknown.\n */\n implementHandlingNulls: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: StoredOf<In[K]> }, OperatorContext]\n ) => StoredOf<Out> | null,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'handled',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /** A table of implementations. One operator implemented twice, or two under one name, is refused. */\n memory: (...implementations: ReadonlyArray<MemoryImplementation>): MemoryOperators =>\n table(implementations, false, []),\n\n /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */\n merge: (left: MemoryOperators, right: MemoryOperators): MemoryOperators => {\n const both = right.implementations.filter(({ operator }) => left.has(operator))\n if (both.length > 0) {\n fail(\n `both tables implement ${both.map(({ operator }) => nameOf(operator)).join(', ')}; replace with Operators.override`,\n )\n }\n return table(\n [...left.implementations, ...right.implementations],\n left.checked || right.checked,\n [...left.evidence, ...right.evidence],\n )\n },\n\n /**\n * The table with these implementations in place of its own for the same\n * operators. Evidence of a replaced implementation goes with it: it was\n * that implementation's.\n */\n override: (\n base: MemoryOperators,\n ...implementations: ReadonlyArray<MemoryImplementation>\n ): MemoryOperators => {\n const replaced = new Set(implementations.map(({ operator }) => operator))\n const names = new Set([...replaced].map(nameOf))\n return table(\n [\n ...base.implementations.filter(({ operator }) => !replaced.has(operator)),\n ...implementations,\n ],\n base.checked,\n // A replaced operator's evidence goes, and so does a law's that called it as a witness.\n base.evidence.filter(\n ({ operator, law }) =>\n !names.has(operator) && !Law.witnessesNamed(law).some(name => names.has(name)),\n ),\n )\n },\n\n /**\n * The table with what is known of its implementations' laws recorded: each\n * record of an operator it implements and a law that operator declares.\n * `Conformance.laws` gives `Tested` records, each of the implementation it\n * ran, and a table takes only those of its own; `Evidence.Proven` says a\n * proof elsewhere covers one.\n */\n withEvidence: (base: MemoryOperators, evidence: ReadonlyArray<Evidence>): MemoryOperators => {\n const own = new Map(base.implementations.map(each => [nameOf(each.operator), each]))\n for (const record of evidence) {\n const implemented =\n own.get(record.operator) ??\n fail(`evidence names ${record.operator}, which this table does not implement`)\n if (!implemented.operator.laws.map(Law.describe).some(law => sameLaw(law, record.law))) {\n fail(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`)\n }\n // Evidence of another implementation, or of a runner, says nothing of this one.\n if (\n record._tag === 'Tested' &&\n !Option.exists(implementationTested(record), tested => tested === implemented)\n ) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was not tested on this table's implementation; test it with Conformance.laws(op, table)`,\n )\n }\n }\n return table(base.implementations, base.checked, [...base.evidence, ...evidence])\n },\n\n /**\n * The memory implementation `Conformance.laws` tested a record on; none for\n * a record of a runner (`Conformance.lawsBy`) or a proof.\n */\n testedOn: (record: Evidence): Option.Option<MemoryImplementation> => implementationTested(record),\n\n /**\n * Whether `Conformance.lawsBy` made a record, through a runner: what an SQL\n * table takes. Which runner it was, the database's or another, is the\n * caller's word; a record built by hand, copied, or tested in memory is not.\n */\n testedByRunner,\n\n /**\n * Each operator the table implements, by name, with the laws it declares and\n * the evidence the table records of them: what a server can publish of how\n * it runs a body. JSON as it is.\n */\n describeTable: (base: MemoryOperators): ReadonlyArray<ImplementedOperator> =>\n base.implementations.map(({ operator }) => ({\n ...described(operator),\n evidence: base.evidence.filter(record => record.operator === nameOf(operator)),\n })),\n\n /**\n * An operator as JSON (`OperatorDescription`): its name, version and\n * description, each argument's and its result's stored side as a JSON\n * Schema (as JSON carries it: a number also admits the strings `\"Infinity\"`,\n * `\"-Infinity\"` and `\"NaN\"`), its null and collation rules, its laws, and\n * whether it is defined. Its signature, never its body.\n */\n describe: (operator: { readonly descriptor: OperatorDescriptor }): OperatorDescription =>\n described(operator.descriptor),\n\n /**\n * The table, checking every answer against its operator's output schema, so\n * an implementation that answers the wrong kind fails where it answered. For\n * tests: it costs a decode per call.\n */\n checked: (base: MemoryOperators): MemoryOperators =>\n table(base.implementations, true, base.evidence),\n\n /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */\n kernel: table([startsWith], false, []),\n}\n","/**\n * The reference interpreter: a query body run over rows already in memory.\n *\n * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body\n * directly, which is what makes \"source-neutral\" a fact rather than a claim —\n * the two are checked against each other over a real database, and a body that\n * means one thing here and another there is a bug in one of them.\n *\n * It is also the interpreter to reach for when there is no database: a test\n * that wants rows, a server assembling a page from values it already holds, or\n * a client judging rows it already has.\n *\n * It lives in `foldkit-entity` because it is the **reference semantics** of the\n * IR this package owns — what §6.0.1 means operationally rather than in prose —\n * and a specification's reference implementation belongs with the\n * specification. The rule that keeps it here: **it may depend on the IR and\n * nothing else.** The moment it wants a Remote concept it has moved to the\n * wrong place and should leave.\n *\n * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,\n * because SQL is what the other interpreter runs. The important case is null:\n * `null = null` is unknown in SQL and a row is not matched by it, where\n * JavaScript would happily call the two equal.\n */\nimport { Match, Option, Schema, SchemaAST } from 'effect'\nimport { absurd } from 'effect/Function'\nimport { Collation } from './collation.js'\nimport { Expr, Query, dependenciesOf, isPredicate, missingName, noOperators } from './expr.js'\nimport type {\n AnyExpr,\n AnyQuery,\n CallExpr,\n Operandish,\n Operation,\n OperatorDescriptor,\n OperatorTable,\n OrderTerm,\n Predicate,\n TestPredicate,\n} from './expr.js'\nimport { Operators, type MemoryImplementation, type MemoryOperators } from './operators.js'\n\n/** A row as this interpreter reads one: values by field key. */\nexport type Row = Readonly<Record<string, unknown>>\n\nexport class QueryEvaluateError extends Error {\n constructor(message: string) {\n super(`[foldkit-entity] ${message}`)\n this.name = 'QueryEvaluateError'\n }\n}\n\n/**\n * A call of a primitive operator the table does not implement. Its own class,\n * because a form judging an invariant reads it as a judgement it cannot make\n * (`Undecided`), not as a failure.\n */\nexport class OperatorMissingError extends QueryEvaluateError {\n readonly operator: OperatorDescriptor\n /** The operator by its id, and its version past the first. */\n readonly named: string\n /** `operators`, the table that lacks it, names the versions of it that it does hold. */\n constructor(operator: OperatorDescriptor, operators: OperatorTable = noOperators) {\n super(`this interpreter does not run the operator \"${missingName(operator, operators)}\"`)\n this.name = 'OperatorMissingError'\n this.operator = operator\n this.named = operatorName(operator)\n }\n}\n\n/** An operator by its id, and its version when that is not the first. */\nconst operatorName = (operator: OperatorDescriptor): string =>\n operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`\n\n/**\n * What a predicate is judged over: the row, the input it was given, and the row\n * a write would leave, which an invariant reads (`Next`).\n */\ninterface Scope {\n readonly row: Row\n readonly input: Row\n readonly next: Row\n /** How a primitive operator is run. */\n readonly operators: MemoryOperators\n}\n\nconst valueOf = (node: AnyExpr, scope: Scope): unknown => {\n switch (node._tag) {\n case 'Field':\n return scope.row[node.key]\n case 'Next':\n return scope.next[node.field.key]\n case 'Literal':\n return node.value\n case 'Input':\n return scope.input[node.key]\n case 'Call':\n return called(node, scope)\n default:\n return absurd(node)\n }\n}\n\n/**\n * What a call comes to, as a value (a predicate's truth as SQL's, unknown as\n * null). A defined operator's is what it means, as SQL compiles it; a\n * primitive one's is the table's implementation, or it is refused by name.\n */\nconst called = (call: CallExpr<unknown> | TestPredicate, scope: Scope): unknown => {\n const expansion: Option.Option<AnyExpr | Predicate> = call.expansion\n return Option.match(expansion, {\n onSome: body => sideOf(body, scope),\n onNone: () =>\n Option.match(scope.operators.get(call.operator), {\n onSome: run => ran(call, run, scope),\n onNone: () => {\n throw new OperatorMissingError(call.operator, scope.operators)\n },\n }),\n })\n}\n\n/** A call of a primitive operator run, its arguments worked out over the scope. */\nconst ran = (\n call: CallExpr<unknown> | TestPredicate,\n run: MemoryImplementation['run'],\n scope: Scope,\n): unknown =>\n runWith(\n call.operator,\n run,\n call.args.map(arg => sideOf(arg, scope)),\n call.collation,\n call._tag === 'Test',\n scope.operators.checked,\n )\n\n/**\n * A primitive operator run over values: strict about null and NUL before it\n * is asked, a throw it makes named as its own, and, in a checked table, its\n * answer held to its output schema (a predicate's null is its unknown).\n */\nconst runWith = (\n operator: OperatorDescriptor,\n run: MemoryImplementation['run'],\n values: ReadonlyArray<unknown>,\n collation: Option.Option<Collation>,\n predicate: boolean,\n checked: boolean,\n): unknown => {\n // NUL before null: SQL refuses text holding it where it is compiled, whatever\n // else the call is given, so a null beside it must not answer first.\n if (values.some(holdsNul)) {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" was given text holding a NUL character, which SQL text cannot hold portably`,\n )\n }\n if (operator.nulls === 'strict' && values.some(isNull)) return null\n let answer: unknown\n try {\n // A value never given (an input left out, a key the row lacks) is null to an\n // implementation that handles null, as SQL binds it.\n answer = run(\n values.map(value => (value === undefined ? null : value)),\n { collation },\n )\n } catch (error) {\n if (error instanceof QueryEvaluateError) throw error\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n const unknownTruth = predicate && answer === null\n if (checked && !unknownTruth && !Schema.is(Schema.toEncoded(operator.output))(answer)) {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(operator)}\" answered ${JSON.stringify(answer)}, which its output schema does not admit`,\n )\n }\n return answer\n}\n\n/**\n * A primitive operator over stored values, as a call of it is run: what a\n * computed assignment comes to (`Write.apply`). Refused, as a call is, when\n * `operators` does not implement it.\n */\nexport const applyOperator = (\n operator: OperatorDescriptor,\n values: ReadonlyArray<unknown>,\n options: {\n readonly collation: Option.Option<Collation>\n readonly operators: MemoryOperators\n },\n): unknown =>\n Option.match(options.operators.get(operator), {\n onNone: () => {\n throw new OperatorMissingError(operator, options.operators)\n },\n onSome: run =>\n runWith(\n operator,\n run,\n values,\n options.collation,\n SchemaAST.isBoolean(Schema.toEncoded(operator.output).ast),\n options.operators.checked,\n ),\n })\n\n/** A predicate operator's answer as a truth: null is unknown, anything but a boolean refused. */\nconst truthOf = (call: TestPredicate, answer: unknown): Truth => {\n if (answer === null || answer === undefined) return 'unknown'\n if (typeof answer !== 'boolean') {\n throw new QueryEvaluateError(\n `the operator \"${operatorName(call.operator)}\" answered ${JSON.stringify(answer)}, which is not a truth`,\n )\n }\n return answer\n}\n\n/** SQL's unknown: neither true nor false, and a row is kept only on true. */\ntype Truth = boolean | 'unknown'\n\nconst isNull = (value: unknown): boolean => value === null || value === undefined\n\nconst { foldAscii } = Collation\n\nconst NUL = String.fromCharCode(0)\n\n/**\n * Whether `value` is text holding a NUL, which Postgres text cannot hold and\n * SQLite compares only up to: no two interpreters agree on it.\n */\nconst holdsNul = (value: unknown): boolean => typeof value === 'string' && value.includes(NUL)\n\n/** A predicate used as a value is its own truth; anything else is its value. */\nconst sideOf = (node: Operandish, scope: Scope): unknown =>\n isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope)\n\n/**\n * What an operand comes to over no row: a call of literals and inputs, run by\n * `operators` (the kernel's when not given), a predicate as its truth with\n * unknown as null. How a conformance check asks an implementation one\n * question; refuses what `evaluate` refuses (an operator the table lacks,\n * text holding NUL).\n */\nexport const valueOfOperand = (\n node: Operandish,\n options: {\n readonly input?: Row | undefined\n readonly operators?: MemoryOperators | undefined\n } = {},\n): unknown =>\n sideOf(node, {\n row: {},\n input: options.input ?? {},\n next: {},\n operators: options.operators ?? Operators.kernel,\n })\n\n/**\n * Refuses a value the query was given (a literal or an input) holding a NUL,\n * before any null beside it can answer: SQL refuses such a parameter where it\n * compiles, whatever the row holds. A NUL stored in a row is refused after,\n * as SQL meets it only beside a value that is not null.\n */\nconst refuseGivenNul = (\n message: string,\n sides: ReadonlyArray<readonly [Operandish, unknown]>,\n): void => {\n if (\n sides.some(\n ([side, value]) =>\n !isPredicate(side) && (side._tag === 'Literal' || side._tag === 'Input') && holdsNul(value),\n )\n ) {\n throw new QueryEvaluateError(message)\n }\n}\n\n/**\n * A predicate compared as a value. SQL's unknown is null there too, so an\n * unknown compared to anything stays unknown rather than becoming false.\n */\nconst truthValue = (truth: Truth): unknown => (truth === 'unknown' ? null : truth)\n\nconst holds = (node: Predicate, scope: Scope): Truth => {\n switch (node._tag) {\n case 'Test':\n return truthOf(node, called(node, scope))\n case 'Eq': {\n const left = sideOf(node.left, scope)\n const right = sideOf(node.right, scope)\n // `null = anything` is unknown in SQL, including `null = null`. A row is\n // kept only when a comparison is true, so an unknown drops it either way;\n // saying so explicitly is what keeps this honest about three-valued logic\n // rather than accidentally right about it.\n const nul =\n 'an equality was given text holding a NUL character, which SQL text cannot hold portably'\n refuseGivenNul(nul, [\n [node.left, left],\n [node.right, right],\n ])\n if (isNull(left) || isNull(right)) return 'unknown'\n if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul)\n return left === right\n }\n case 'Null':\n // The one comparison that is never unknown: asking whether a value is\n // absent always has an answer.\n return isNull(valueOf(node.operand, scope)) !== node.present\n case 'Contains': {\n const value = valueOf(node.value, scope)\n const search = sideOf(node.search, scope)\n // `null like anything` is unknown, which is why an empty search is not\n // the same as no filter over a column that can be null.\n refuseGivenNul(\n 'a containment test was given text holding a NUL character, which SQL text cannot hold portably',\n [\n [node.search, search],\n [node.value, value],\n ],\n )\n if (isNull(value) || isNull(search)) return 'unknown'\n if (typeof value !== 'string' || typeof search !== 'string') {\n throw new QueryEvaluateError('a containment test was given something that is not text')\n }\n // Postgres text cannot hold NUL and SQLite's `like` stops at it, so no\n // two interpreters agree on such a value: refused rather than answered.\n if (holdsNul(value) || holdsNul(search)) {\n throw new QueryEvaluateError(\n 'a containment test was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n // Case-insensitive for ASCII letters only, because that is what\n // `Expr.contains` documents and what the compiled SQL folds both sides to.\n return foldAscii(value).includes(foldAscii(search))\n }\n case 'In': {\n const among = valueOf(node.among, scope)\n if (!Array.isArray(among)) {\n throw new QueryEvaluateError('a membership test was given a list that is not a list')\n }\n // SQL's `in`: an empty list is false whatever the value, then a null\n // value is unknown, a match is true, and no match against a list\n // holding a null is unknown, since that null might have been it.\n if (among.length === 0) return false\n const value = valueOf(node.value, scope)\n if (holdsNul(value) || among.some(holdsNul)) {\n throw new QueryEvaluateError(\n 'a membership test was given text holding a NUL character, which SQL text cannot hold portably',\n )\n }\n if (isNull(value)) return 'unknown'\n if (among.some(each => each === value)) return true\n return among.some(isNull) ? 'unknown' : false\n }\n // Every operand is asked, with no short cut: SQL fixes no order, so one\n // that refuses its value (a NUL) refuses here whichever operand decided.\n case 'And': {\n const truths = node.operands.map(operand => holds(operand, scope))\n if (truths.includes(false)) return false\n return truths.includes('unknown') ? 'unknown' : true\n }\n case 'Or': {\n const truths = node.operands.map(operand => holds(operand, scope))\n if (truths.includes(true)) return true\n return truths.includes('unknown') ? 'unknown' : false\n }\n case 'Not': {\n const truth = holds(node.operand, scope)\n return truth === 'unknown' ? 'unknown' : !truth\n }\n case 'Compare': {\n const left = valueOf(node.left, scope)\n const right = valueOf(node.right, scope)\n const nul =\n 'a comparison was given text holding a NUL character, which SQL text cannot hold portably'\n refuseGivenNul(nul, [\n [node.left, left],\n [node.right, right],\n ])\n if (isNull(left) || isNull(right)) return 'unknown'\n if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul)\n // Numbers with numbers and text with text, as `orderBy` compares them,\n // so a comparison and an ordering never disagree about what is first.\n const kind = typeof left\n if (kind !== typeof right || (kind !== 'number' && kind !== 'string')) {\n throw new QueryEvaluateError('a comparison was given values that do not order together')\n }\n const order = compare(left, right, node.collation)\n return Match.value(node.operator).pipe(\n Match.when('lt', () => order < 0),\n Match.when('lte', () => order <= 0),\n Match.when('gt', () => order > 0),\n Match.when('gte', () => order >= 0),\n Match.exhaustive,\n )\n }\n }\n}\n\n/** What a predicate comes to: SQL's three values, of which a row is kept only on `true`. */\nexport type PredicateTruth = Truth\n\n/** Whether a predicate reads a field, asked once per node: nodes are frozen. */\nconst readsAField = new WeakMap<Predicate, boolean>()\n\n/**\n * A predicate's truth from the input alone, when it reads no field; none when\n * it reads one. An interpreter that runs per request decides such a predicate\n * before it builds anything: `isNull($status)` is known before any row is.\n * Refuses what `evaluate` refuses (text holding a NUL).\n */\nexport const decided = (\n node: Predicate,\n input: Row,\n operators: MemoryOperators = Operators.kernel,\n): Option.Option<PredicateTruth> => {\n let reads = readsAField.get(node)\n if (reads === undefined) {\n // A field after a write is a field too: nothing in the input alone decides it.\n const read = dependenciesOf(node)\n reads = read.fields.length + read.next.length > 0\n readsAField.set(node, reads)\n }\n return reads ? Option.none() : Option.some(holds(node, { row: {}, input, next: {}, operators }))\n}\n\n/** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */\nexport const truthOver = (\n node: Predicate,\n row: Row,\n input: Row = {},\n next: Row = {},\n operators: MemoryOperators = Operators.kernel,\n): PredicateTruth => holds(node, { row, input, next, operators })\n\n/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */\nconst matches = (body: AnyQuery, row: Row, input: Row, operators: MemoryOperators): boolean =>\n body.where.every(node => holds(node, { row, input, next: {}, operators }) === true)\n\n/** The kinds of value this interpreter orders by; every key of one term must share one. */\nconst comparable = new Set(['string', 'number', 'boolean'])\n\n/**\n * Text by code point, as SQLite's `BINARY` and Postgres's `\"C\"` compare it.\n * JavaScript's `<` compares UTF-16 code units, which puts a character past\n * U+FFFF (two units, the first from U+D800) before U+E000 to U+FFFF, where\n * every byte-ordered backend puts it after.\n */\nconst byCodePoint = (left: string, right: string): number => {\n let i = 0\n let j = 0\n while (i < left.length && j < right.length) {\n const a = left.codePointAt(i)!\n const b = right.codePointAt(j)!\n if (a !== b) return a < b ? -1 : 1\n i += a > 0xffff ? 2 : 1\n j += b > 0xffff ? 2 : 1\n }\n return i < left.length ? 1 : j < right.length ? -1 : 0\n}\n\n/** Two keys of one term, text by its collation (code point when none is declared). */\nconst compare = (left: unknown, right: unknown, collation: Option.Option<Collation>): number => {\n if (typeof left === 'string' && typeof right === 'string') {\n const fold = Option.exists(collation, declared => declared._tag === 'AsciiFold')\n return fold ? byCodePoint(foldAscii(left), foldAscii(right)) : byCodePoint(left, right)\n }\n if (typeof left === 'boolean' && typeof right === 'boolean') {\n return Number(left) - Number(right)\n }\n return (left as number) - (right as number)\n}\n\n/** What an order's keys are worked out with: a call may read the input, and runs by the table. */\ninterface OrderScope {\n readonly input: Row\n readonly operators: MemoryOperators\n}\n\n/** Each term's key for one row: a field's value, or what a call comes to over the row. */\nconst keysOf = (row: Row, terms: ReadonlyArray<OrderTerm>, scope: OrderScope) =>\n terms.map(term =>\n valueOf(term.expr, { row, input: scope.input, next: {}, operators: scope.operators }),\n )\n\n/**\n * Refuses an ordering this interpreter will not answer for, before sorting, so\n * the refusal names the first offending row in row order rather than whichever\n * pair the engine's sort happened to compare first. Every term is checked over\n * every row's keys: a key whose kind differs from the first present one's. A\n * null key is not refused; the term says where it goes.\n */\nconst checkOrder = (\n keys: ReadonlyArray<ReadonlyArray<unknown>>,\n terms: ReadonlyArray<OrderTerm>,\n query: string,\n) =>\n terms.forEach((term, index) => {\n if (term.expr._tag !== 'Field' && term.expr._tag !== 'Call') {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by something that is neither a field nor a call`,\n )\n }\n if (Option.exists(term.collation, declared => declared._tag === 'Locale')) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders ${Expr.show(term.expr)} by a backend's locale collation, which only that backend has`,\n )\n }\n let first: string | undefined\n for (const row of keys) {\n const value = row[index]\n if (isNull(value)) continue\n const kind = typeof value\n first ??= kind\n if (kind !== first || !comparable.has(kind)) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by values this interpreter cannot compare (${first} and ${kind})`,\n )\n }\n }\n })\n\n/** Two rows' keys by checked terms: negative when `left` sorts first. */\nconst byTerms = (\n terms: ReadonlyArray<OrderTerm>,\n left: ReadonlyArray<unknown>,\n right: ReadonlyArray<unknown>,\n): number => {\n for (const [index, term] of terms.entries()) {\n const absentLeft = isNull(left[index])\n const absentRight = isNull(right[index])\n // Where a row without a value goes is the term's to say, whichever the\n // direction; two such rows tie, for the next term.\n if (absentLeft || absentRight) {\n if (absentLeft && absentRight) continue\n return absentLeft === (term.nulls === 'first') ? -1 : 1\n }\n const sign = compare(left[index], right[index], term.collation)\n if (sign !== 0) return term.direction === 'asc' ? sign : -sign\n }\n return 0\n}\n\nconst ordered = (\n rows: ReadonlyArray<Row>,\n terms: ReadonlyArray<OrderTerm>,\n query: string,\n scope: OrderScope,\n) => {\n // Keys are worked out and checked however few the rows, so a term refused over\n // one row is refused as it is over many, as `evaluateEach` refuses it.\n if (terms.length === 0) return [...rows]\n // Each row's keys worked out once, not once per comparison: a call may be dear.\n const keyed = rows.map(row => ({ row, keys: keysOf(row, terms, scope) }))\n checkOrder(\n keyed.map(({ keys }) => keys),\n terms,\n query,\n )\n return keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row)\n}\n\n/**\n * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),\n * as `evaluate` sorts: negative when it comes first. A call among them runs\n * over each row with `input` and `operators` (the kernel's when not given).\n * Refuses what `evaluate` refuses, for these two rows: a term over neither a\n * field nor a call, a locale collation, keys of different kinds, or an\n * operator the table lacks. For a client placing one row among others it\n * holds.\n */\nexport const compareRows = (\n terms: ReadonlyArray<OrderTerm>,\n left: Row,\n right: Row,\n query: string,\n options: {\n readonly input?: Row | undefined\n readonly operators?: MemoryOperators | undefined\n } = {},\n): number => {\n const scope = { input: options.input ?? {}, operators: options.operators ?? Operators.kernel }\n const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)] as const\n checkOrder(keys, terms, query)\n return byTerms(terms, keys[0], keys[1])\n}\n\n/**\n * The operations this interpreter runs. It is the reference, so this is the\n * whole kernel — but it is declared rather than assumed, because an\n * interpreter that gains an operator and forgets to say so is exactly what\n * `Query.unsupported` exists to catch.\n */\nexport const supported: ReadonlyArray<Operation> = [\n 'eq',\n 'isNull',\n 'isNotNull',\n 'contains',\n 'in',\n 'and',\n 'or',\n 'not',\n 'compare',\n]\n\n/**\n * Refuses a body needing an operation this interpreter does not run, rather\n * than skipping it and answering a different question. Called by `evaluate`;\n * call it directly to check a body once instead of on every run.\n */\nexport const assertSupported = (\n body: AnyQuery,\n operators: MemoryOperators = Operators.kernel,\n): void => {\n const missing = Query.unsupported(body, supported, operators)\n if (missing.length > 0) {\n throw new QueryEvaluateError(\n `this interpreter does not run ${missing.join(', ')}, which query \"${body.entity.name}\" needs`,\n )\n }\n}\n\n/**\n * The rows the body matches, in the order it asks for. Pure: it reads the rows\n * it is given and nothing else.\n *\n * `input` holds the values this run was given, by the keys the body's\n * placeholders were built with — the same record the query would be called\n * with anywhere else.\n */\nexport const evaluate = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): ReadonlyArray<Row> => {\n const operators = options.operators ?? Operators.kernel\n assertSupported(body, operators)\n return ordered(\n rows.filter(row => matches(body, row, input, operators)),\n Query.orderFor(body, input),\n body.entity.name,\n { input, operators },\n )\n}\n\n/** What `evaluateEach` made of each row: those it matched, in order, and those it refused. */\nexport interface Evaluated {\n readonly matched: ReadonlyArray<Row>\n readonly refused: ReadonlyArray<Row>\n}\n\n/**\n * As `evaluate`, with each row judged alone: a row whose own values are\n * refused (text holding a NUL, a value an operator fails on) is set aside in\n * `refused` and the others are still answered. A client judging the rows it\n * holds wants this, since one bad stored row says nothing about the rest.\n *\n * What no single row causes still refuses the run: an operation or operator\n * the table lacks, an order by a locale collation, an input the body reads\n * holding a NUL (every row would refuse, and no row is the cause), and order\n * keys of different kinds across rows.\n */\nexport const evaluateEach = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): Evaluated => {\n const operators = options.operators ?? Operators.kernel\n assertSupported(body, operators)\n const terms = Query.orderFor(body, input)\n const scope = { input, operators }\n const keyed: Array<{ readonly row: Row; readonly keys: ReadonlyArray<unknown> }> = []\n const refused: Row[] = []\n for (const row of rows) {\n try {\n if (matches(body, row, input, operators)) keyed.push({ row, keys: keysOf(row, terms, scope) })\n } catch (error) {\n if (!(error instanceof QueryEvaluateError) || givenNul(body, terms, input)) throw error\n refused.push(row)\n }\n }\n checkOrder(\n keyed.map(({ keys }) => keys),\n terms,\n body.entity.name,\n )\n return {\n matched: keyed\n .sort((left, right) => byTerms(terms, left.keys, right.keys))\n .map(({ row }) => row),\n refused,\n }\n}\n\n/** Whether a constant or an input the body reads is text holding a NUL, or a list holding one. */\nconst givenNul = (body: AnyQuery, terms: ReadonlyArray<OrderTerm>, input: Row): boolean =>\n Expr.givesNul(...body.where, ...terms.map(term => term.expr)) ||\n Query.dependencies(body).inputs.some(key => {\n const value = input[key]\n return Array.isArray(value) ? value.some(holdsNul) : holdsNul(value)\n })\n","/**\n * Invariants: what every stored row of an Entity must hold, and what every\n * change of one must, declared once on the Entity through its metadata and read\n * from there by each interpreter: the reference judge here, a Schema check, a\n * form, a server's writer.\n *\n * One is built over the row before a write (`before`, each field as `Expr.field`) and\n * the row after it (`after`, each field as `Expr.next`). What it reads decides\n * when it is judged:\n *\n * ```text\n * reads `after` only -> a state invariant: every create and update, a CHECK constraint\n * reads `before` too -> a transition invariant: every update, which has a row before\n * ```\n *\n * It reads no input and no principal. Who may write is a guard's; whether a\n * write applies now is its `when`'s.\n */\nimport { Metadata } from 'foldkit-metadata'\nimport { Option, Schema, type SchemaAST } from 'effect'\nimport { OperatorMissingError, truthOver, type Row } from './evaluate.js'\nimport { Operators, type MemoryOperators } from './operators.js'\nimport { Expr, Query, type FieldExpr, type NextExpr, type Predicate, type Reads } from './expr.js'\n// A cycle with `index.ts`, safe because `Entity` is read only when an invariant is attached.\nimport {\n Entity,\n type AnyEntity,\n type EntityField,\n type EntityInput,\n type InputMember,\n} from './index.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\n\n/** One invariant of an Entity, as its interpreters read it. */\nexport interface Invariant {\n /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */\n readonly id: string\n readonly predicate: Predicate\n /** What someone the rules let write is told when a write would break it. */\n readonly message: string\n /** The fields a form shows the failure beside. */\n readonly path: ReadonlyArray<string>\n /** The fields it reads of the row before a write; none for a state invariant. */\n readonly before: ReadonlyArray<string>\n /** The fields it reads of the row after. */\n readonly after: ReadonlyArray<string>\n}\n\n/** Each field as the row before a write holds it: what an invariant reads as `before`. */\nexport type BeforeRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: FieldExpr<\n Schema.Schema.Type<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n}\n\n/** Each field as the row after a write holds it: what an invariant reads as `after`. */\nexport type AfterRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: NextExpr<\n Schema.Schema.Type<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n}\n\n/** A row, or a change from one row to another, as an invariant is judged over it. */\nexport interface Change {\n readonly after: Row\n /** The row before an update; none for a create, which judges no transition invariant. */\n readonly before?: Row\n}\n\nconst Invariants = Metadata.key<Invariant>('foldkit-entity/invariants', {\n // The same invariant reached twice (two annotated copies combined) is one.\n merge: values => [...new Set(values)],\n summarize: invariant => invariant.id,\n})\n\n/** What a row, or a change, comes to under an Entity's invariants. */\nexport type Judgement =\n | { readonly _tag: 'Valid' }\n | { readonly _tag: 'Invalid'; readonly failures: ReadonlyArray<Invariant> }\n /**\n * Validity is not known: some invariant reads a field the row does not have\n * (`fields`), or calls an operator the table does not run (`operators`, by name).\n */\n | {\n readonly _tag: 'Undecided'\n readonly fields: ReadonlyArray<string>\n readonly operators: ReadonlyArray<string>\n }\n\n/** Whether an invariant reads the row before, and so is judged only where there is one. */\nexport const readsBefore = (held: Invariant): boolean => held.before.length > 0\n\n/**\n * An invariant as declared: the step that attaches it to its Entity, carrying\n * its id, so a refusal is matched against the declaration rather than a\n * string spelled again (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`).\n */\nexport interface DeclaredInvariant<E extends AnyEntity> {\n (entity: E): E\n readonly id: string\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`)\n}\n\nexport const invariant = <E extends AnyEntity>(\n id: string,\n build: (rows: {\n readonly before: BeforeRow<E>\n readonly after: AfterRow<E>\n }) => Predicate & Reads<E['name']>,\n options: {\n readonly message: string\n readonly path?: ReadonlyArray<keyof E['fields'] & string>\n },\n): DeclaredInvariant<E> =>\n Object.assign(\n (entity: E): E => {\n if (id.length === 0) fail(entity, 'an invariant needs an id')\n if (invariantsOf(entity).some(held => held.id === id))\n fail(entity, `\"${id}\" is declared twice`)\n const fields = entity.fields as Readonly<Record<string, E['fields'][string]>>\n const after = Object.fromEntries(\n Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]),\n ) as unknown as AfterRow<E>\n const before = Object.fromEntries(\n Object.entries(fields).map(([key, field]) => [key, Expr.field(field)]),\n ) as unknown as BeforeRow<E>\n const predicate = build({ before, after }) as Predicate\n // `where` refuses a predicate over another Entity, which the type allows when it is unmarked.\n const body = Query.from(entity).pipe(Query.where(predicate))\n const dependencies = Query.dependencies(body)\n if (dependencies.inputs.length > 0) {\n fail(\n entity,\n `\"${id}\" reads the input ${dependencies.inputs.join(', ')}; it judges stored rows`,\n )\n }\n const beforeReads = dependencies.predicate.map(field => field.key)\n const afterReads = dependencies.next.map(field => field.key)\n // Reading the row before alone, it says which rows a write may start from: a write's `when`.\n // Judged as an invariant, a create would skip it and a repair would be refused by it.\n if (afterReads.length === 0) {\n fail(\n entity,\n `\"${id}\" reads no field of \\`after\\`; what a write may start from is its \\`when\\``,\n )\n }\n const path = options.path ?? [...new Set([...afterReads, ...beforeReads])]\n for (const key of path) {\n if (!Object.hasOwn(fields, key)) fail(entity, `\"${id}\"'s path names \"${key}\", not a field`)\n }\n return entity.pipe(\n Entity.annotate(\n Invariants.of(\n Object.freeze({\n id,\n predicate,\n message: options.message,\n path: Object.freeze([...path]),\n before: Object.freeze(beforeReads),\n after: Object.freeze(afterReads),\n }),\n ),\n ),\n ) as E\n },\n { id },\n )\n\nexport const invariantsOf = (entity: AnyEntity): ReadonlyArray<Invariant> =>\n Invariants.get(entity.metadata)\n\n/** `judge` with the invariants given, as a binding that keeps them holds them. */\nexport const judgeAgainst = (\n invariants: ReadonlyArray<Invariant>,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const missing = new Set<string>()\n const unrun = new Set<string>()\n const failures: Array<Invariant> = []\n const { after, before } = change\n for (const held of invariants) {\n // A create has no row before, so a transition invariant has nothing to judge.\n if (readsBefore(held) && before === undefined) continue\n const absent = [\n ...held.after.filter(key => !Object.hasOwn(after, key)),\n ...held.before.filter(key => !Object.hasOwn(before ?? {}, key)),\n ]\n if (absent.length > 0) absent.forEach(key => missing.add(key))\n else {\n try {\n if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) {\n failures.push(held)\n }\n } catch (error) {\n // An operator this table does not run is a judgement it cannot make, as a\n // field the row lacks is: a form passes it, and a server's checks refuse to\n // start without the operator (expr-operations-DESIGN §5.6).\n if (!(error instanceof OperatorMissingError)) throw error\n unrun.add(error.named)\n }\n }\n }\n if (failures.length > 0) return { _tag: 'Invalid', failures }\n if (missing.size > 0 || unrun.size > 0) {\n return { _tag: 'Undecided', fields: [...missing], operators: [...unrun] }\n }\n return { _tag: 'Valid' }\n}\n\n/**\n * A row, or a change, under every invariant (each row as the store holds it,\n * encoded): valid only when each is true. SQL's unknown, from a null, fails\n * one, as a `WHERE` drops the row; a field a row does not have leaves it\n * undecided, never valid. Without `before` (a create), transition invariants\n * are not judged.\n */\nexport const judge = (\n entity: AnyEntity,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => judgeAgainst(invariantsOf(entity), change, operators)\n\n/**\n * The row an input's value describes, judged under its Entity's state\n * invariants: each key mapped to a field, encoded as the store holds it. An\n * invariant over a field the input does not set (an `Option` holding nothing, a\n * key left out) is undecided, so a partial input is never called valid on its\n * account. It has no row before, so it judges no transition.\n */\nexport const judgeInput = (\n input: EntityInput<AnyEntity, any, any>,\n value: Readonly<Record<string, unknown>>,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const invariants = invariantsOf(input.entity)\n if (invariants.length === 0) return { _tag: 'Valid' }\n const members = input.members as Readonly<Record<string, InputMember>>\n const row: Record<string, unknown> = {}\n for (const [key, member] of Object.entries(members)) {\n if (member._tag !== 'Field' || !Object.hasOwn(value, key)) continue\n const encode = Schema.encodeUnknownOption(\n member.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n const given = value[key]\n const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given)\n // The value as the field holds it: itself for a field typed `Option`, else what it holds.\n // One the field cannot hold is no row the store would keep, so it decides nothing here.\n const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode))\n Option.map(\n Option.flatMap(held, () => stored),\n encoded => {\n row[member.key] = encoded\n },\n )\n }\n return judgeAgainst(invariants, { after: row }, operators)\n}\n\n/**\n * The Entity's state invariants as an Effect Schema check over its row type:\n * each failure at its path, with its message. The value is encoded first,\n * field by field, so it is judged as the store would hold it.\n */\nexport const check = <E extends AnyEntity>(\n entity: E,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): SchemaAST.Filter<Schema.Schema.Type<E['schema']>> =>\n Schema.makeFilter(value => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const decoded = value as Readonly<Record<string, unknown>>\n const row: Record<string, unknown> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (!Object.hasOwn(decoded, key)) continue\n row[key] = Schema.encodeUnknownSync(\n field.schema as unknown as Schema.Codec<unknown, unknown>,\n )(decoded[key])\n }\n const judged = judge(entity, { after: row }, options.operators)\n if (judged._tag !== 'Invalid') return undefined\n return judged.failures.flatMap((failure): ReadonlyArray<Schema.FilterIssue> =>\n failure.path.length === 0\n ? [failure.message]\n : failure.path.map(key => ({ path: [key], issue: failure.message })),\n )\n })\n","/**\n * The members a server filters an Entity's rows by under a rule the client\n * does not run, such as an authorization rule. A client that places rows in\n * a list judges membership by the list's body; a change to one of these\n * members can move a row into or out of what the server lists, which only\n * the server can say. Declared by whoever owns the rule (`foldkit-guard`\n * attaches it), read by whoever places (`foldkit-remote`).\n */\nimport { Metadata } from 'foldkit-metadata'\n\nconst key = Metadata.key<ReadonlyArray<string>>('foldkit-entity/read-filter', {\n // Every rule attached filters rows, so their members add up.\n merge: lists => [[...new Set(lists.flat())]],\n summarize: members => members.join(', '),\n})\n\nexport const ReadFilter = {\n /** Entity metadata: the rows the server lists depend on these members. */\n of: (members: ReadonlyArray<string>): Metadata => key.of(members),\n\n /** The members an Entity's metadata names, every attachment's together. */\n members: (metadata: Metadata): ReadonlyArray<string> => key.get(metadata)[0] ?? [],\n}\n","import { Option, Schema } from 'effect'\n\n/** What a schema says of itself to a person: its `title` and `description`. */\nexport interface SchemaWords {\n readonly title: Option.Option<string>\n readonly description: Option.Option<string>\n}\n\nconst text = (value: unknown): Option.Option<string> =>\n typeof value === 'string' ? Option.some(value) : Option.none()\n\nexport const Words = {\n /**\n * A schema's words, as a label and its help text. Under Effect 4 a checked\n * schema resolves to its last check's annotations, which say what the check\n * expects and carry no `title`, so a title given before the check is read from\n * the schema's own annotations. Read words through this, never through\n * `Schema.resolveAnnotations` directly.\n */\n of: (schema: Schema.Top): SchemaWords => {\n const resolved = Schema.resolveAnnotations(schema) ?? {}\n const own = schema.ast.annotations ?? {}\n return {\n title: Option.orElse(text(resolved.title), () => text(own['title'])),\n description: Option.orElse(text(resolved.description), () => text(own['description'])),\n }\n },\n}\n","/**\n * A write as a value: what an operation changes, declared over the input it\n * takes, so the changes can be known before it runs and its interpreters can\n * agree on what it means.\n *\n * A `Write` is built on `Entity.input`, which already says which input key is\n * which member of the Entity. `Write.update`, `Write.insert` and `Write.delete`\n * add what to do with them: the key that names the row, and optionally the key\n * holding the revision it was read at. Every other key mapped to a field is\n * set; a key mapped to `Entity.unmapped` is about the operation and is not\n * written.\n *\n * It is authority someone declared, never something derived from an Entity: an\n * Entity having a field does not mean anyone may set it.\n */\nimport { Data, Option, Schema, SchemaAST } from 'effect'\nimport type {\n AnyEntity,\n EntityField,\n EntityInput,\n EntityRef,\n EntityRelation,\n InputMember,\n} from './index.js'\nimport type { Collation } from './collation.js'\nimport { applyOperator } from './evaluate.js'\nimport {\n Expr,\n Query,\n dependenciesOf,\n isPredicate,\n type AnyExpr,\n type AnyQuery,\n type InputExpr,\n type Operandish,\n type Predicate,\n type Reads,\n} from './expr.js'\nimport type { BeforeRow } from './invariant.js'\nimport type { MemoryOperators } from './operators.js'\nimport { SchemaShape } from './shape.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\ntype OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/** One input key the write sets, and the field it sets. */\nexport interface WriteSet {\n readonly key: string\n readonly field: AnyField\n}\n\n/**\n * One input key holding an amount, and the field it moves. `integer` is whether\n * the amount's schema holds it to an integer (`Schema.isInt`): a writer over an\n * integer column refuses an increment without it, which the Entity cannot see.\n */\nexport interface WriteIncrement extends WriteSet {\n readonly integer: boolean\n}\n\n/**\n * One field the write computes (`label := concat(title, ' draft')`): an\n * expression over the row before the write and the input, every defined\n * operator in it expanded, so what is carried is primitive calls alone.\n */\nexport interface WriteAssignment {\n readonly field: AnyField\n readonly expr: AnyExpr\n}\n\n/**\n * A computed assignment as data, bound to one input: what travels to a server\n * and sits in a client's pending patch, which holds no descriptor and no\n * function. A field of the row before the write, a stored value, or a call of\n * a primitive operator by name (`id`, or `id@version`), with the collation it\n * compares text under (`null` for none: this is JSON).\n */\nexport type Computation = Data.TaggedEnum<{\n Field: { readonly key: string }\n Value: { readonly value: unknown }\n Call: {\n readonly operator: string\n readonly args: ReadonlyArray<Computation>\n readonly collation: Collation | null\n }\n}>\nexport const Computation = Data.taggedEnum<Computation>()\n\n/** One input key the write points at another row with: a `one` relation, by the target's id. */\nexport interface WriteLink {\n readonly key: string\n readonly relation: OneRelation\n}\n\n/**\n * One row of an Entity, by id, from an operation's input: updated, inserted\n * with an id the client chose, or deleted.\n */\nexport interface Write<E extends AnyEntity, Fields extends Schema.Struct.Fields> {\n readonly _tag: 'Update' | 'Insert' | 'Delete'\n readonly input: EntityInput<E, Fields, any>\n /** The input key holding the row's id, and the Entity's `id` field it is. */\n readonly id: WriteSet & { readonly key: keyof Fields & string }\n /**\n * The input key holding the revision the row was read at, and its field, when\n * the write is refused for a row that moved on since.\n */\n readonly expect: (WriteSet & { readonly key: keyof Fields & string }) | undefined\n /**\n * What the row must hold for the write to land, over the Entity, read\n * before the write and checked where it commits: an interpreter writes only\n * a row it holds of, and refuses the rest as unmet.\n */\n readonly when: Option.Option<AnyQuery>\n /** The keys it sets, in the input's order. */\n readonly sets: ReadonlyArray<WriteSet>\n /**\n * The fields it moves by an amount the input holds (`stock + quantity`),\n * computed where the write commits: the input key, and the field it moves.\n */\n readonly increments: ReadonlyArray<WriteIncrement>\n /** The fields it computes, each from the row before the write and the input. */\n readonly assignments: ReadonlyArray<WriteAssignment>\n /** The `one` relations it points elsewhere, in the input's order. */\n readonly links: ReadonlyArray<WriteLink>\n}\n\nexport type AnyWrite = Write<AnyEntity, any>\n\n/** A write declared with a precondition, so it may be refused as unmet. */\nexport type ConditionedWrite<E extends AnyEntity, Fields extends Schema.Struct.Fields> = Write<\n E,\n Fields\n> & { readonly when: Option.Some<AnyQuery> }\n\ninterface RowOptions<Fields extends Schema.Struct.Fields> {\n readonly id: keyof Fields & string\n readonly expect?: keyof Fields & string\n}\n\n/** The keys of `Fields` whose values are numbers. */\ntype NumberKeys<Fields> = {\n [K in keyof Fields & string]: Fields[K] extends Schema.Top\n ? Schema.Schema.Type<Fields[K]> extends number\n ? K\n : never\n : never\n}[keyof Fields & string]\n\n/** An update's increments: a number field of the Entity, by the input key holding the amount. */\nexport type WriteIncrements<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n readonly [\n K in NumberKeys<{ [F in keyof E['fields']]: E['fields'][F]['schema'] }>\n ]?: NumberKeys<Fields>\n}\n\n/**\n * An update's computed fields: each a field of the Entity, by what it comes\n * to over the row before the write (`row`, each field as `Expr.field`) and\n * the input. Its kind is checked against the field's where it is declared.\n */\nexport type WriteComputations<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n readonly [F in keyof E['fields'] & string]?: (context: {\n readonly row: BeforeRow<E>\n readonly input: {\n readonly [K in keyof Fields & string]: InputExpr<Schema.Schema.Type<Fields[K]>>\n }\n }) => AnyExpr\n}\n\n/** An update's options: a row's, what it moves by an amount, and what it computes. */\ntype UpdateOptions<\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n> = RowOptions<Fields> & {\n readonly increment?: WriteIncrements<E, Fields>\n readonly compute?: WriteComputations<E, Fields>\n}\n\n/** `update`: conditioned when given `when`, which the overloads tell apart. */\ninterface UpdateWrite {\n <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n input: EntityInput<E, Fields, any>,\n options: UpdateOptions<E, Fields> & { readonly when: WriteCondition<E, Fields> },\n ): ConditionedWrite<E, Fields>\n // `when?: undefined`, so an optional `when` in a variable cannot pick this one and lose `Unmet`.\n <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n input: EntityInput<E, Fields, any>,\n options: UpdateOptions<E, Fields> & { readonly when?: undefined },\n ): Write<E, Fields>\n}\n\n/** `delete`: conditioned when given `when`, as an update is. */\ninterface DeleteWrite {\n <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n input: EntityInput<E, Fields, any>,\n options: RowOptions<Fields> & { readonly when: WriteCondition<E, Fields> },\n ): ConditionedWrite<E, Fields>\n <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n input: EntityInput<E, Fields, any>,\n options: RowOptions<Fields> & { readonly when?: undefined },\n ): Write<E, Fields>\n}\n\n// `declared` sets `when` exactly when it is given, which is what the overloads say.\nconst update: UpdateWrite = (\n input: EntityInput<AnyEntity, any, any>,\n options: UpdateOptions<AnyEntity, any>,\n) => settingSomething(declared('Update', input, options)) as never\n\nconst remove: DeleteWrite = (input: EntityInput<AnyEntity, any, any>, options: RowOptions<any>) => {\n const write = declared('Delete', input, options)\n const named = [...write.sets, ...write.links][0]\n if (named !== undefined) fail(input, `a delete sets nothing, but \"${named.key}\" is mapped`)\n return write as never\n}\n\n/**\n * A write's precondition: a predicate over its Entity's row, given one\n * placeholder per input key, as a `Query.define` body is. It is built once,\n * so `input` stands for what the write will be given.\n */\nexport type WriteCondition<E extends AnyEntity, Fields extends Schema.Struct.Fields> = (context: {\n readonly input: {\n readonly [K in keyof Fields & string]: InputExpr<Schema.Schema.Type<Fields[K]>>\n }\n}) => Predicate & Reads<E['name']>\n\n/** One row's new values, in the store's wire shape: what a client patches and a server writes. */\nexport interface BoundWrite {\n readonly entity: string\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n /**\n * Each `one` relation it points, by the relation's key: the row it points at,\n * or none for an optional relation set to nothing. How a ref is carried (a\n * key on the wire, a foreign key in a table) is each interpreter's.\n */\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n /** Each field it moves, by the amount, encoded: added by the server, and predicted over what a client holds. */\n readonly increments: Readonly<Record<string, number>>\n /** Each field it computes, as data: run by the server where it writes, predicted by a client. */\n readonly assignments: Readonly<Record<string, Computation>>\n}\n\nconst fail = (input: EntityInput<AnyEntity, any, any>, message: string): never => {\n throw new Error(`[foldkit-entity] Write of ${input.entity.name}: ${message}`)\n}\n\nconst membersOf = (\n input: EntityInput<AnyEntity, any, any>,\n): Readonly<Record<string, InputMember | undefined>> => input.members\n\n/** A field's value as the store holds it. A field's schema needs no service, so none is asked. */\nconst encoded = (field: AnyField, value: unknown): unknown =>\n Schema.encodeUnknownSync(field.schema as unknown as Schema.Codec<unknown, unknown>)(value)\n\n/**\n * A key's value as given, when it was: an absent key, and an `Option` that\n * holds nothing, give none, and a `Some` what it holds. What `Entity.input`\n * lets a key map itself to, a write can bind.\n */\nconst given = (value: unknown): Option.Option<unknown> => {\n if (value === undefined) return Option.none()\n return Option.isOption(value) ? value : Option.some(value)\n}\n\nconst fieldAt = (input: EntityInput<AnyEntity, any, any>, key: string, role: string): AnyField => {\n const member = membersOf(input)[key]\n if (member === undefined) return fail(input, `${role} \"${key}\" is not a key of the input`)\n if (member._tag !== 'Field') return fail(input, `${role} \"${key}\" is not mapped to a field`)\n return member\n}\n\n/**\n * What every kind shares: the key naming the row, the expected revision, and\n * what the other keys set or point. A kind adds its own checks.\n */\nconst declared = <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n kind: Write<E, Fields>['_tag'],\n input: EntityInput<E, Fields, any>,\n options: {\n readonly id: keyof Fields & string\n readonly expect?: keyof Fields & string\n readonly when?: WriteCondition<E, Fields> | undefined\n readonly increment?: Readonly<Record<string, string | undefined>>\n readonly compute?: WriteComputations<E, Fields> | undefined\n },\n): Write<E, Fields> => {\n const id = fieldAt(input, options.id, 'id')\n if (id.key !== 'id') fail(input, `id \"${options.id}\" is mapped to \"${id.key}\", not to \"id\"`)\n const idSchema = input.schema.fields[options.id] as unknown as Schema.Top\n const takes = Schema.is(Schema.toType(idSchema) as Schema.Codec<unknown>)\n if (SchemaAST.isOptional(idSchema.ast) || takes(undefined) || takes(Option.none()))\n fail(input, `id \"${options.id}\" may be absent, and a declared write names its row`)\n if (options.expect === options.id) fail(input, 'expect cannot be the id')\n const expect =\n options.expect === undefined\n ? undefined\n : Object.freeze({ key: options.expect, field: fieldAt(input, options.expect, 'expect') })\n const sets: Array<WriteSet> = []\n const links: Array<WriteLink> = []\n for (const [key, member] of Object.entries(membersOf(input))) {\n if (member === undefined || key === options.id || key === options.expect) continue\n switch (member._tag) {\n case 'Field':\n sets.push(Object.freeze({ key, field: member }))\n break\n case 'Unmapped':\n break\n case 'RelationInput':\n if (member.relation.cardinality !== 'one') {\n fail(input, `\"${key}\" is a many relation; a write points one relation at a time`)\n }\n links.push(Object.freeze({ key, relation: member.relation as OneRelation }))\n break\n case 'NestedInput':\n fail(input, `\"${key}\" writes a nested row; a write writes its own row only`)\n }\n }\n const placeholders: Record<string, InputExpr<unknown>> = Object.create(null)\n for (const [key, schema] of Object.entries(input.schema.fields)) {\n placeholders[key] = Expr.input(key, schema as unknown as Schema.Codec<unknown, unknown>)\n }\n const when = Option.map(Option.fromUndefinedOr(options.when), condition => {\n // `where` refuses a predicate over another Entity, which the type allows when it is unmarked.\n return Query.from(input.entity).pipe(\n Query.where(condition({ input: placeholders as never }) as Predicate),\n ) as AnyQuery\n })\n const increments = Object.entries(options.increment ?? {}).flatMap(([fieldKey, key]) =>\n key === undefined ? [] : [incrementOf(input, fieldKey, key, { expect, sets })],\n )\n const fields = input.entity.fields as Readonly<Record<string, E['fields'][string]>>\n const row = Object.fromEntries(\n Object.entries(fields).map(([key, field]) => [key, Expr.field(field)]),\n ) as unknown as BeforeRow<E>\n const computes: ReadonlyArray<\n readonly [string, WriteComputations<E, Fields>[keyof E['fields'] & string]]\n > = Object.entries(options.compute ?? {})\n const assignments = computes.flatMap(([fieldKey, compute]) =>\n compute === undefined\n ? []\n : [\n assignmentOf(input, fieldKey, () => compute({ row, input: placeholders as never }), {\n expect,\n sets,\n increments,\n }),\n ],\n )\n return Object.freeze({\n _tag: kind,\n input,\n id: Object.freeze({ key: options.id, field: id }),\n expect,\n when,\n sets: Object.freeze(sets),\n increments: Object.freeze(increments),\n assignments: Object.freeze(assignments),\n links: Object.freeze(links),\n })\n}\n\n/** The kind of one stored form, as far as an assignment must agree with its field. */\nconst storedKind = (ast: SchemaAST.AST): string => {\n if (SchemaAST.isNull(ast)) return 'null'\n const literal = SchemaAST.isLiteral(ast) ? typeof ast.literal : undefined\n if (SchemaAST.isNumber(ast) || literal === 'number') return 'number'\n if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || literal === 'string') {\n return 'text'\n }\n if (SchemaAST.isBoolean(ast) || literal === 'boolean') return 'boolean'\n return 'other'\n}\n\n/** Every kind a stored form may hold: a union's members' kinds. */\nconst storedKinds = (ast: SchemaAST.AST): ReadonlySet<string> =>\n new Set(\n SchemaAST.isUnion(ast)\n ? ast.types.flatMap(member => [...storedKinds(member)])\n : [storedKind(ast)],\n )\n\n/** The stored kinds a scalar may come to, by what it is. */\nconst kindsOf = (expr: AnyExpr): ReadonlySet<string> => {\n switch (expr._tag) {\n case 'Field':\n return storedKinds(Schema.toEncoded(expr.schema).ast)\n case 'Next':\n return storedKinds(Schema.toEncoded(expr.field.schema).ast)\n case 'Input':\n return storedKinds(Schema.toEncoded(expr.schema).ast)\n case 'Literal':\n return new Set([\n expr.value === null ? 'null' : typeof expr.value === 'string' ? 'text' : typeof expr.value,\n ])\n case 'Call':\n return storedKinds(Schema.toEncoded(expr.operator.output).ast)\n }\n}\n\n/**\n * Whether `expr` may come to null: a nullable field or input, a null literal,\n * an operator answering one, or a strict operator given an argument that may\n * be null, which it answers with null.\n */\nconst mayBeNull = (expr: AnyExpr): boolean =>\n kindsOf(expr).has('null') ||\n (expr._tag === 'Call' &&\n expr.operator.nulls === 'strict' &&\n expr.args.some(arg => !isPredicate(arg) && mayBeNull(arg)))\n\n/** Whether a predicate is anywhere in `expr`, which data carries only as a value. */\nconst holdsPredicate = (expr: Operandish): boolean =>\n isPredicate(expr) || (expr._tag === 'Call' && expr.args.some(holdsPredicate))\n\n/**\n * One computed field, checked: a field of the Entity written by nothing else,\n * computed from this Entity's row before the write and the input alone\n * (never `Next`, so assignments do not depend on each other), to a value of\n * the field's stored kind, with no predicate in it.\n */\nconst assignmentOf = (\n input: EntityInput<AnyEntity, any, any>,\n fieldKey: string,\n compute: () => AnyExpr,\n declared: {\n readonly expect: WriteSet | undefined\n readonly sets: ReadonlyArray<WriteSet>\n readonly increments: ReadonlyArray<WriteIncrement>\n },\n): WriteAssignment => {\n const fields = input.entity.fields as Readonly<Record<string, AnyField>>\n const field = Object.hasOwn(fields, fieldKey) ? fields[fieldKey] : undefined\n if (field === undefined) return fail(input, `computes \"${fieldKey}\", which is not a field`)\n if (fieldKey === 'id') return fail(input, 'computes the id')\n if (declared.expect?.field.key === fieldKey) {\n return fail(input, `computes \"${fieldKey}\", the revision it expects`)\n }\n if (\n declared.sets.some(set => set.field.key === fieldKey) ||\n declared.increments.some(increment => increment.field.key === fieldKey)\n ) {\n return fail(input, `computes \"${fieldKey}\", which the write also sets`)\n }\n const operand: Operandish = compute()\n const expr = isPredicate(operand) ? operand : Expr.expanded(operand)\n if (isPredicate(expr) || holdsPredicate(expr)) {\n return fail(\n input,\n `computes \"${fieldKey}\" with a predicate, which an assignment carries only as a value`,\n )\n }\n const reads = dependenciesOf(expr)\n if (reads.next.length > 0) {\n return fail(\n input,\n `computes \"${fieldKey}\" from the row after the write, which an assignment never reads`,\n )\n }\n const stranger = reads.fields.find(read => read.owner.name !== input.entity.name)\n if (stranger !== undefined) {\n return fail(\n input,\n `computes \"${fieldKey}\" from ${stranger.owner.name}.${stranger.key}, another Entity's field`,\n )\n }\n const stored = storedKinds(Schema.toEncoded(field.schema as unknown as Schema.Top).ast)\n const comes = [...kindsOf(expr)].filter(kind => kind !== 'null' && !stored.has(kind))\n if (comes.length > 0) {\n return fail(input, `computes \"${fieldKey}\" as ${comes.join(' or ')}, which it does not store`)\n }\n // Memory would show the null, and the database refuse it as NOT NULL.\n if (!stored.has('null') && mayBeNull(expr)) {\n return fail(input, `computes \"${fieldKey}\" as possibly null, which it does not store`)\n }\n return Object.freeze({ field, expr })\n}\n\n/** An assignment's expression, bound to one input, as data. */\nconst computationOf = (\n write: AnyWrite,\n expr: AnyExpr,\n input: Readonly<Record<string, unknown>>,\n): Computation => {\n switch (expr._tag) {\n // `Next` is refused where an assignment is declared.\n case 'Field':\n case 'Next':\n return Computation.Field({ key: expr._tag === 'Field' ? expr.key : expr.field.key })\n case 'Literal':\n return Computation.Value({ value: expr.value })\n case 'Input':\n return Computation.Value({\n value: Schema.encodeUnknownSync(\n write.input.schema.fields[expr.key] as unknown as Schema.Codec<unknown, unknown>,\n )(input[expr.key]),\n })\n case 'Call':\n return Computation.Call({\n operator:\n expr.operator.version === 1\n ? expr.operator.id\n : `${expr.operator.id}@${expr.operator.version}`,\n args: expr.args.map(arg => computationOf(write, arg as AnyExpr, input)),\n collation: Option.getOrNull(expr.collation),\n })\n }\n}\n\n/**\n * What a computation comes to over `row`, the row before the write: none when\n * the row lacks a field it reads, or `operators` lacks an operator it calls.\n */\nconst computed = (\n computation: Computation,\n row: Readonly<Record<string, unknown>>,\n operators: MemoryOperators,\n): Option.Option<unknown> =>\n Computation.$match(computation, {\n Field: ({ key }) => (Object.hasOwn(row, key) ? Option.some(row[key]) : Option.none()),\n Value: ({ value }) => Option.some(value),\n Call: ({ operator, args, collation }) =>\n Option.flatMap(operators.named(operator), descriptor =>\n Option.map(Option.all(args.map(arg => computed(arg, row, operators))), values =>\n applyOperator(descriptor, values, {\n collation: Option.fromNullOr(collation),\n operators,\n }),\n ),\n ),\n })\n\n/** Whether a value's stored form is a plain number. */\nconst storedAsNumber = (schema: Schema.Top): boolean =>\n SchemaAST.isNumber(Schema.toEncoded(schema).ast)\n\n/** Whether a value's stored form is checked to be an integer. */\nconst storedAsInteger = (schema: Schema.Top): boolean =>\n SchemaShape.holdsIntegers(Schema.toEncoded(schema).ast)\n\n/**\n * One increment, checked: a field of the Entity stored as a number, written\n * by nothing else, moved by an unmapped input key whose value is a number, and\n * an integer when the field is one.\n */\nconst incrementOf = (\n input: EntityInput<AnyEntity, any, any>,\n fieldKey: string,\n key: string,\n declared: { readonly expect: WriteSet | undefined; readonly sets: ReadonlyArray<WriteSet> },\n): WriteIncrement => {\n const fields = input.entity.fields as Readonly<Record<string, AnyField>>\n const field = Object.hasOwn(fields, fieldKey) ? fields[fieldKey] : undefined\n if (field === undefined) return fail(input, `increments \"${fieldKey}\", which is not a field`)\n if (fieldKey === 'id') return fail(input, 'increments the id')\n if (declared.expect?.field.key === fieldKey) {\n return fail(input, `increments \"${fieldKey}\", the revision it expects`)\n }\n if (declared.sets.some(set => set.field.key === fieldKey)) {\n return fail(input, `increments \"${fieldKey}\", which a key also sets`)\n }\n if (!storedAsNumber(field.schema as unknown as Schema.Top)) {\n return fail(input, `increments \"${fieldKey}\", which is not stored as a number`)\n }\n const member = membersOf(input)[key]\n if (member === undefined) return fail(input, `\"${key}\" is not a key of the input`)\n if (member._tag !== 'Unmapped') {\n return fail(input, `\"${key}\" is an amount, so it must be unmapped, not written as a member`)\n }\n const amount = input.schema.fields[key] as unknown as Schema.Top\n if (!storedAsNumber(amount)) return fail(input, `\"${key}\" is an amount, but not a number`)\n // The databases split over a fraction added to an integer: Postgres refuses the\n // statement, SQLite stores it in the integer column. So it never reaches either.\n const integer = storedAsInteger(amount)\n if (storedAsInteger(field.schema as unknown as Schema.Top) && !integer) {\n return fail(\n input,\n `\"${key}\" may not be an integer, but \"${fieldKey}\" is one; give the amount Schema.Int`,\n )\n }\n return Object.freeze({ key, field, integer })\n}\n\n/** An update or an insert that would write nothing is refused where it is declared. */\nconst settingSomething = <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n write: Write<E, Fields>,\n): Write<E, Fields> =>\n write.sets.length === 0 &&\n write.links.length === 0 &&\n write.increments.length === 0 &&\n write.assignments.length === 0\n ? fail(write.input, 'it sets no field')\n : write\n\nexport const Write = {\n /**\n * Sets, on the row whose id is the input's `id` key, every field the input\n * maps a key to. `expect` names the key holding the revision the row was\n * read at: an interpreter writes only a row still at that revision.\n *\n * ```ts\n * const EditPost = Write.update(EditPostInput, { id: 'id' })\n * ```\n *\n * A key mapped to a `one` relation (`Relation.input`) points the row at the\n * id it holds. Refused where it is written: an `id` that is not the Entity's\n * `id` field, a `many` relation or a nested key (not written by an update\n * yet), or nothing to set.\n *\n * `when` is what the row must hold for the update to land, checked where it\n * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it\n * does not hold of is refused as unmet.\n *\n * `compute` sets a field to what an expression comes to over the row before\n * the write and the input, run where it commits\n * (`{ label: ({ row }) => concat(row.title, ' draft') }`). It is refused for\n * a field another key writes, an expression over the row after the write or\n * another Entity, or one of a kind the field does not store.\n */\n update,\n\n /**\n * Inserts the row whose id is the input's `id` key, an id the client chose,\n * with every field and `one` relation the input maps a key to. An insert\n * expects no revision: there is no row to have read. A row already there\n * under that id (a retry) is left as it is.\n */\n insert: <E extends AnyEntity, Fields extends Schema.Struct.Fields>(\n input: EntityInput<E, Fields, any>,\n options: { readonly id: keyof Fields & string },\n ): Write<E, Fields> => {\n return settingSomething(declared('Insert', input, options))\n },\n\n /**\n * Deletes the row whose id is the input's `id` key, only while it is still at\n * the revision `expect` names, when it names one. It sets nothing, so a key\n * mapped to a member is refused where it is written. A row already gone (a\n * retry) is gone. `when`, as an update's, is what the row must hold.\n */\n delete: remove,\n\n /**\n * The revision this input says the row was read at, encoded, with its field:\n * what an interpreter writes only a row still at. None for a write that\n * expects none.\n */\n expected: <Fields extends Schema.Struct.Fields>(\n write: Write<AnyEntity, Fields>,\n value: Schema.Struct.Type<Fields>,\n ): Option.Option<{ readonly field: string; readonly revision: unknown }> =>\n Option.map(Option.fromUndefinedOr(write.expect), ({ key, field }) => ({\n field: field.key,\n revision: encoded(field, (value as Readonly<Record<string, unknown>>)[key]),\n })),\n\n /** The members any invocation may write: what a query reading none of them cannot be changed by. */\n writes: (write: AnyWrite): ReadonlyArray<AnyField | OneRelation> => [\n ...write.sets.map(set => set.field),\n ...write.increments.map(increment => increment.field),\n ...write.assignments.map(assignment => assignment.field),\n ...write.links.map(link => link.relation),\n ],\n\n /**\n * The fields a write reads from the row it writes: those its `when` reads,\n * each it increments, each its assignments read, and the revision it\n * expects. What an interpreter must read, and what a startup check judges\n * it could disclose.\n */\n reads: (write: AnyWrite): ReadonlyArray<AnyField> => {\n const fields = new Map<string, AnyField>()\n const add = (field: AnyField) => fields.set(field.key, field)\n Option.map(write.when, body =>\n Query.dependencies(body).predicate.forEach(field => add(field as unknown as AnyField)),\n )\n write.increments.forEach(increment => add(increment.field))\n write.assignments.forEach(assignment =>\n dependenciesOf(assignment.expr).fields.forEach(field => add(field as unknown as AnyField)),\n )\n if (write.expect !== undefined) add(write.expect.field)\n return [...fields.values()]\n },\n\n /**\n * The row this input writes and its new values, encoded as the store holds\n * them: the patch a client shows before the server answers. `keys`, when\n * given, narrows it to those input keys (what an author changed); the rest of\n * the input is still the whole, validated value.\n */\n bind: <Fields extends Schema.Struct.Fields>(\n write: Write<AnyEntity, Fields>,\n value: Schema.Struct.Type<Fields>,\n keys?: ReadonlyArray<string>,\n ): BoundWrite => {\n const input = value as Readonly<Record<string, unknown>>\n const wanted = keys === undefined ? undefined : new Set(keys)\n const asked = (key: string) => wanted === undefined || wanted.has(key)\n const values: Record<string, unknown> = {}\n for (const { key, field } of write.sets) {\n if (!asked(key)) continue\n // A key the input leaves out, or an `Option` holding nothing, writes nothing.\n Option.map(given(input[key]), held => {\n values[field.key] = encoded(field, held)\n })\n }\n const links: Record<string, Option.Option<EntityRef>> = {}\n for (const { key, relation } of write.links) {\n if (!asked(key)) continue\n const target = relation.target()\n links[relation.key] = Option.map(\n Option.flatMap(given(input[key]), Option.fromNullishOr),\n id => ({ entity: target.name, id: String(encoded(target.fields.id as AnyField, id)) }),\n )\n }\n const increments: Record<string, number> = {}\n for (const { key, field } of write.increments) {\n // `keys` names input keys, so an increment is asked for by its amount's key.\n if (!asked(key)) continue\n const schema = write.input.schema.fields[key] as unknown as Schema.Codec<unknown, number>\n Option.map(given(input[key]), held => {\n increments[field.key] = Schema.encodeUnknownSync(schema)(held)\n })\n }\n // Every assignment: it reads the row as well as the input, so no key alone asks for it.\n const assignments: Record<string, Computation> = {}\n for (const { field, expr } of write.assignments) {\n assignments[field.key] = computationOf(write, expr, input)\n }\n return {\n entity: write.input.entity.name,\n id: String(encoded(write.id.field, input[write.id.key])),\n values,\n links,\n increments,\n assignments,\n }\n },\n\n /**\n * The fields of the row before it that a bound write's amounts and\n * assignments read: what to read to work out the row it leaves.\n */\n boundReads: (bound: Pick<BoundWrite, 'increments' | 'assignments'>): ReadonlyArray<string> => {\n const keys = new Set(Object.keys(bound.increments))\n const walk = (computation: Computation): void =>\n Computation.$match(computation, {\n Field: ({ key }) => void keys.add(key),\n Value: () => undefined,\n Call: ({ args }) => args.forEach(walk),\n })\n Object.values(bound.assignments).forEach(walk)\n return [...keys]\n },\n\n /**\n * The row a bound write leaves over `row`, the row before it: its values\n * set, each amount added (a null stays null, as in SQL), and each\n * assignment computed by `operators` over the row before. `unknown` names\n * each field it could not work out: one `row` lacks, or holds as no number\n * for an amount, or an assignment calling an operator the table lacks. That\n * field keeps what `row` holds. The one computation of this row: a guard\n * judges it, a writer explains a miss with it, a client predicts it.\n */\n apply: (\n row: Readonly<Record<string, unknown>>,\n bound: Pick<BoundWrite, 'values' | 'increments' | 'assignments'>,\n options: { readonly operators: MemoryOperators },\n ): {\n readonly row: Readonly<Record<string, unknown>>\n readonly unknown: ReadonlyArray<string>\n } => {\n const after: Record<string, unknown> = { ...row, ...bound.values }\n const unknown: Array<string> = []\n for (const [field, amount] of Object.entries(bound.increments)) {\n const held = Object.hasOwn(row, field) ? row[field] : undefined\n if (held === null) after[field] = null\n else if (typeof held === 'number') after[field] = held + amount\n else unknown.push(field)\n }\n for (const [field, computation] of Object.entries(bound.assignments)) {\n Option.match(computed(computation, row, options.operators), {\n onNone: () => unknown.push(field),\n onSome: value => {\n after[field] = value\n },\n })\n }\n return { row: after, unknown }\n },\n}\n","/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { type Option, Pipeable, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\nimport {\n check,\n invariant,\n invariantsOf,\n judge,\n judgeAgainst,\n judgeInput,\n readsBefore,\n} from './invariant.js'\nimport { SchemaShape } from './shape.js'\n\nexport const EntityTypeId: unique symbol = Symbol.for('foldkit-entity/Entity')\nexport type EntityTypeId = typeof EntityTypeId\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n readonly metadata: Metadata\n}\n\n/** What `Derived.make` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint> {\n readonly schema: S\n}\n\n/**\n * A value consumers may read that is not part of `entity.schema`. It says\n * nothing about how the value is computed; an interpreter supplies it.\n */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<Name, K, Derived[K]['schema']>\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/** Unsatisfiable when a new key is already a member, so the pipe step is the error site. */\ntype Free<E extends AnyEntity, New> = keyof New & keyof E['members'] extends never\n ? unknown\n : { readonly alreadyAMember: keyof New & keyof E['members'] }\n\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\n : never\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/** Marks a relation key that is already a member of its owner, or an owner that is not listed. */\ntype CheckRelations<Es extends Entities, Rs> = {\n readonly [K in keyof Rs]: K extends keyof Es\n ? {\n readonly [R in keyof Rs[K]]: R extends keyof Es[K]['members']\n ? `\"${R & string}\" is already a member of ${Es[K]['name']}`\n : Rs[K][R]\n }\n : 'not one of the entities being related'\n}\n\nexport const SelectionTypeId: unique symbol = Symbol.for('foldkit-entity/Selection')\nexport type SelectionTypeId = typeof SelectionTypeId\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\ntype RefSchema<Target extends AnyEntity> = Schema.Struct<{\n readonly entity: Schema.Literal<Target['name']>\n readonly id: IdSchemaOf<Target>\n}>\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\n\n/** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */\nexport type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type']\n\n/** `true` for any member; a relation also takes a Selection of its target. */\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\nexport const SelectionPageTypeId: unique symbol = Symbol.for('foldkit-entity/SelectionPage')\nexport type SelectionPageTypeId = typeof SelectionPageTypeId\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\ntype PageSchema<S extends Schema.Constraint> = Schema.Struct<{\n readonly items: Schema.$Array<S>\n readonly hasNext: Schema.Boolean\n readonly hasPrevious: Schema.Boolean\n}>\n\ntype SelectionSpec<E extends AnyEntity, Spec> = {\n readonly [K in keyof Spec]: K extends keyof E['relations']\n ? E['relations'][K] extends EntityRelation<any, any, infer Target, infer C, any>\n ?\n | true\n | AnySelection<Target['name']>\n // Only a `many` relation has pages.\n | (C extends 'many' ? SelectionPage<Target['name'], any> : never)\n : never\n : K extends keyof E['members']\n ? true\n : `\"${K & string}\" is not a member of ${E['name']}`\n}\n\ntype RelationShape<\n C extends Cardinality,\n Optional extends boolean,\n S extends Schema.Constraint,\n> = C extends 'many' ? Schema.$Array<S> : Optional extends true ? Schema.NullOr<S> : S\n\ntype SelectedSchema<Member, Selected> = Member extends\n | EntityField<any, any, infer S>\n | EntityDerived<any, any, infer S>\n ? S\n : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? Selected extends SelectionPage<any, infer S>\n ? PageSchema<S>\n : RelationShape<\n C,\n Optional,\n Selected extends Selection<any, any, infer S> ? S : RefSchema<Target>\n >\n : never\n\ntype SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>\n}>\n\n/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */\nconst idSchemaOf = (entity: AnyEntity): Schema.Top => {\n const fields: Readonly<Record<string, EntityMember | undefined>> = entity.fields\n const id = fields.id\n if (id === undefined || id._tag !== 'Field') return Schema.String\n const type = Schema.toType(id.schema as Schema.Top)\n return SchemaShape.isText(type.ast) ? type : Schema.String\n}\n\nconst isSelectionPage = (value: unknown): value is SelectionPage<string, Schema.Constraint> =>\n typeof value === 'object' && value !== null && SelectionPageTypeId in value\n\nconst isSelection = (value: unknown): value is AnySelection =>\n typeof value === 'object' && value !== null && SelectionTypeId in value\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/** The ids a relation takes as input: one id, a nullable id, or a list of ids. */\ntype RelationIds<R> =\n R extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? C extends 'many'\n ? ReadonlyArray<IdOf<Target>>\n : Optional extends true\n ? IdOf<Target> | null\n : IdOf<Target>\n : never\n\n/** What a nested input takes: the value of the target's input, or a list of them for a `many`. */\ntype NestedValues<R, I> =\n I extends EntityInput<any, infer Fields, any>\n ? R extends EntityRelation<any, any, any, 'many', any>\n ? ReadonlyArray<Schema.Struct.Type<Fields>>\n : Schema.Struct.Type<Fields>\n : never\n\ntype Present<T> = Exclude<T, null | undefined>\n/** What an `Option` holds, else the value itself. */\ntype Held<T> =\n T extends Option.Some<infer A> ? Present<A> : T extends Option.None<any> ? never : Present<T>\n/**\n * Whether an input value fits a field. Only the value that is present has to\n * fit: an input may leave a key out (a partial update), send `null` to clear\n * it, or hold an `Option` (an id absent for something new), whose value fits as\n * it is (an `Option` field) or as what it holds. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Fits<Input, Field> = [Present<Input>] extends [Field]\n ? true\n : [Held<Input>] extends [Field]\n ? true\n : false\n\ntype MappingFor<Name extends string, Input, M> = M extends Unmapped\n ? M\n : M extends\n | EntityField<infer Owner, any, any>\n | RelationInput<EntityRelation<infer Owner, any, any, any, any>>\n | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any>\n ? [Owner] extends [Name]\n ? M extends EntityField<any, any, infer S>\n ? Fits<Input, Schema.Schema.Type<S>> extends true\n ? M\n : 'the input value does not fit this field'\n : M extends RelationInput<infer R>\n ? Present<Input> extends RelationIds<R>\n ? M\n : 'the input value is not the id shape of this relation'\n : M extends NestedInput<infer R, infer I>\n ? R extends EntityRelation<any, any, infer Target, any, any>\n ? I extends EntityInput<infer Of, any, any>\n ? [Of['name']] extends [Target['name']]\n ? Present<Input> extends NestedValues<R, I>\n ? M\n : 'the input value is not the value of the nested input'\n : `the nested input is of ${Of['name']}, not ${Target['name']}`\n : never\n : never\n : never\n : `this member belongs to ${Owner}`\n : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped'\n\n/** A key that names a field whose value it fits maps itself; every other key needs an entry. */\ntype SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n [K in keyof Fields]: K extends keyof E['fields']\n ? Fits<Schema.Schema.Type<Fields[K]>, Schema.Schema.Type<E['fields'][K]['schema']>> extends true\n ? K\n : never\n : never\n}[keyof Fields]\n\n/**\n * A mapping written as a member's key: `'title'` is that Field, and `'author'` is\n * `Relation.input` of that relation. Nothing is inferred from the input key's own\n * name; the member is still named, only more briefly.\n */\ntype Named<E extends AnyEntity, M> = M extends string\n ? M extends keyof E['fields']\n ? E['fields'][M]\n : M extends keyof E['relations']\n ? RelationInput<E['relations'][M]>\n : `\"${M}\" names no field or relation of ${E['name']}`\n : M\n\ntype InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown\n} & {\n readonly [K in keyof Mapping]: K extends keyof Fields\n ? Named<E, Mapping[K]> extends infer Member\n ? Member extends string\n ? Member\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> extends Member\n ? Mapping[K]\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member>\n : never\n : `\"${K & string}\" is not a key of the input`\n}\n\ntype InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in keyof Fields]: K extends keyof Mapping\n ? Named<E, Mapping[K]>\n : K extends keyof E['fields']\n ? E['fields'][K]\n : never\n}\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\n/** The Entity member an input key writes, by its key; nothing for an unmapped key. */\nexport type WrittenKey<M> =\n M extends EntityField<any, infer Key, any>\n ? Key\n : M extends\n | RelationInput<EntityRelation<any, infer Key, any, any, any>>\n | NestedInput<EntityRelation<any, infer Key, any, any, any>, any>\n ? Key\n : never\n\n/** A nested input reads what it writes of the target; every other member reads as it is. */\nexport type WrittenAs<M> =\n M extends NestedInput<any, EntityInput<infer Of, any, infer Members>>\n ? Selection<Of['name'], WrittenSpec<Members>, SelectionSchema<Of, WrittenSpec<Members>>>\n : true\n\n/** Every member the input writes: what to read to show the input's current values. */\nexport type WrittenSpec<Members> = {\n readonly [K in keyof Members as WrittenKey<Members[K]>]: WrittenAs<Members[K]>\n}\n\nconst unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\ninterface Parts {\n readonly identity: EntityIdentity<string>\n readonly schema: Schema.Struct<Schema.Struct.Fields>\n readonly fields: Readonly<Record<string, EntityMember>>\n readonly relations: Readonly<Record<string, EntityMember>>\n readonly derived: Readonly<Record<string, EntityMember>>\n readonly metadata: Metadata\n}\n\nconst EntityProto = {\n [EntityTypeId]: EntityTypeId,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst make = (parts: Parts): AnyEntity =>\n Object.freeze(\n Object.assign(Object.create(EntityProto), parts, {\n name: parts.identity.name,\n fields: Object.freeze(parts.fields),\n relations: Object.freeze(parts.relations),\n derived: Object.freeze(parts.derived),\n members: Object.freeze({ ...parts.fields, ...parts.relations, ...parts.derived }),\n }),\n )\n\nconst isSameEntity = (left: AnyEntity, right: AnyEntity): boolean =>\n left.identity.token === right.identity.token\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\nconst isEntity = (value: unknown): value is AnyEntity =>\n typeof value === 'object' && value !== null && EntityTypeId in value\n\nconst kindName = { Field: 'field', Relation: 'relation', Derived: 'derived member' } as const\n\nconst kindOf = (entity: AnyEntity, key: string): string | undefined => {\n const member = (entity.members as Readonly<Record<string, EntityMember>>)[key]\n return member && kindName[member._tag]\n}\n\nconst assertFree = (entity: AnyEntity, keys: ReadonlyArray<string>, adding: string): void => {\n for (const key of keys) {\n const kind = kindOf(entity, key)\n if (kind !== undefined)\n throw new Error(\n `Entity \"${entity.name}\": cannot add ${adding} \"${key}\", it is already a ${kind}`,\n )\n }\n}\n\nconst mapValues = <A, B>(\n record: Readonly<Record<string, A>>,\n f: (value: A, key: string) => B,\n): Record<string, B> =>\n Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]))\n\nexport const Entity = {\n /** Declares an Entity from its intrinsic fields. Each call is a new identity. */\n define: <const Name extends string, Fields extends Schema.Struct.Fields>(\n name: Name,\n schema: Schema.Struct<Fields>,\n ): Entity<Name, Fields> => {\n const identity: EntityIdentity<Name> = Object.freeze({ name, token: Symbol(name) })\n return make({\n identity,\n schema,\n fields: mapValues(schema.fields, (fieldSchema, key) =>\n Object.freeze({\n _tag: 'Field',\n owner: identity,\n key,\n schema: fieldSchema,\n metadata: Metadata.empty,\n }),\n ),\n relations: {},\n derived: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n },\n\n /**\n * Declares the relations between a set of Entities in one step, and returns\n * them related. One step, because Entities that point at each other cannot\n * each be declared in terms of the other.\n */\n relate: <const Es extends Entities, const Rs extends RelationMap<Es>>(\n entities: Es,\n relations: Rs & CheckRelations<Es, Rs>,\n ): { readonly [K in keyof Es]: Related<Es, Rs, K> } => {\n const keyByToken = new Map<symbol, string>()\n for (const [key, entity] of Object.entries(entities)) {\n if (!isEntity(entity)) throw new Error(`Entity.relate: \"${key}\" is not an Entity`)\n const earlier = keyByToken.get(entity.identity.token)\n if (earlier !== undefined)\n throw new Error(`Entity.relate: \"${earlier}\" and \"${key}\" are the same Entity`)\n keyByToken.set(entity.identity.token, key)\n }\n const given: Readonly<Record<string, RelationSpecs | undefined>> = relations\n for (const owner of Object.keys(given))\n if (!(owner in entities))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = given[ownerKey] ?? {}\n assertFree(entity, Object.keys(specs), 'relation')\n const added = mapValues<RelationSpec<AnyEntity, Cardinality, boolean>, EntityMember>(\n specs,\n (spec, key) => {\n const targetKey = isEntity(spec.target)\n ? keyByToken.get(spec.target.identity.token)\n : undefined\n if (targetKey === undefined)\n throw new Error(\n `Entity \"${entity.name}\": relation \"${key}\" targets an Entity that is not being related`,\n )\n return Object.freeze({\n _tag: 'Relation',\n owner: entity.identity,\n key,\n // Read on call: the target may come later in `entities` than its owner.\n target: () => related[targetKey]!,\n cardinality: spec.cardinality,\n optional: spec.optional,\n metadata: Metadata.empty,\n })\n },\n )\n related[ownerKey] = make({ ...entity, relations: { ...entity.relations, ...added } })\n }\n return Object.freeze(related) as never\n },\n\n /**\n * Selects members of an Entity and assembles the schema of the result. A\n * relation selected with `true` yields an `EntityRef`; with a Selection of its\n * target, that Selection's value. `many` yields an array, an optional `one`\n * is nullable.\n */\n select: <E extends AnyEntity, const Spec>(\n entity: E,\n spec: Spec & SelectionSpec<E, Spec>,\n ): Selection<E['name'], Spec, SelectionSchema<E, Spec>, IdOf<E>> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n const fields = mapValues<unknown, Schema.Constraint>(spec, (selected, key) => {\n const member = members[key]\n if (member === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot select \"${key}\", it is not a member`)\n if (member._tag !== 'Relation') {\n if (selected !== true)\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is a ${kindName[member._tag]}, select it with true`,\n )\n return member.schema\n }\n const target = member.target()\n if (isSelectionPage(selected)) {\n if (member.cardinality !== 'many')\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is one ${target.name}, so it has no pages`,\n )\n if (!isSameEntity(selected.selection.entity, target))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" pages a Selection of ${target.name}`)\n return Schema.Struct({\n items: Schema.Array(selected.selection.schema as Schema.Top),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n })\n }\n let item: Schema.Top\n if (selected === true)\n item = Schema.Struct({ entity: Schema.Literal(target.name), id: idSchemaOf(target) })\n else if (isSelection(selected) && isSameEntity(selected.entity, target))\n item = selected.schema\n else\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" takes true or a Selection of ${target.name}`,\n )\n return member.cardinality === 'many'\n ? Schema.Array(item)\n : member.optional\n ? Schema.NullOr(item)\n : item\n })\n return Object.freeze({\n [SelectionTypeId]: SelectionTypeId,\n entity,\n members: spec,\n schema: Schema.Struct(fields),\n }) as never\n },\n\n /**\n * A `many` relation read a page at a time, in place of its Selection:\n * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page\n * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.\n */\n page: <Name extends string, S extends Schema.Constraint>(\n selection: Selection<Name, any, S>,\n window: PageWindow,\n ): SelectionPage<Name, S> => {\n const sides = [window.first, window.last].filter(size => size !== undefined)\n if (sides.length !== 1 || !sides.every(size => Number.isInteger(size) && size >= 0))\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`,\n )\n if (\n (window.first !== undefined && window.before !== undefined) ||\n (window.last !== undefined && window.after !== undefined)\n )\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`,\n )\n const page: SelectionPage<Name, S> = {\n [SelectionPageTypeId]: SelectionPageTypeId,\n selection,\n window,\n }\n return Object.freeze(page)\n },\n\n /** Adds readable members that are not part of `entity.schema`. */\n derived:\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New>): WithDerived<E, New> => {\n assertFree(entity, Object.keys(specs), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(specs, (spec, key) =>\n Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n metadata: Metadata.empty,\n }),\n )\n return make({ ...entity, derived: { ...entity.derived, ...added } }) as never\n },\n\n /** Attaches an interpreter's metadata to the Entity itself. */\n annotate:\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n make({ ...entity, metadata: Metadata.combine([entity.metadata, metadata]) }) as E,\n\n /**\n * Declares what every stored row, or every change of one, must hold:\n * `Entity.invariant('reservedWithinQuantity', ({ after }) =>\n * Expr.lte(after.reserved, after.quantity), { message })` over the row a\n * write leaves, or with `before` too over the change an update makes.\n * Refused where it is declared: an id declared twice, a predicate over another\n * Entity, one reading an input or nothing of `after` (that is a `when`), a path\n * naming no field.\n */\n invariant,\n\n /** The Entity's invariants, in the order they were declared. */\n invariants: invariantsOf,\n\n /**\n * A row (`{ after }`, a create's) or a change (`{ before, after }`, an\n * update's) under the Entity's invariants: `Valid`, `Invalid` with the ones\n * that fail (a null fails, as SQL's unknown), or `Undecided` with the fields\n * one reads that a row lacks.\n */\n judge,\n\n /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */\n readsBefore,\n\n /** `Entity.judge` against invariants already read, such as those a database binding keeps. */\n judgeAgainst,\n\n /**\n * The row an `Entity.input`'s value describes, judged: what a form can say\n * before the server does. Undecided for an invariant over a field it leaves unset.\n */\n judgeInput,\n\n /** The state invariants as a Schema check over the row type, each failure at its path. */\n check,\n\n /** Attaches an interpreter's metadata to members, by key. */\n annotateMembers:\n <E extends AnyEntity>(metadata: { readonly [K in keyof E['members']]?: Metadata }) =>\n (entity: E): E => {\n const given = metadata as Readonly<Record<string, Metadata | undefined>>\n for (const key of Object.keys(given))\n if (kindOf(entity, key) === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot annotate \"${key}\", it is not a member`)\n const annotate = (members: Readonly<Record<string, EntityMember>>) =>\n mapValues(members, (member, key) => {\n const extra = given[key]\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n return make({\n ...entity,\n fields: annotate(entity.fields),\n relations: annotate(entity.relations),\n derived: annotate(entity.derived),\n }) as E\n },\n\n /**\n * Reads an operation's input schema against an Entity. A key that names a\n * field maps to it; any other key is mapped explicitly, to a Field, to\n * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred\n * from a naming convention such as `authorId`.\n */\n input: <\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n // `{}` when every key maps itself, so the argument can be omitted.\n const Mapping = {},\n >(\n entity: E,\n schema: Schema.Struct<Fields>,\n ...mapping: keyof InputMapping<E, Fields, Mapping> extends never\n ? [mapping?: Mapping & InputMapping<E, Fields, Mapping>]\n : [mapping: Mapping & InputMapping<E, Fields, Mapping>]\n ): EntityInput<E, Fields, InputMembers<E, Fields, Mapping>> => {\n const written: Readonly<Record<string, InputMember | string | undefined>> = mapping[0] ?? {}\n for (const key of Object.keys(written))\n if (!(key in schema.fields))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" is mapped but is not a key of the input`)\n // A member named by its key: a Field as it is, a relation as its ids.\n const named = (key: string, name: string): InputMember => {\n const member = (entity.members as Readonly<Record<string, EntityMember | undefined>>)[name]\n switch (member?._tag) {\n case 'Field':\n return member\n case 'Relation':\n return Object.freeze({ _tag: 'RelationInput', relation: member })\n case 'Derived':\n case undefined:\n return fail(\n entity,\n `input key \"${key}\" is mapped to \"${name}\", which names no field or relation`,\n )\n }\n }\n const given: Readonly<Record<string, InputMember | undefined>> = mapValues(\n written,\n (member, key) => (typeof member === 'string' ? named(key, member) : member),\n )\n const fields: Readonly<Record<string, InputMember | undefined>> = entity.fields\n const members = mapValues(schema.fields, (_, key) => {\n const member =\n given[key] ??\n fields[key] ??\n fail(entity, `input key \"${key}\" names no field; map it to a member or Entity.unmapped`)\n const owned =\n member._tag === 'Field'\n ? member\n : member._tag === 'RelationInput' || member._tag === 'NestedInput'\n ? member.relation\n : member._tag === 'Unmapped'\n ? undefined\n : fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n )\n if (owned !== undefined && owned.owner.token !== entity.identity.token)\n fail(entity, `input key \"${key}\" is mapped to a member of \"${owned.owner.name}\"`)\n if (\n member._tag === 'NestedInput' &&\n !isSameEntity(member.input.entity, member.relation.target())\n )\n fail(\n entity,\n `input key \"${key}\" nests an input of \"${member.input.entity.name}\", but \"${member.relation.key}\" is of \"${member.relation.target().name}\"`,\n )\n return member\n })\n return Object.freeze({ entity, schema, members: Object.freeze(members) }) as never\n },\n\n /** For an input key that is about the operation rather than the Entity. */\n unmapped,\n\n /**\n * The schemas of some of an Entity's fields, by key, to spread into an input's\n * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.\n * The input then keeps the field's own rules, and its keys map themselves.\n */\n fields: <E extends AnyEntity, const Keys extends ReadonlyArray<keyof E['fields'] & string>>(\n entity: E,\n ...keys: Keys\n ): { readonly [K in Keys[number]]: E['fields'][K]['schema'] } =>\n Object.fromEntries(\n keys.map(key => [\n key,\n (\n (\n entity.fields as Readonly<\n Record<string, EntityField<string, string, Schema.Constraint> | undefined>\n >\n )[key] ?? fail(entity, `\"${key}\" is not a field`)\n ).schema,\n ]),\n ) as never,\n\n /**\n * The Selection of every member an input writes, with each relation as refs:\n * what an edit screen loads before it shows the input's current values.\n */\n selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n ): Selection<\n E['name'],\n WrittenSpec<Members>,\n SelectionSchema<E, WrittenSpec<Members>>,\n IdOf<E>\n > => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n const spec = Object.fromEntries(\n Object.values(members).flatMap((member): ReadonlyArray<readonly [string, unknown]> =>\n member._tag === 'Field'\n ? [[member.key, true]]\n : member._tag === 'RelationInput'\n ? [[member.relation.key, true]]\n : member._tag === 'NestedInput'\n ? // What the nested input writes of the target, so its keys can be shown too.\n [[member.relation.key, Entity.selectFor(member.input)]]\n : [],\n ),\n )\n return Entity.select(input.entity, spec as never) as never\n },\n\n /**\n * The input values that reproduce `value`, a value read through `selectFor`\n * (or any Selection with those members): a field as it is, a relation as the\n * id or ids of its refs. A key whose member `value` lacks is left out, as is\n * an unmapped key, which the Entity knows nothing about.\n */\n valuesFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n value: Readonly<Record<string, unknown>>,\n ): Partial<Schema.Struct.Type<Fields>> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n // The id of a ref or of a nested Selection's value; `undefined` when it has none.\n const idOf = (held: unknown): unknown =>\n held === null\n ? null\n : typeof held === 'object' && 'id' in held\n ? held.id\n : typeof held === 'string'\n ? held\n : undefined\n const entries = Object.entries(members).flatMap(([key, member]) => {\n if (member._tag === 'Unmapped') return []\n const written = member._tag === 'Field' ? member.key : member.relation.key\n if (!(written in value)) return []\n const read = value[written]\n switch (member._tag) {\n case 'Field':\n return [[key, read] as const]\n case 'NestedInput': {\n const nested = (held: unknown): unknown =>\n typeof held === 'object' && held !== null\n ? Entity.valuesFor(member.input, held as Readonly<Record<string, unknown>>)\n : null\n return [[key, Array.isArray(read) ? read.map(nested) : nested(read)] as const]\n }\n case 'RelationInput': {\n const ids = Array.isArray(read) ? read.map(idOf) : idOf(read)\n // A relation read without its ids (a nested Selection that left `id` out) fills nothing.\n const known = Array.isArray(ids) ? !ids.includes(undefined) : ids !== undefined\n return known ? [[key, ids] as const] : []\n }\n }\n })\n return Object.fromEntries(entries) as Partial<Schema.Struct.Type<Fields>>\n },\n\n is: isEntity,\n\n /** True when both descriptors are versions of one Entity. */\n same: isSameEntity,\n}\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one(\n target: AnyEntity,\n options?: { readonly optional: boolean },\n): RelationSpec<AnyEntity, 'one', boolean> {\n return { target, cardinality: 'one', optional: options?.optional ?? false }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n }),\n}\n\nexport const Derived = {\n make: <S extends Schema.Constraint>(schema: S): DerivedSpec<S> => ({ schema }),\n}\n\nexport * from './expr.js'\nexport * from './collation.js'\nexport * from './operators.js'\nexport * from './law.js'\nexport * from './text.js'\nexport * from './readFilter.js'\nexport * from './words.js'\nexport * from './shape.js'\n// The reference semantics of the IR above. The conformance suite that proves\n// an interpreter agrees with it is `foldkit-entity/conformance`, kept out of\n// this entry because it is fixture data every form and admin screen would\n// otherwise carry.\nexport * from './evaluate.js'\nexport type {\n AfterRow,\n BeforeRow,\n Change,\n DeclaredInvariant,\n Invariant,\n Judgement,\n} from './invariant.js'\nexport {\n Write,\n type AnyWrite,\n type BoundWrite,\n type ConditionedWrite,\n Computation,\n type WriteAssignment,\n type WriteComputations,\n type WriteCondition,\n type WriteIncrement,\n type WriteLink,\n type WriteSet,\n} from './write.js'\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAMA,QAAM,SAAS,IAAe,4BAA4B;CAE9D,QAAO,eAAc,WAAW,MAAM,EAAE;CACxC,YAAW,cAAa,UAAU;AACpC,CAAC;;AAGD,MAAM,aAAa;AAEnB,MAAa,YAAY;CACvB,QAAQ,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;CACxC,WAAW,OAAO,OAAO,EAAE,MAAM,YAAY,CAAC;CAC9C,SAAS,WAA8B;EACrC,IAAI,CAAC,WAAW,KAAK,MAAM,GACzB,MAAM,IAAI,MAAM,uCAAuC,OAAO,0BAA0B;EAE1F,OAAO,OAAO,OAAO;GAAE,MAAM;GAAU;EAAO,CAAC;CACjD;;CAGA,KAAK,cAAmCA,MAAI,GAAG,SAAS;;CAGxD,WAAW,aACT,OAAO,gBAAgBA,MAAI,IAAI,QAAQ,CAAC,CAAC,EAAE;;;;;;;CAQ7C,YAAY,SAAyB,KAAK,QAAQ,YAAW,UAAS,MAAM,YAAY,CAAC;AAC3F;;ACtDA,MAAM,aAAa,QACjB,UAAU,OAAO,GAAG,KAAK,UAAU,YAAY,GAAG;AAEpD,MAAM,UAAU,QACd,UAAU,SAAS,GAAG,KACtB,UAAU,kBAAkB,GAAG,KAC9B,UAAU,UAAU,GAAG,KAAK,OAAO,IAAI,YA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