foldkit-entity 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +121 -18
- package/dist/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +20 -0
- package/dist/conformance/index.js.map +1 -1
- package/dist/conformance/operator.d.ts.map +1 -1
- package/dist/conformance/operator.js +13 -4
- package/dist/conformance/operator.js.map +1 -1
- package/dist/entity.d.ts +13 -1
- package/dist/entity.d.ts.map +1 -1
- package/dist/entity.js +40 -12
- package/dist/entity.js.map +1 -1
- package/dist/evaluate.d.ts +1 -1
- package/dist/evaluate.d.ts.map +1 -1
- package/dist/evaluate.js +22 -18
- package/dist/evaluate.js.map +1 -1
- package/dist/expr.d.ts +70 -20
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +67 -47
- package/dist/expr.js.map +1 -1
- package/dist/held.js +11 -3
- package/dist/held.js.map +1 -1
- package/dist/index.d.ts +16 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/invariant.d.ts.map +1 -1
- package/dist/invariant.js +25 -19
- package/dist/invariant.js.map +1 -1
- package/dist/law.d.ts.map +1 -1
- package/dist/law.js +3 -9
- package/dist/law.js.map +1 -1
- package/dist/lawCore.d.ts +42 -0
- package/dist/lawCore.d.ts.map +1 -0
- package/dist/lawCore.js +12 -0
- package/dist/lawCore.js.map +1 -0
- package/dist/memoryTable.d.ts +11 -0
- package/dist/memoryTable.d.ts.map +1 -0
- package/dist/memoryTable.js +69 -0
- package/dist/memoryTable.js.map +1 -0
- package/dist/operators.d.ts.map +1 -1
- package/dist/operators.js +2 -66
- package/dist/operators.js.map +1 -1
- package/dist/sets.js.map +1 -1
- package/dist/write.d.ts +1 -1
- package/dist/write.d.ts.map +1 -1
- package/dist/write.js +40 -18
- package/dist/write.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operator.js","names":[],"sources":["../../src/conformance/operator.ts"],"sourcesContent":["/**\n * An operator held to what it declares (expr-operations-DESIGN §10.4): its\n * laws tested against an implementation, and one set of calls run through\n * every implementation given, their answers and refusals compared.\n *\n * Cases are drawn from a fixed sample of each kind of value (text with the\n * empty string, mixed case, non-ASCII, an astral character and `like`'s\n * wildcards; numbers with zero, negatives and a fraction; both booleans), kept\n * where the operator's input schema and the law's domain decode them, and\n * chosen by a seeded shuffle when there are more than asked for, so a run is\n * repeatable.\n */\nimport { Data, Option, Schema, SchemaAST } from 'effect'\nimport {\n Collation,\n Evidence,\n Expr,\n Law,\n Operators,\n QueryEvaluateError,\n valueOfOperand,\n type LawDescription,\n type MemoryOperators,\n type Operandish,\n type Operator,\n type TestedEvidence,\n} from '../index.js'\nimport { stampRun, stampTested } from '../tested.js'\nimport { tuplesOf } from './tuples.js'\n\ntype AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>\n\n/** What an implementation said of one call: a value, or that it refused it. */\nexport type Outcome = Data.TaggedEnum<{\n Value: { readonly value: unknown }\n Refused: { readonly reason: string }\n}>\nexport const Outcome = Data.taggedEnum<Outcome>()\n\n/**\n * What `Conformance.laws` found: every law held, with the evidence; the first\n * case one did not; or a law no case of which both sides answered, which\n * shows nothing of it.\n */\nexport type LawsVerdict = Data.TaggedEnum<{\n Holds: { readonly evidence: ReadonlyArray<TestedEvidence> }\n Unanswered: {\n readonly law: LawDescription\n /** Why the first refused call was refused. */\n readonly reason: string\n }\n Counterexample: {\n readonly law: LawDescription\n readonly args: ReadonlyArray<unknown>\n /** The collation the calls were made under, for an operator that compares text. */\n readonly collation: Option.Option<Collation>\n readonly left: Outcome\n readonly right: Outcome\n }\n}>\nexport const LawsVerdict = Data.taggedEnum<LawsVerdict>()\n\n/**\n * One way to run a call: its value, or a throw for a call it refuses. A call\n * of a predicate answers its truth, unknown as `null`.\n */\nexport type Runner = (call: Operandish) => unknown\n\n/** A call the implementations did not agree on, with what each said. */\nexport interface Disagreement {\n readonly args: ReadonlyArray<unknown>\n readonly collation: Option.Option<Collation>\n readonly outcomes: Readonly<Record<string, Outcome>>\n}\n\nexport interface OperatorReport {\n /** How many calls ran, each through every implementation. */\n readonly cases: number\n readonly disagreements: ReadonlyArray<Disagreement>\n}\n\nconst NUL = String.fromCharCode(0)\n// 'B' sorts before 'a' by code point and after it folded: what tells the collations apart.\n// `%`, `_` and `\\` are what `like` reads as wildcards and its escape.\nconst texts = [\n '',\n 'a',\n 'A',\n 'ab',\n 'aB',\n 'b',\n 'B',\n 'é',\n 'É',\n String.fromCodePoint(0x1f600),\n '%',\n '_',\n '\\\\',\n]\nconst numbers = [-2, -1, 0, 1, 2, 7, 0.5, -0.5, 1e6]\nconst booleans = [true, false]\n\n/** The sample values of a stored kind, before any schema narrows them. */\nconst candidates = (ast: SchemaAST.AST): ReadonlyArray<unknown> => {\n if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return texts\n if (SchemaAST.isNumber(ast)) return numbers\n if (SchemaAST.isBoolean(ast)) return booleans\n if (SchemaAST.isLiteral(ast)) return [ast.literal]\n if (SchemaAST.isUnion(ast)) return ast.types.flatMap(candidates)\n return []\n}\n\n/** Whether a stored value is one `schema` stores. */\nconst decodes = (schema: Schema.Top) => (value: unknown) =>\n Schema.is(Schema.toEncoded(schema))(value)\n\n/** The non-null samples every schema of `schemas` decodes, and the domain too when one is given. */\nconst samplesOf = (\n schemas: ReadonlyArray<Schema.Top>,\n domain: Option.Option<Schema.Top>,\n): ReadonlyArray<unknown> =>\n [...new Set(candidates(Schema.toEncoded(schemas[0]!).ast))].filter(\n value =>\n value !== null &&\n schemas.every(schema => decodes(schema)(value)) &&\n Option.match(domain, { onNone: () => true, onSome: within => decodes(within)(value) }),\n )\n\n/** A plain object: what JSON makes, and nothing whose data sits in a prototype. */\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/** A plain object's keys holding a value: one holding `undefined` is as absent, as JSON writes it. */\nconst keysOf = (record: Readonly<Record<string, unknown>>): ReadonlyArray<string> =>\n Object.keys(record).filter(key => record[key] !== undefined)\n\n/**\n * Two stored values alike, structurally. Not by their JSON, which writes\n * `Infinity` and `NaN` as `null`: a division by zero answering `Infinity` in\n * memory and null in SQL would read as agreeing. An object that is not plain\n * (its data in a prototype: a Date) is compared by its JSON, a Date's its time.\n */\nconst sameValue = (left: unknown, right: unknown): boolean => {\n if (typeof left === 'number' && typeof right === 'number') {\n return left === right || (Number.isNaN(left) && Number.isNaN(right))\n }\n if (Array.isArray(left) && Array.isArray(right)) {\n return left.length === right.length && left.every((each, i) => sameValue(each, right[i]))\n }\n if (isRecord(left) && isRecord(right)) {\n const keys = keysOf(left)\n return (\n keys.length === keysOf(right).length &&\n keys.every(key => Object.hasOwn(right, key) && sameValue(left[key], right[key]))\n )\n }\n if (typeof left === 'object' && left !== null && typeof right === 'object' && right !== null) {\n return JSON.stringify(left) === JSON.stringify(right)\n }\n return left === right\n}\n\n/** Two outcomes alike: equal values as stored, or both refusals. */\nconst same = (left: Outcome, right: Outcome): boolean =>\n left._tag === 'Refused' || right._tag === 'Refused'\n ? left._tag === right._tag\n : sameValue(left.value, right.value)\n\n/** Text by code point, as every interpreter's `binary` orders it; `<` compares UTF-16 units. */\nconst byCodePoint = (left: string, right: string): number => {\n const [a, b] = [[...left], [...right]]\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n const sign = a[i]!.codePointAt(0)! - b[i]!.codePointAt(0)!\n if (sign !== 0) return sign\n }\n return a.length - b.length\n}\n\n/** Two values of one kind in order: numbers, booleans, text by code point. */\nconst orderOf = (left: unknown, right: unknown): number =>\n typeof left === 'string' && typeof right === 'string'\n ? byCodePoint(left, right)\n : Number(left) - Number(right)\n\n/** A call of `op`, given `collation` when its rule takes one. */\nconst callOf = (\n op: AnyOperator,\n args: ReadonlyArray<unknown>,\n collation: Option.Option<Collation>,\n): Operandish =>\n Option.match(collation, {\n onNone: () => op(...args),\n onSome: each => op(...args, { collation: each }),\n })\n\n/** One side of an equation: a call to run (its text folded first, for a collation law), or a value. */\ntype Side = { readonly node: Operandish; readonly fold: boolean } | { readonly value: unknown }\n\n/** One equation for one tuple: its two sides, and what makes their outcomes keep the law. */\ninterface Plan {\n readonly args: ReadonlyArray<unknown>\n readonly collation: Option.Option<Collation>\n readonly left: Side\n readonly right: Side\n readonly holds: (left: Outcome, right: Outcome) => boolean\n}\n\n/** Each law `op` declares, with its equations: what `laws` and `lawsBy` evaluate. */\ninterface LawPlans {\n readonly law: LawDescription\n readonly plans: ReadonlyArray<Plan>\n}\n\nconst foldText = (value: unknown): unknown =>\n typeof value === 'string' ? Collation.foldAscii(value) : value\n\nconst nameOf = (op: AnyOperator): string =>\n op.descriptor.version === 1 ? op.descriptor.id : `${op.descriptor.id}@${op.descriptor.version}`\n\n/**\n * The equations of every law `op` declares, over up to `limit` tuples a law\n * chosen by `seed`. Nothing is run: a memory table and an SQL runner\n * evaluate the same plans.\n */\nconst lawPlans = (op: AnyOperator, limit: number, seed: number): ReadonlyArray<LawPlans> => {\n const { descriptor } = op\n const comparesText = (each: AnyOperator) => each.descriptor.collation !== 'none'\n // Each operator is called under a collation only where it compares text.\n const under = (each: AnyOperator, collation: Option.Option<Collation>) =>\n comparesText(each) ? collation : Option.none<Collation>()\n const run = (node: Operandish): Side => ({ node, fold: false })\n const value = (held: unknown): Side => ({ value: held })\n return descriptor.laws.map(law => {\n const shared = samplesOf(descriptor.input, law.domain)\n const tuples = (arity: number) =>\n tuplesOf(\n Array.from({ length: arity }, () => shared),\n limit,\n seed,\n )\n // The kernel compares text only under a collation, and literals bring none. An\n // implementation is told the collation, and may answer differently under each:\n // a pass under each where `op`, or a witness the law calls, compares text.\n const witnesses = Law.$match(law, {\n Inverse: ({ other }) => [other],\n Distributes: ({ over }) => [over],\n Associative: () => [],\n Commutative: () => [],\n Idempotent: () => [],\n Identity: () => [],\n Absorbing: () => [],\n Monotonic: () => [],\n PreservesCollation: () => [],\n })\n const collations = [op, ...witnesses].some(comparesText)\n ? [Option.some(Collation.binary), Option.some(Collation.asciiFold)]\n : [Option.none<Collation>()]\n const plans = collations.flatMap((collation): ReadonlyArray<Plan> => {\n const call = (...args: ReadonlyArray<unknown>) => callOf(op, args, under(op, collation))\n // A witness operator is called as `op` is: under the collation when it compares text.\n const witness = (other: AnyOperator, ...args: ReadonlyArray<unknown>) =>\n callOf(other, args, under(other, collation))\n const equal = (args: ReadonlyArray<unknown>, left: Side, right: Side): Plan => ({\n args,\n collation,\n left,\n right,\n holds: same,\n })\n const sided = (\n witness: unknown,\n side: 'left' | 'right' | 'both',\n answer: (a: unknown) => unknown,\n ) =>\n tuples(1).flatMap(([a]) => [\n ...(side === 'right'\n ? []\n : [equal([witness, a], run(call(witness, a)), value(answer(a)))]),\n ...(side === 'left'\n ? []\n : [equal([a, witness], run(call(a, witness)), value(answer(a)))]),\n ])\n return Law.$match(law, {\n Associative: () =>\n tuples(3).map(([a, b, c]) =>\n equal([a, b, c], run(call(call(a, b), c)), run(call(a, call(b, c)))),\n ),\n Commutative: () =>\n tuples(2).map(([a, b]) => equal([a, b], run(call(a, b)), run(call(b, a)))),\n Idempotent: () => tuples(1).map(([a]) => equal([a], run(call(a, a)), value(a))),\n Identity: ({ value: witness, side }) => sided(witness, side, a => a),\n Absorbing: ({ value: witness, side }) => sided(witness, side, () => witness),\n Inverse: ({ other, identity }) =>\n tuples(1).map(([a]) => equal([a], run(call(a, witness(other, a))), value(identity))),\n Distributes: ({ over }) =>\n tuples(3).map(([a, b, c]) =>\n equal(\n [a, b, c],\n run(call(a, witness(over, b, c))),\n run(witness(over, call(a, b), call(a, c))),\n ),\n ),\n Monotonic: ({ direction, position }) => {\n // Text in order as the collation orders it, folded under asciiFold.\n const under = (held: unknown) =>\n Option.exists(collation, each => each._tag === 'AsciiFold') ? foldText(held) : held\n const order = (left: unknown, right: unknown) => orderOf(under(left), under(right))\n const each = descriptor.input.map(schema => samplesOf([schema], law.domain))\n const pairs = each[position]!.flatMap(low =>\n each[position]!.filter(high => order(low, high) < 0).map(high => [low, high] as const),\n )\n const rest = each.filter((_, index) => index !== position)\n const sign = direction === 'increasing' ? 1 : -1\n return tuplesOf<unknown>([pairs, ...rest], limit, seed).map(([pair, ...others]) => {\n const [low, high] = pair as readonly [unknown, unknown]\n const at = (held: unknown) => {\n const args = [...others]\n args.splice(position, 0, held)\n return args\n }\n return {\n args: at(low),\n collation,\n left: run(call(...at(low))),\n right: run(call(...at(high))),\n // Equal outcomes agree, as under every other law: two refusals (no case),\n // and two equal infinities, whose difference `order` reads is NaN.\n holds: (left: Outcome, right: Outcome) =>\n same(left, right) ||\n (left._tag === 'Value' &&\n right._tag === 'Value' &&\n sign * order(left.value, right.value) <= 0),\n }\n })\n },\n // A law about the fold itself: its equations are made once, in the asciiFold pass.\n PreservesCollation: () =>\n Option.exists(collation, each => each._tag === 'AsciiFold')\n ? tuples(2).map(([a, b]) =>\n equal(\n [a, b],\n { node: call(a, b), fold: true },\n { node: call(foldText(a), foldText(b)), fold: true },\n ),\n )\n : [],\n })\n })\n if (plans.length === 0) {\n throw new Error(\n `[foldkit-entity] Conformance.laws: no sample of ${nameOf(op)}'s arguments is in ${Law.describe(law).kind}'s domain`,\n )\n }\n return { law: Law.describe(law), plans }\n })\n}\n\n/**\n * The verdict over laws whose calls' outcomes `answered` gives: the first\n * failure, or evidence of each. Two sides that both refuse agree, as a law\n * over values says nothing of a call neither answers, but they are no case of\n * it: a law is shown only by the cases whose sides both answer a value, and\n * one with none is `Unanswered`.\n */\nconst verdictOf = (\n op: AnyOperator,\n laws: ReadonlyArray<LawPlans>,\n answered: (node: Operandish) => Outcome,\n options: { readonly implementation: string; readonly seed: number },\n): LawsVerdict => {\n const outcomes = (side: Side): Outcome => {\n if ('value' in side) return Outcome.Value({ value: side.value })\n const outcome = answered(side.node)\n return side.fold\n ? Outcome.$match(outcome, {\n Value: ({ value }) => Outcome.Value({ value: foldText(value) }),\n Refused: refused => refused,\n })\n : outcome\n }\n const evidence: Array<TestedEvidence> = []\n for (const { law, plans } of laws) {\n let cases = 0\n let refusal = Option.none<string>()\n for (const plan of plans) {\n const left = outcomes(plan.left)\n const right = outcomes(plan.right)\n if (!plan.holds(left, right)) {\n return LawsVerdict.Counterexample({\n law,\n args: plan.args,\n collation: plan.collation,\n left,\n right,\n })\n }\n if (left._tag === 'Value' && right._tag === 'Value') cases += 1\n else if (Option.isNone(refusal) && left._tag === 'Refused') refusal = Option.some(left.reason)\n }\n if (cases === 0) {\n return LawsVerdict.Unanswered({\n law,\n reason: Option.getOrElse(refusal, () => 'no call was answered'),\n })\n }\n evidence.push(\n Evidence.Tested({\n operator: nameOf(op),\n law,\n implementation: options.implementation,\n cases,\n seed: options.seed,\n }),\n )\n }\n return LawsVerdict.Holds({ evidence })\n}\n\nexport const Conformance = {\n /** A runner of calls through a memory table: `Conformance.operator`'s for the in-memory interpreter. */\n memory:\n (operators: MemoryOperators): Runner =>\n call =>\n valueOfOperand(call, { operators }),\n\n /**\n * Tests every law `op` declares against `operators`' implementation of it,\n * up to `cases` tuples a law (200 by default), chosen by `seed` (0); a law\n * of both sides checks each tuple from each. Holds with a `Tested` record a\n * law, which `Operators.withEvidence` keeps; or the first case a law fails,\n * with both sides.\n */\n laws: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n op: Operator<In, Out>,\n operators: MemoryOperators,\n options: {\n readonly implementation?: string | undefined\n readonly cases?: number | undefined\n readonly seed?: number | undefined\n } = {},\n ): LawsVerdict => {\n const operator: AnyOperator = op\n const seed = options.seed ?? 0\n const outcome = (node: Operandish): Outcome => {\n try {\n return Outcome.Value({ value: valueOfOperand(node, { operators }) })\n } catch (error) {\n if (error instanceof QueryEvaluateError) return Outcome.Refused({ reason: error.message })\n throw error\n }\n }\n const verdict = verdictOf(operator, lawPlans(operator, options.cases ?? 200, seed), outcome, {\n implementation: options.implementation ?? 'memory',\n seed,\n })\n // Each record is of this table's implementations, its witnesses' too, which `withEvidence` checks.\n if (verdict._tag === 'Holds') verdict.evidence.forEach(record => stampTested(record, operators))\n return verdict\n },\n\n /**\n * As `laws`, each call run by `run` instead of a memory table: an SQL\n * implementation selected from a database, say, whose evidence a binding's\n * SQL table records. A throw is a refusal.\n */\n lawsBy: async <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n op: Operator<In, Out>,\n run: Runner,\n options: {\n readonly implementation: string\n readonly cases?: number | undefined\n readonly seed?: number | undefined\n },\n ): Promise<LawsVerdict> => {\n const operator: AnyOperator = op\n const seed = options.seed ?? 0\n const laws = lawPlans(operator, options.cases ?? 200, seed)\n const answers = new Map<Operandish, Outcome>()\n for (const { plans } of laws) {\n for (const side of plans.flatMap(plan => [plan.left, plan.right])) {\n if (!('node' in side) || answers.has(side.node)) continue\n try {\n answers.set(side.node, Outcome.Value({ value: await run(side.node) }))\n } catch (error) {\n answers.set(side.node, Outcome.Refused({ reason: String(error) }))\n }\n }\n }\n // Every call was run above, so each has its answer.\n const verdict = verdictOf(operator, laws, node => answers.get(node)!, {\n implementation: options.implementation,\n seed,\n })\n // Each record is a runner's, which an SQL table's `withEvidence` checks.\n if (verdict._tag === 'Holds') verdict.evidence.forEach(stampRun)\n return verdict\n },\n\n /**\n * Runs one set of calls of `op` through every implementation and compares\n * what each answered or refused. The calls are `cases` (argument tuples, as\n * stored), or generated: each argument a sample of its kind, null where its\n * schema admits one, and text holding NUL, under `binary` and `asciiFold` where the operator compares\n * text, up to `limit` (300) chosen by `seed` (0). A defined operator's\n * expansion is run beside the others, as `expansion`, by `expansionTable`\n * (the kernel's when not given).\n */\n operator: async <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n op: Operator<In, Out>,\n options: {\n readonly implementations: Readonly<Record<string, Runner>>\n readonly cases?: ReadonlyArray<ReadonlyArray<unknown>> | undefined\n readonly limit?: number | undefined\n readonly seed?: number | undefined\n readonly expansionTable?: MemoryOperators | undefined\n },\n ): Promise<OperatorReport> => {\n const operator: AnyOperator = op\n const { descriptor } = operator\n const runners: Record<string, Runner> = { ...options.implementations }\n if (Option.isSome(descriptor.definedAs)) {\n if (Object.hasOwn(runners, 'expansion')) {\n throw new Error(\n `[foldkit-entity] Conformance.operator: \"expansion\" names the expansion of ${nameOf(operator)}, which runs beside the implementations; name yours otherwise`,\n )\n }\n const table = options.expansionTable ?? Operators.kernel\n runners.expansion = call => valueOfOperand(Expr.expanded(call), { operators: table })\n }\n const generated = () =>\n tuplesOf(\n descriptor.input.map(schema => {\n const text = candidates(Schema.toEncoded(schema).ast).some(\n value => typeof value === 'string',\n )\n // Null only where the schema admits it: a call refuses a null literal otherwise.\n const nulls = decodes(schema)(null) ? [null] : []\n return [...nulls, ...samplesOf([schema], Option.none()), ...(text ? [`a${NUL}`] : [])]\n }),\n options.limit ?? 300,\n options.seed ?? 0,\n )\n const collations =\n descriptor.collation === 'none'\n ? [Option.none<Collation>()]\n : [Option.some(Collation.binary), Option.some(Collation.asciiFold)]\n const disagreements: Array<Disagreement> = []\n let cases = 0\n for (const args of options.cases ?? generated()) {\n for (const collation of collations) {\n cases += 1\n const call = callOf(operator, args, collation)\n // No prototype: an implementation named `__proto__` would set it, not a key.\n const outcomes: Record<string, Outcome> = Object.create(null)\n for (const [name, run] of Object.entries(runners)) {\n try {\n outcomes[name] = Outcome.Value({ value: await run(call) })\n } catch (error) {\n outcomes[name] = Outcome.Refused({ reason: String(error) })\n }\n }\n const [first, ...others] = Object.values(outcomes)\n if (first !== undefined && others.some(each => !same(first, each))) {\n disagreements.push({ args, collation, outcomes })\n }\n }\n }\n return { cases, disagreements }\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqCA,MAAa,UAAU,KAAK,WAAoB;AAuBhD,MAAa,cAAc,KAAK,WAAwB;AAqBxD,MAAM,MAAM,OAAO,aAAa,CAAC;AAGjC,MAAM,QAAQ;CACZ;CACA;CAC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S,CAAC;EAEpD;EAEF,OAAO;GAAE;GAAO;EAAc;CAChC;AACF"}
|
|
1
|
+
{"version":3,"file":"operator.js","names":[],"sources":["../../src/conformance/operator.ts"],"sourcesContent":["/**\n * An operator held to what it declares (expr-operations-DESIGN §10.4): its\n * laws tested against an implementation, and one set of calls run through\n * every implementation given, their answers and refusals compared.\n *\n * Cases are drawn from a fixed sample of each kind of value (text with the\n * empty string, mixed case, non-ASCII, an astral character and `like`'s\n * wildcards; numbers with zero, negatives and a fraction; both booleans), kept\n * where the operator's input schema and the law's domain decode them, and\n * chosen by a seeded shuffle when there are more than asked for, so a run is\n * repeatable.\n */\nimport { Data, Match, Option, Schema, SchemaAST } from 'effect'\nimport {\n Collation,\n Evidence,\n Expr,\n Law,\n Operators,\n QueryEvaluateError,\n valueOfOperand,\n type LawDescription,\n type MemoryOperators,\n type Operandish,\n type Operator,\n type TestedEvidence,\n} from '../index.js'\nimport { stampRun, stampTested } from '../tested.js'\nimport { tuplesOf } from './tuples.js'\n\ntype AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>\n\n/** What an implementation said of one call: a value, or that it refused it. */\nexport type Outcome = Data.TaggedEnum<{\n Value: { readonly value: unknown }\n Refused: { readonly reason: string }\n}>\nexport const Outcome = Data.taggedEnum<Outcome>()\n\n/**\n * What `Conformance.laws` found: every law held, with the evidence; the first\n * case one did not; or a law no case of which both sides answered, which\n * shows nothing of it.\n */\nexport type LawsVerdict = Data.TaggedEnum<{\n Holds: { readonly evidence: ReadonlyArray<TestedEvidence> }\n Unanswered: {\n readonly law: LawDescription\n /** Why the first refused call was refused. */\n readonly reason: string\n }\n Counterexample: {\n readonly law: LawDescription\n readonly args: ReadonlyArray<unknown>\n /** The collation the calls were made under, for an operator that compares text. */\n readonly collation: Option.Option<Collation>\n readonly left: Outcome\n readonly right: Outcome\n }\n}>\nexport const LawsVerdict = Data.taggedEnum<LawsVerdict>()\n\n/**\n * One way to run a call: its value, or a throw for a call it refuses. A call\n * of a predicate answers its truth, unknown as `null`.\n */\nexport type Runner = (call: Operandish) => unknown\n\n/** A call the implementations did not agree on, with what each said. */\nexport interface Disagreement {\n readonly args: ReadonlyArray<unknown>\n readonly collation: Option.Option<Collation>\n readonly outcomes: Readonly<Record<string, Outcome>>\n}\n\nexport interface OperatorReport {\n /** How many calls ran, each through every implementation. */\n readonly cases: number\n readonly disagreements: ReadonlyArray<Disagreement>\n}\n\nconst NUL = String.fromCharCode(0)\n// 'B' sorts before 'a' by code point and after it folded: what tells the collations apart.\n// `%`, `_` and `\\` are what `like` reads as wildcards and its escape.\nconst texts = [\n '',\n 'a',\n 'A',\n 'ab',\n 'aB',\n 'b',\n 'B',\n 'é',\n 'É',\n String.fromCodePoint(0x1f600),\n '%',\n '_',\n '\\\\',\n]\nconst numbers = [-2, -1, 0, 1, 2, 7, 0.5, -0.5, 1e6]\nconst booleans = [true, false]\n\n/** The sample values of a stored kind, before any schema narrows them. */\nconst candidates = (ast: SchemaAST.AST): ReadonlyArray<unknown> => {\n if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return texts\n if (SchemaAST.isNumber(ast)) return numbers\n if (SchemaAST.isBoolean(ast)) return booleans\n if (SchemaAST.isLiteral(ast)) return [ast.literal]\n if (SchemaAST.isUnion(ast)) return ast.types.flatMap(candidates)\n return []\n}\n\n/** Whether a stored value is one `schema` stores. */\nconst decodes = (schema: Schema.Top) => (value: unknown) =>\n Schema.is(Schema.toEncoded(schema))(value)\n\n/** The non-null samples every schema of `schemas` decodes, and the domain too when one is given. */\nconst samplesOf = (\n schemas: ReadonlyArray<Schema.Top>,\n domain: Option.Option<Schema.Top>,\n): ReadonlyArray<unknown> =>\n [...new Set(candidates(Schema.toEncoded(schemas[0]!).ast))].filter(\n value =>\n value !== null &&\n schemas.every(schema => decodes(schema)(value)) &&\n Option.match(domain, { onNone: () => true, onSome: within => decodes(within)(value) }),\n )\n\n/** A plain object: what JSON makes, and nothing whose data sits in a prototype. */\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/** A plain object's keys holding a value: one holding `undefined` is as absent, as JSON writes it. */\nconst keysOf = (record: Readonly<Record<string, unknown>>): ReadonlyArray<string> =>\n Object.keys(record).filter(key => record[key] !== undefined)\n\n/**\n * Two stored values alike, structurally. Not by their JSON, which writes\n * `Infinity` and `NaN` as `null`: a division by zero answering `Infinity` in\n * memory and null in SQL would read as agreeing. An object that is not plain\n * (its data in a prototype: a Date) is compared by its JSON, a Date's its time.\n */\nconst sameValue = (left: unknown, right: unknown): boolean => {\n if (typeof left === 'number' && typeof right === 'number') {\n return left === right || (Number.isNaN(left) && Number.isNaN(right))\n }\n if (Array.isArray(left) && Array.isArray(right)) {\n return left.length === right.length && left.every((each, i) => sameValue(each, right[i]))\n }\n if (isRecord(left) && isRecord(right)) {\n const keys = keysOf(left)\n return (\n keys.length === keysOf(right).length &&\n keys.every(key => Object.hasOwn(right, key) && sameValue(left[key], right[key]))\n )\n }\n if (typeof left === 'object' && left !== null && typeof right === 'object' && right !== null) {\n return JSON.stringify(left) === JSON.stringify(right)\n }\n return left === right\n}\n\n/** Two outcomes alike: equal values as stored, or both refusals. */\nconst same = (left: Outcome, right: Outcome): boolean =>\n Match.valueTags(left, {\n Refused: () => right._tag === 'Refused',\n Value: ({ value }) =>\n Match.valueTags(right, {\n Refused: () => false,\n Value: other => sameValue(value, other.value),\n }),\n })\n\n/** Text by code point, as every interpreter's `binary` orders it; `<` compares UTF-16 units. */\nconst byCodePoint = (left: string, right: string): number => {\n const [a, b] = [[...left], [...right]]\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n const sign = a[i]!.codePointAt(0)! - b[i]!.codePointAt(0)!\n if (sign !== 0) return sign\n }\n return a.length - b.length\n}\n\n/** Two values of one kind in order: numbers, booleans, text by code point. */\nconst orderOf = (left: unknown, right: unknown): number =>\n typeof left === 'string' && typeof right === 'string'\n ? byCodePoint(left, right)\n : Number(left) - Number(right)\n\n/** A call of `op`, given `collation` when its rule takes one. */\nconst callOf = (\n op: AnyOperator,\n args: ReadonlyArray<unknown>,\n collation: Option.Option<Collation>,\n): Operandish =>\n Option.match(collation, {\n onNone: () => op(...args),\n onSome: each => op(...args, { collation: each }),\n })\n\n/** One side of an equation: a call to run (its text folded first, for a collation law), or a value. */\ntype Side = { readonly node: Operandish; readonly fold: boolean } | { readonly value: unknown }\n\n/** One equation for one tuple: its two sides, and what makes their outcomes keep the law. */\ninterface Plan {\n readonly args: ReadonlyArray<unknown>\n readonly collation: Option.Option<Collation>\n readonly left: Side\n readonly right: Side\n readonly holds: (left: Outcome, right: Outcome) => boolean\n}\n\n/** Each law `op` declares, with its equations: what `laws` and `lawsBy` evaluate. */\ninterface LawPlans {\n readonly law: LawDescription\n readonly plans: ReadonlyArray<Plan>\n}\n\nconst foldText = (value: unknown): unknown =>\n typeof value === 'string' ? Collation.foldAscii(value) : value\n\nconst nameOf = (op: AnyOperator): string =>\n op.descriptor.version === 1 ? op.descriptor.id : `${op.descriptor.id}@${op.descriptor.version}`\n\n/**\n * The equations of every law `op` declares, over up to `limit` tuples a law\n * chosen by `seed`. Nothing is run: a memory table and an SQL runner\n * evaluate the same plans.\n */\nconst lawPlans = (op: AnyOperator, limit: number, seed: number): ReadonlyArray<LawPlans> => {\n const { descriptor } = op\n const comparesText = (each: AnyOperator) => each.descriptor.collation !== 'none'\n // Each operator is called under a collation only where it compares text.\n const under = (each: AnyOperator, collation: Option.Option<Collation>) =>\n comparesText(each) ? collation : Option.none<Collation>()\n const run = (node: Operandish): Side => ({ node, fold: false })\n const value = (held: unknown): Side => ({ value: held })\n return descriptor.laws.map(law => {\n const shared = samplesOf(descriptor.input, law.domain)\n const tuples = (arity: number) =>\n tuplesOf(\n Array.from({ length: arity }, () => shared),\n limit,\n seed,\n )\n // The kernel compares text only under a collation, and literals bring none. An\n // implementation is told the collation, and may answer differently under each:\n // a pass under each where `op`, or a witness the law calls, compares text.\n const witnesses = Law.$match(law, {\n Inverse: ({ other }) => [other],\n Distributes: ({ over }) => [over],\n Associative: () => [],\n Commutative: () => [],\n Idempotent: () => [],\n Identity: () => [],\n Absorbing: () => [],\n Monotonic: () => [],\n PreservesCollation: () => [],\n })\n const collations = [op, ...witnesses].some(comparesText)\n ? [Option.some(Collation.binary), Option.some(Collation.asciiFold)]\n : [Option.none<Collation>()]\n const plans = collations.flatMap((collation): ReadonlyArray<Plan> => {\n const call = (...args: ReadonlyArray<unknown>) => callOf(op, args, under(op, collation))\n // A witness operator is called as `op` is: under the collation when it compares text.\n const witness = (other: AnyOperator, ...args: ReadonlyArray<unknown>) =>\n callOf(other, args, under(other, collation))\n const equal = (args: ReadonlyArray<unknown>, left: Side, right: Side): Plan => ({\n args,\n collation,\n left,\n right,\n holds: same,\n })\n const sided = (\n witness: unknown,\n side: 'left' | 'right' | 'both',\n answer: (a: unknown) => unknown,\n ) =>\n tuples(1).flatMap(([a]) => [\n ...(side === 'right'\n ? []\n : [equal([witness, a], run(call(witness, a)), value(answer(a)))]),\n ...(side === 'left'\n ? []\n : [equal([a, witness], run(call(a, witness)), value(answer(a)))]),\n ])\n return Law.$match(law, {\n Associative: () =>\n tuples(3).map(([a, b, c]) =>\n equal([a, b, c], run(call(call(a, b), c)), run(call(a, call(b, c)))),\n ),\n Commutative: () =>\n tuples(2).map(([a, b]) => equal([a, b], run(call(a, b)), run(call(b, a)))),\n Idempotent: () => tuples(1).map(([a]) => equal([a], run(call(a, a)), value(a))),\n Identity: ({ value: witness, side }) => sided(witness, side, a => a),\n Absorbing: ({ value: witness, side }) => sided(witness, side, () => witness),\n Inverse: ({ other, identity }) =>\n tuples(1).map(([a]) => equal([a], run(call(a, witness(other, a))), value(identity))),\n Distributes: ({ over }) =>\n tuples(3).map(([a, b, c]) =>\n equal(\n [a, b, c],\n run(call(a, witness(over, b, c))),\n run(witness(over, call(a, b), call(a, c))),\n ),\n ),\n Monotonic: ({ direction, position }) => {\n // Text in order as the collation orders it, folded under asciiFold.\n const under = (held: unknown) =>\n Option.exists(collation, each => each._tag === 'AsciiFold') ? foldText(held) : held\n const order = (left: unknown, right: unknown) => orderOf(under(left), under(right))\n const each = descriptor.input.map(schema => samplesOf([schema], law.domain))\n const pairs = each[position]!.flatMap(low =>\n each[position]!.filter(high => order(low, high) < 0).map(high => [low, high] as const),\n )\n const rest = each.filter((_, index) => index !== position)\n const sign = direction === 'increasing' ? 1 : -1\n return tuplesOf<unknown>([pairs, ...rest], limit, seed).map(([pair, ...others]) => {\n const [low, high] = pair as readonly [unknown, unknown]\n const at = (held: unknown) => {\n const args = [...others]\n args.splice(position, 0, held)\n return args\n }\n return {\n args: at(low),\n collation,\n left: run(call(...at(low))),\n right: run(call(...at(high))),\n // Equal outcomes agree, as under every other law: two refusals (no case),\n // and two equal infinities, whose difference `order` reads is NaN.\n holds: (left: Outcome, right: Outcome) =>\n same(left, right) ||\n (left._tag === 'Value' &&\n right._tag === 'Value' &&\n sign * order(left.value, right.value) <= 0),\n }\n })\n },\n // A law about the fold itself: its equations are made once, in the asciiFold pass.\n PreservesCollation: () =>\n Option.exists(collation, each => each._tag === 'AsciiFold')\n ? tuples(2).map(([a, b]) =>\n equal(\n [a, b],\n { node: call(a, b), fold: true },\n { node: call(foldText(a), foldText(b)), fold: true },\n ),\n )\n : [],\n })\n })\n if (plans.length === 0) {\n throw new Error(\n `[foldkit-entity] Conformance.laws: no sample of ${nameOf(op)}'s arguments is in ${Law.describe(law).kind}'s domain`,\n )\n }\n return { law: Law.describe(law), plans }\n })\n}\n\n/**\n * The verdict over laws whose calls' outcomes `answered` gives: the first\n * failure, or evidence of each. Two sides that both refuse agree, as a law\n * over values says nothing of a call neither answers, but they are no case of\n * it: a law is shown only by the cases whose sides both answer a value, and\n * one with none is `Unanswered`.\n */\nconst verdictOf = (\n op: AnyOperator,\n laws: ReadonlyArray<LawPlans>,\n answered: (node: Operandish) => Outcome,\n options: { readonly implementation: string; readonly seed: number },\n): LawsVerdict => {\n const outcomes = (side: Side): Outcome => {\n if ('value' in side) return Outcome.Value({ value: side.value })\n const outcome = answered(side.node)\n return side.fold\n ? Outcome.$match(outcome, {\n Value: ({ value }) => Outcome.Value({ value: foldText(value) }),\n Refused: refused => refused,\n })\n : outcome\n }\n const evidence: Array<TestedEvidence> = []\n for (const { law, plans } of laws) {\n let cases = 0\n let refusal = Option.none<string>()\n for (const plan of plans) {\n const left = outcomes(plan.left)\n const right = outcomes(plan.right)\n if (!plan.holds(left, right)) {\n return LawsVerdict.Counterexample({\n law,\n args: plan.args,\n collation: plan.collation,\n left,\n right,\n })\n }\n if (left._tag === 'Value' && right._tag === 'Value') {\n cases += 1\n continue\n }\n if (Option.isNone(refusal) && left._tag === 'Refused') refusal = Option.some(left.reason)\n }\n if (cases === 0) {\n return LawsVerdict.Unanswered({\n law,\n reason: Option.getOrElse(refusal, () => 'no call was answered'),\n })\n }\n evidence.push(\n Evidence.Tested({\n operator: nameOf(op),\n law,\n implementation: options.implementation,\n cases,\n seed: options.seed,\n }),\n )\n }\n return LawsVerdict.Holds({ evidence })\n}\n\nexport const Conformance = {\n /** A runner of calls through a memory table: `Conformance.operator`'s for the in-memory interpreter. */\n memory:\n (operators: MemoryOperators): Runner =>\n call =>\n valueOfOperand(call, { operators }),\n\n /**\n * Tests every law `op` declares against `operators`' implementation of it,\n * up to `cases` tuples a law (200 by default), chosen by `seed` (0); a law\n * of both sides checks each tuple from each. Holds with a `Tested` record a\n * law, which `Operators.withEvidence` keeps; or the first case a law fails,\n * with both sides.\n */\n laws: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n op: Operator<In, Out>,\n operators: MemoryOperators,\n options: {\n readonly implementation?: string | undefined\n readonly cases?: number | undefined\n readonly seed?: number | undefined\n } = {},\n ): LawsVerdict => {\n const operator: AnyOperator = op\n const seed = options.seed ?? 0\n const outcome = (node: Operandish): Outcome => {\n try {\n return Outcome.Value({ value: valueOfOperand(node, { operators }) })\n } catch (error) {\n if (error instanceof QueryEvaluateError) return Outcome.Refused({ reason: error.message })\n throw error\n }\n }\n const verdict = verdictOf(operator, lawPlans(operator, options.cases ?? 200, seed), outcome, {\n implementation: options.implementation ?? 'memory',\n seed,\n })\n // Each record is of this table's implementations, its witnesses' too, which `withEvidence` checks.\n if (verdict._tag === 'Holds') verdict.evidence.forEach(record => stampTested(record, operators))\n return verdict\n },\n\n /**\n * As `laws`, each call run by `run` instead of a memory table: an SQL\n * implementation selected from a database, say, whose evidence a binding's\n * SQL table records. A throw is a refusal.\n */\n lawsBy: async <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n op: Operator<In, Out>,\n run: Runner,\n options: {\n readonly implementation: string\n readonly cases?: number | undefined\n readonly seed?: number | undefined\n },\n ): Promise<LawsVerdict> => {\n const operator: AnyOperator = op\n const seed = options.seed ?? 0\n const laws = lawPlans(operator, options.cases ?? 200, seed)\n const answers = new Map<Operandish, Outcome>()\n for (const { plans } of laws) {\n for (const side of plans.flatMap(plan => [plan.left, plan.right])) {\n if (!('node' in side) || answers.has(side.node)) continue\n try {\n answers.set(side.node, Outcome.Value({ value: await run(side.node) }))\n } catch (error) {\n answers.set(side.node, Outcome.Refused({ reason: String(error) }))\n }\n }\n }\n // Every call was run above, so each has its answer.\n const verdict = verdictOf(operator, laws, node => answers.get(node)!, {\n implementation: options.implementation,\n seed,\n })\n // Each record is a runner's, which an SQL table's `withEvidence` checks.\n if (verdict._tag === 'Holds') verdict.evidence.forEach(stampRun)\n return verdict\n },\n\n /**\n * Runs one set of calls of `op` through every implementation and compares\n * what each answered or refused. The calls are `cases` (argument tuples, as\n * stored), or generated: each argument a sample of its kind, null where its\n * schema admits one, and text holding NUL, under `binary` and `asciiFold` where the operator compares\n * text, up to `limit` (300) chosen by `seed` (0). A defined operator's\n * expansion is run beside the others, as `expansion`, by `expansionTable`\n * (the kernel's when not given).\n */\n operator: async <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n op: Operator<In, Out>,\n options: {\n readonly implementations: Readonly<Record<string, Runner>>\n readonly cases?: ReadonlyArray<ReadonlyArray<unknown>> | undefined\n readonly limit?: number | undefined\n readonly seed?: number | undefined\n readonly expansionTable?: MemoryOperators | undefined\n },\n ): Promise<OperatorReport> => {\n const operator: AnyOperator = op\n const { descriptor } = operator\n const runners: Record<string, Runner> = { ...options.implementations }\n if (Option.isSome(descriptor.definedAs)) {\n if (Object.hasOwn(runners, 'expansion')) {\n throw new Error(\n `[foldkit-entity] Conformance.operator: \"expansion\" names the expansion of ${nameOf(operator)}, which runs beside the implementations; name yours otherwise`,\n )\n }\n const table = options.expansionTable ?? Operators.kernel\n runners.expansion = call => valueOfOperand(Expr.expanded(call), { operators: table })\n }\n const generated = () =>\n tuplesOf(\n descriptor.input.map(schema => {\n const text = candidates(Schema.toEncoded(schema).ast).some(\n value => typeof value === 'string',\n )\n // Null only where the schema admits it: a call refuses a null literal otherwise.\n const nulls = decodes(schema)(null) ? [null] : []\n return [...nulls, ...samplesOf([schema], Option.none()), ...(text ? [`a${NUL}`] : [])]\n }),\n options.limit ?? 300,\n options.seed ?? 0,\n )\n const collations =\n descriptor.collation === 'none'\n ? [Option.none<Collation>()]\n : [Option.some(Collation.binary), Option.some(Collation.asciiFold)]\n const disagreements: Array<Disagreement> = []\n let cases = 0\n for (const args of options.cases ?? generated()) {\n for (const collation of collations) {\n cases += 1\n const call = callOf(operator, args, collation)\n // No prototype: an implementation named `__proto__` would set it, not a key.\n const outcomes: Record<string, Outcome> = Object.create(null)\n for (const [name, run] of Object.entries(runners)) {\n try {\n outcomes[name] = Outcome.Value({ value: await run(call) })\n } catch (error) {\n outcomes[name] = Outcome.Refused({ reason: String(error) })\n }\n }\n const [first, ...others] = Object.values(outcomes)\n if (first !== undefined && others.some(each => !same(first, each))) {\n disagreements.push({ args, collation, outcomes })\n }\n }\n }\n return { cases, disagreements }\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqCA,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E,QAAQ,OAAO,KAAK,EAAE,CAAC;GAC5D;GAEF,MAAM,CAAC,OAAO,GAAG,UAAU,OAAO,OAAO,QAAQ;GACjD,IAAI,UAAU,KAAA,KAAa,OAAO,MAAK,SAAQ,CAAC,KAAK,OAAO,IAAI,CAAC,GAC/D,cAAc,KAAK;IAAE;IAAM;IAAW;GAAS,CAAC;EAEpD;EAEF,OAAO;GAAE;GAAO;EAAc;CAChC;AACF"}
|
package/dist/entity.d.ts
CHANGED
|
@@ -137,7 +137,7 @@ export declare const variantsOf: (entity: AnyEntity) => Option.Option<EntityVari
|
|
|
137
137
|
* each be declared in terms of the other.
|
|
138
138
|
*/
|
|
139
139
|
export declare const relate: <const Es extends Entities, const Rs extends RelationMap<Es>>(entities: Es, relations: Rs & CheckRelations<Es, Rs>) => { readonly [K in keyof Es]: Related<Es, Rs, K>; };
|
|
140
|
-
/** A `one` relation a delete
|
|
140
|
+
/** A `one` relation a delete acts through (it cascades, restricts or clears), and the Entity that owns it. */
|
|
141
141
|
export interface Cascade {
|
|
142
142
|
readonly relation: OneRelation;
|
|
143
143
|
readonly owner: AnyEntity;
|
|
@@ -149,6 +149,18 @@ export interface Cascade {
|
|
|
149
149
|
* members every descriptor of it shares.
|
|
150
150
|
*/
|
|
151
151
|
export declare const cascading: (entity: AnyEntity) => ReadonlyArray<Cascade>;
|
|
152
|
+
/**
|
|
153
|
+
* The `one` relations, of any Entity, declared `onDelete: 'restrict'` that
|
|
154
|
+
* point at `entity`: a delete of one of its rows is refused while a row points
|
|
155
|
+
* at it through one (#467).
|
|
156
|
+
*/
|
|
157
|
+
export declare const restricting: (entity: AnyEntity) => ReadonlyArray<Cascade>;
|
|
158
|
+
/**
|
|
159
|
+
* The optional `one` relations, of any Entity, declared `onDelete: 'setNull'`
|
|
160
|
+
* that point at `entity`: deleting one of its rows clears the link on each row
|
|
161
|
+
* pointing at it through one, which stays (#467).
|
|
162
|
+
*/
|
|
163
|
+
export declare const clearing: (entity: AnyEntity) => ReadonlyArray<Cascade>;
|
|
152
164
|
/**
|
|
153
165
|
* Selects members of an Entity and assembles the schema of the result. A
|
|
154
166
|
* relation selected with `true` yields an `EntityRef`; with a Selection of its
|
package/dist/entity.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity.d.ts","names":[],"sources":["../src/entity.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"entity.d.ts","names":[],"sources":["../src/entity.ts"],"mappings":";;;;;;;;KA8DK,KAAK,UAAU,WAAW,aAAa,YAAY;WAEzC,sBAAsB,YAAY;;;KAG5C,WAAW,UAAU,WAAW,YAAY,mBAC9C,WAAW,MAAM,IAAI;WACX;WACA,UAAU,+BAA+B;KAE/C,yBAAyB,qBAExB,mBAEA,oBAAmB,UACtB;WAEY,mCAAmC;;KAG/C,YAAY,GAAG,YAAY,gBAC9B,UAAU,oBAAoB,YAAY,cAAc,SAAS,SAAS,KACtE,cAAc,MAAM,QAAQ,GAAG,IAAI,KAAK,KACxC,UAAU,aAAa,YAAY,cAAc,SAAS,KACxD,OAAO,MAAM,QAAQ,GAAG,IAAI;;KAI/B,eAAe,WAAW,UAAU,kBAC7B,WAAW,KAAK,gBAAgB,iBAE1B,WAAW,GAAG,KAAK,gBAAgB,GAAG,oBACxC,sCAAsC,GAAG,eAC7C,GAAG,GAAG;KAKb,UAAU,eAAe,aAAa,OAAO;WACvC,QAAQ,OAAO,QAAQ;WACvB,IAAI,WAAW;;KAGrB,aAAa,gCAAgC,UAAU;KAEvD,WAAW,UAAU,OAAO,cAAc,OAAO;WAC3C,OAAO,OAAO,OAAO;WACrB,SAAS,OAAO;WAChB,aAAa,OAAO;;;KAI1B,cAAc,KAAK;WACb;aACE,aAAa,UAAU,SAC9B;eAA0B,QAAQ,OAAO,OAAO;;;gBAItC,WAAW,aAAa,EAAE;;KAIrC,mBAAmB,UAAU,WAAW,GAAG,SAAS,cAAc,mDAE9C,eAEnB,gBAAgB,cACd,gBAAgB,cAA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AY,GAAG;;;;;;;;;;;;;;;;;;;;;;qBAyE1E,OACV,UAAU,WAAS,QAAU,WAAW,IAAE;WAAsB,IAAI;OAAO,QACnE,MAAI;;qBAYF,WAAQ,UACR,cACV,UAAU,WAAS,QAAU,MAAI;;qBAIvB,kBACV,UAAU,WAAS,sBAAwB,WAAW,gBAAgB,iBAAU,QACxE,MAAI;;;;;;;qBA4BF,QACX,UAAU,WACV,eAAe,OAAO,OAAO,cAEvB,cAAY,QAEV,GAAC,QACD,OAAO,OAAO,YAAO,eACX,aAAa,GAAG,QAAQ,0BACrC,UAAU,UAAU,aAAa,GAAG,QAAQ,aAC5C,SAAS,UAAU,aAAa,GAAG,QAAQ,cAC/C,YAAY,GAAG,QAAQ,aAAa,GAAG,QAAQ;;;;;;qBAiErC,SACX,UAAU,iBACJ,aAAa,oBAAoB,uBAAqB,QAEpD,MAAC,MACA,qBACI,KAAK,eAAe,YAAY;;;;;;;;qBAoBlC,YAAa,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OAClF,YAAY,GAAG,QAAQ,UAAQ;WAClB,OAAO,SAAS;MACnC,UACD,WACA,YAAY,UACZ,gBAAgB,GAAG,YAAY,WAC/B,KAAK;;;;;;;qBAuBM,YAAa,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OAClF,YAAY,GAAG,QAAQ,UAAQ,OAC/B,SAAS,6BACf,QAAQ,OAAO,OAAO,KAAK"}
|
package/dist/entity.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Option, Schema } from "effect";
|
|
1
|
+
import { Match, Option, Schema } from "effect";
|
|
2
2
|
import { Metadata } from "foldkit-metadata";
|
|
3
3
|
import { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from "./ids.js";
|
|
4
4
|
import { own, put } from "./record.js";
|
|
@@ -177,17 +177,21 @@ const relate = (entities, relations) => {
|
|
|
177
177
|
put(related, ownerKey, entity);
|
|
178
178
|
}
|
|
179
179
|
for (const [entity, added] of additions) extend(entity, { relations: added });
|
|
180
|
-
for (const [entity, added] of additions) for (const member of Object.values(added)) if (member._tag === "Relation" && Option.isSome(member.onDelete))
|
|
180
|
+
for (const [entity, added] of additions) for (const member of Object.values(added)) if (member._tag === "Relation" && Option.isSome(member.onDelete)) pointInto(member.onDelete.value, member.target().identity, {
|
|
181
181
|
relation: member,
|
|
182
182
|
owner: entity
|
|
183
183
|
});
|
|
184
184
|
return Object.freeze(related);
|
|
185
185
|
};
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
186
|
+
const pointing = {
|
|
187
|
+
cascade: /* @__PURE__ */ new WeakMap(),
|
|
188
|
+
restrict: /* @__PURE__ */ new WeakMap(),
|
|
189
|
+
setNull: /* @__PURE__ */ new WeakMap()
|
|
190
|
+
};
|
|
191
|
+
const pointInto = (action, target, edge) => {
|
|
192
|
+
const known = pointing[action].get(target) ?? [];
|
|
193
|
+
known.push(edge);
|
|
194
|
+
pointing[action].set(target, known);
|
|
191
195
|
};
|
|
192
196
|
/**
|
|
193
197
|
* The `one` relations, of any Entity, declared `onDelete: 'cascade'` that point
|
|
@@ -195,7 +199,19 @@ const cascadeInto = (target, cascade) => {
|
|
|
195
199
|
* one, and so on from those. The owner is the Entity as it was related, whose
|
|
196
200
|
* members every descriptor of it shares.
|
|
197
201
|
*/
|
|
198
|
-
const cascading = (entity) =>
|
|
202
|
+
const cascading = (entity) => pointing.cascade.get(entity.identity) ?? [];
|
|
203
|
+
/**
|
|
204
|
+
* The `one` relations, of any Entity, declared `onDelete: 'restrict'` that
|
|
205
|
+
* point at `entity`: a delete of one of its rows is refused while a row points
|
|
206
|
+
* at it through one (#467).
|
|
207
|
+
*/
|
|
208
|
+
const restricting = (entity) => pointing.restrict.get(entity.identity) ?? [];
|
|
209
|
+
/**
|
|
210
|
+
* The optional `one` relations, of any Entity, declared `onDelete: 'setNull'`
|
|
211
|
+
* that point at `entity`: deleting one of its rows clears the link on each row
|
|
212
|
+
* pointing at it through one, which stays (#467).
|
|
213
|
+
*/
|
|
214
|
+
const clearing = (entity) => pointing.setNull.get(entity.identity) ?? [];
|
|
199
215
|
/**
|
|
200
216
|
* Selects members of an Entity and assembles the schema of the result. A
|
|
201
217
|
* relation selected with `true` yields an `EntityRef`; with a Selection of its
|
|
@@ -371,7 +387,10 @@ const input = (entity, schema, ...mapping) => {
|
|
|
371
387
|
const fields = entity.fields;
|
|
372
388
|
const members = mapValues(schema.fields, (_, key) => {
|
|
373
389
|
const member = own(given, key) ?? own(fields, key) ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
|
|
374
|
-
const owned =
|
|
390
|
+
const owned = Match.value(member).pipe(Match.tag("Field", (field) => field), Match.tags({
|
|
391
|
+
RelationInput: ({ relation }) => relation,
|
|
392
|
+
NestedInput: ({ relation }) => relation
|
|
393
|
+
}), Match.tag("Unmapped", () => void 0), Match.orElse(() => fail(entity, `input key "${key}" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`)));
|
|
375
394
|
if (owned !== void 0 && owned.owner.token !== entity.identity.token) fail(entity, `input key "${key}" is mapped to a member of "${owned.owner.name}"`);
|
|
376
395
|
if (member._tag === "NestedInput" && !isSameEntity(member.input.entity, member.relation.target())) fail(entity, `input key "${key}" nests an input of "${member.input.entity.name}", but "${member.relation.key}" is of "${member.relation.target().name}"`);
|
|
377
396
|
return member;
|
|
@@ -397,7 +416,12 @@ const fields = (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (
|
|
|
397
416
|
*/
|
|
398
417
|
const selectFor = (input, options = {}) => {
|
|
399
418
|
const members = input.members;
|
|
400
|
-
const spec = Object.fromEntries(Object.values(members).flatMap((member) =>
|
|
419
|
+
const spec = Object.fromEntries(Object.values(members).flatMap((member) => Match.valueTags(member, {
|
|
420
|
+
Field: ({ key }) => [[key, true]],
|
|
421
|
+
RelationInput: ({ relation }) => [[relation.key, true]],
|
|
422
|
+
NestedInput: ({ relation, input: nested }) => [[relation.key, selectFor(nested)]],
|
|
423
|
+
Unmapped: () => []
|
|
424
|
+
})));
|
|
401
425
|
return select(input.entity, {
|
|
402
426
|
...spec,
|
|
403
427
|
...options.also
|
|
@@ -414,7 +438,11 @@ const valuesFor = (input, value) => {
|
|
|
414
438
|
const idOf = (held) => held === null ? null : typeof held === "object" && "id" in held ? held.id : typeof held === "string" ? held : void 0;
|
|
415
439
|
const entries = Object.entries(members).flatMap(([key, member]) => {
|
|
416
440
|
if (member._tag === "Unmapped") return [];
|
|
417
|
-
const written =
|
|
441
|
+
const written = Match.valueTags(member, {
|
|
442
|
+
Field: ({ key: field }) => field,
|
|
443
|
+
RelationInput: ({ relation }) => relation.key,
|
|
444
|
+
NestedInput: ({ relation }) => relation.key
|
|
445
|
+
});
|
|
418
446
|
if (!(written in value)) return [];
|
|
419
447
|
const read = value[written];
|
|
420
448
|
switch (member._tag) {
|
|
@@ -431,6 +459,6 @@ const valuesFor = (input, value) => {
|
|
|
431
459
|
});
|
|
432
460
|
return Object.fromEntries(entries);
|
|
433
461
|
};
|
|
434
|
-
export { annotate, annotateMembers, cascading, check, define, defineVariants, derived, fields, input, invariant, invariants, isEntity as is, judge, judgeAgainst, judgeInput, page, readsBefore, relate, isSameEntity as same, select, selectFor, selectionSchema, sets, unmapped, valuesFor, variantsOf };
|
|
462
|
+
export { annotate, annotateMembers, cascading, check, clearing, define, defineVariants, derived, fields, input, invariant, invariants, isEntity as is, judge, judgeAgainst, judgeInput, page, readsBefore, relate, restricting, isSameEntity as same, select, selectFor, selectionSchema, sets, unmapped, valuesFor, variantsOf };
|
|
435
463
|
|
|
436
464
|
//# sourceMappingURL=entity.js.map
|
package/dist/entity.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity.js","names":["variantsOfIdentity"],"sources":["../src/entity.ts"],"sourcesContent":["/**\n * The `Entity` namespace: declaring Entities, their relations and derived\n * members, and Selections and inputs over them. An ES module rather than an\n * object, so a page keeps only the members it calls: one that declares and\n * reads Entities keeps none of the invariant judge or its expression\n * evaluator (#378).\n */\nimport { Option, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\nimport { extend, make, mapValues, partsOf, remake, variantBases } from './descriptor.js'\nimport type { OneRelation } from './expr.js'\nimport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\nimport {\n Derivation,\n type AnyEntity,\n type Cardinality,\n type DerivedSpec,\n type DerivedSpecs,\n type Entities,\n type Entity,\n type EntityDerived,\n type EntityField,\n type EntityIdentity,\n type EntityInput,\n type EntityMember,\n type EntityRelation,\n type EntitySets,\n type IdOf,\n type IdSchemaOf,\n type InputMember,\n type NestedInput,\n type PageWindow,\n type Related,\n type RelationInput,\n type RelationMap,\n type RelationSpec,\n type RelationSpecs,\n type Selection,\n type SelectionPage,\n type Unmapped,\n type VariantEntity,\n} from './index.js'\nimport { own, put } from './record.js'\nimport { checkedSet, type EntitySet, type SetOn } from './sets.js'\nimport { SchemaShape } from './shape.js'\nimport {\n declareVariants,\n registerVariants,\n variantsOf as variantsOfIdentity,\n type CheckCases,\n type EntityVariants,\n type StoredFields,\n type VariantCases,\n type VariantUnion,\n} from './variants.js'\n\n// What the signatures below check with. Not exported: a consumer's declaration\n// then writes out what one resolves to instead of naming a module the\n// package does not export.\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\n/** Unsatisfiable when a `Derived.count` or `Derived.exists` names a relation pointing at another Entity. */\ntype PointsHere<E extends AnyEntity, New extends DerivedSpecs> = {\n [K in keyof New]: New[K]['derives'] extends {\n readonly _tag: 'Count' | 'Exists'\n readonly relation: EntityRelation<any, any, infer Target, any, any>\n }\n ? [Target['name']] extends [E['name']]\n ? never\n : K\n : never\n}[keyof New] extends infer Wrong\n ? [Wrong] extends [never]\n ? unknown\n : { readonly countsRowsPointingAtAnotherEntity: Wrong }\n : never\n\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends VariantEntity<infer Name, infer Fields, infer R, infer D, infer U>\n ? VariantEntity<Name, Fields, R, D & New, U>\n : E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\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\ntype RefSchema<Target extends AnyEntity> = Schema.Struct<{\n readonly entity: Schema.Literal<Target['name']>\n readonly id: IdSchemaOf<Target>\n}>\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\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\n/** A variant Entity's cases, by tag, as the field sets of its union (`_tag` among them); never for one shape. */\ntype CaseFieldSets<E> = E extends {\n readonly variants: {\n readonly cases: infer C extends Readonly<\n Record<string, { readonly fields: Schema.Struct.Fields }>\n >\n }\n}\n ? { readonly [T in keyof C & string]: C[T]['fields'] }\n : never\n\n/** Whether `K` is a field only some cases have, selected without `_tag` to say which case a row is. */\ntype CaseOnlyWithoutTag<E extends AnyEntity, K, Spec> = [CaseFieldSets<E>] extends [never]\n ? false\n : '_tag' extends keyof Spec\n ? false\n : K extends keyof E['fields']\n ? K extends keyof CaseFieldSets<E>[keyof CaseFieldSets<E>]\n ? false\n : true\n : false\n\n/** `true` for any member; a relation also takes a Selection of its target. */\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 ? CaseOnlyWithoutTag<E, K, Spec> extends true\n ? `\"${K & string}\" is a field of some cases of ${E['name']}; select _tag with it`\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 FlatSelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>\n}>\n\n/** What one case holds of a Selection: the selected fields it has, as it holds them, and every other member. */\ntype CaseSelectionFields<E extends AnyEntity, Spec, Fields> = {\n readonly [\n K in Exclude<keyof Spec & keyof E['members'], '_tag'> as K extends keyof E['fields']\n ? K extends keyof Fields\n ? K\n : never\n : K\n ]: K extends keyof Fields ? Fields[K] : SelectedSchema<E['members'][K], Spec[K]>\n}\n\n/**\n * A Selection's schema: a Struct, or, for a variant Entity whose `_tag` is\n * selected, a tagged union with a case per variant.\n */\ntype SelectionSchema<E extends AnyEntity, Spec> = [CaseFieldSets<E>] extends [never]\n ? FlatSelectionSchema<E, Spec>\n : '_tag' extends keyof Spec\n ? Schema.TaggedUnion<{\n readonly [T in keyof CaseFieldSets<E> & string]: Schema.TaggedStruct<\n T,\n CaseSelectionFields<E, Spec, CaseFieldSets<E>[T]>\n >\n }>\n : FlatSelectionSchema<E, Spec>\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\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/**\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 ? Held<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\n/** The member each key of an input writes, as `Entity.input` reads it from a mapping. */\nexport type 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/** 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\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\n/**\n * The schema a Selection of `entity` reads, given each selected member's\n * schema by key: a Struct, or, for a variant Entity whose `_tag` is among\n * them, its tagged union (each case keeps the selected fields it has, as it\n * holds them). An interpreter that reads members its own way (Remote reads a\n * relation as a ref) builds a Selection's value with it.\n *\n * A variant Entity's Selection: with `_tag`, a tagged union whose cases hold\n * the selected fields they have, each as the case holds it, and every\n * selected relation and derived member; without it, the stored row's Struct,\n * refused when it selects a field only some cases have.\n */\nexport const selectionSchema = (\n entity: AnyEntity,\n selected: Readonly<Record<string, Schema.Constraint>>,\n): Schema.Top =>\n Option.match(variantsOfIdentity(entity.identity), {\n onNone: () => Schema.Struct(selected),\n onSome: variants => variantSelection(entity, variants, selected),\n })\n\nconst variantSelection = (\n entity: AnyEntity,\n variants: EntityVariants,\n selected: Readonly<Record<string, Schema.Constraint>>,\n): Schema.Top => {\n const caseOnly = (key: string) =>\n Object.hasOwn(entity.fields, key) &&\n key !== '_tag' &&\n variants.tags.some(tag => !Object.hasOwn(variants.cases[tag]!, key))\n if (!Object.hasOwn(selected, '_tag')) {\n const untold = Object.keys(selected).filter(caseOnly)\n if (untold.length > 0)\n fail(\n entity,\n `${untold.join(', ')} ${untold.length === 1 ? 'is a field' : 'are fields'} of some cases; select _tag with ${untold.length === 1 ? 'it' : 'them'}`,\n )\n return Schema.Struct(selected)\n }\n const cases: Record<string, Schema.Struct.Fields> = {}\n for (const tag of variants.tags) {\n const own = variants.cases[tag]!\n const fields: Record<string, Schema.Constraint> = {}\n for (const [key, schema] of Object.entries(selected)) {\n if (key === '_tag') continue\n if (!Object.hasOwn(entity.fields, key)) put(fields, key, schema)\n else if (Object.hasOwn(own, key)) put(fields, key, own[key]!)\n }\n put(cases, tag, fields)\n }\n return Schema.TaggedUnion(cases)\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/** For an input key that is about the operation rather than the Entity. */\nexport const unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\n/** True when both descriptors are versions of one Entity. */\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\n/** Declares an Entity from its intrinsic fields. Each call is a new identity. */\nexport const 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 annotated: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n}\n\n/**\n * Declares an Entity whose rows are one of several shapes, each case's fields\n * by its tag:\n *\n * ```ts\n * const Domain = Entity.defineVariants('Domain', {\n * Available: { ...DomainName.fields, ...DomainQuote.fields },\n * Unconfirmed: DomainName.fields,\n * })\n * Domain.variants.match(row, { Available: ({ price }) => price, Unconfirmed: () => 0 })\n * ```\n *\n * A row is `Domain.variants`, Effect's tagged union of the cases. The stored\n * row is `fields` and `schema`: `_tag`, the fields every case has, and each\n * other field nullable, null on a row of another case. Each case with fields\n * of its own gets an invariant saying so (`variant_Available`), which a\n * database binding writes as a CHECK. A key in several cases is one stored\n * field, so it is declared with one schema, spread into each case. Refused\n * here: fewer than two cases, a case declaring `_tag`, an optional key.\n */\nexport const defineVariants = <const Name extends string, const Cases extends VariantCases>(\n name: Name,\n cases: Cases & CheckCases<Cases>,\n): VariantEntity<Name, StoredFields<Cases>, {}, {}, VariantUnion<Cases>> => {\n const { fields, variants } = declareVariants(name, cases)\n const declared = define(name, Schema.Struct(fields))\n registerVariants(declared.identity, declared.schema, variants)\n // Made again so the descriptor reads the variants just registered.\n const entity = remake(declared, {})\n // Each case's invariant is built from it when first read (`Entity.invariants`).\n variantBases.set(entity.identity, entity)\n return entity as never\n}\n\n/**\n * An Entity's variants as an interpreter reads them: the union, each case's\n * fields, and the codec from a stored row to its case. None for an Entity of\n * one shape.\n */\nexport const variantsOf = (entity: AnyEntity): Option.Option<EntityVariants> =>\n variantsOfIdentity(entity.identity)\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 */\nexport const 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 (!Object.hasOwn(entities, owner))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n // Every relation is checked before any is added, so a refused call adds none.\n const additions: Array<readonly [AnyEntity, Readonly<Record<string, EntityMember>>]> = []\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = own(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 onDelete: spec.onDelete,\n authorizedBy: spec.authorizedBy,\n metadata: Metadata.empty,\n })\n },\n )\n additions.push([entity, added])\n put(related, ownerKey, entity)\n }\n for (const [entity, added] of additions) extend(entity, { relations: added })\n // Once every relation is added, so each target is the one `relate` returns.\n for (const [entity, added] of additions)\n for (const member of Object.values(added))\n if (member._tag === 'Relation' && Option.isSome(member.onDelete))\n cascadeInto(member.target().identity, { relation: member as OneRelation, owner: entity })\n return Object.freeze(related) as never\n}\n\n/** A `one` relation a delete cascades through, and the Entity that owns it, whose rows go. */\nexport interface Cascade {\n readonly relation: OneRelation\n readonly owner: AnyEntity\n}\n\nconst cascades = new WeakMap<EntityIdentity<string>, Array<Cascade>>()\nconst cascadeInto = (target: EntityIdentity<string>, cascade: Cascade): void => {\n const known = cascades.get(target) ?? []\n known.push(cascade)\n cascades.set(target, known)\n}\n\n/**\n * The `one` relations, of any Entity, declared `onDelete: 'cascade'` that point\n * at `entity`: deleting one of its rows deletes each row pointing at it through\n * one, and so on from those. The owner is the Entity as it was related, whose\n * members every descriptor of it shares.\n */\nexport const cascading = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n cascades.get(entity.identity) ?? []\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 */\nexport const 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 = own(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)) 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: selectionSchema(entity, 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 */\nexport const 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/**\n * Adds readable members that are not part of `entity.schema`. A\n * `Derived.count` or `Derived.exists` must read rows pointing at this\n * Entity: one over a relation to another is refused here, as is an exists\n * whose viewer is not another `one` relation of the same pointing Entity.\n */\nexport const derived =\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New> & PointsHere<E, New>): WithDerived<E, New> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n // The very spec added again (`Guards.may` on a second view of the Entity) is the member it added.\n const fresh: DerivedSpecs = Object.fromEntries(\n Object.entries(specs).filter(([key, spec]) => {\n const taken = own(members, key)\n return !(\n taken?._tag === 'Derived' &&\n taken.schema === spec.schema &&\n taken.derives === spec.derives\n )\n }),\n )\n assertFree(entity, Object.keys(fresh), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(fresh, (spec, key) => {\n const pointingHere = (relation: OneRelation, verb: string): void => {\n if (relation.cardinality !== 'one')\n fail(\n entity,\n `\"${key}\" ${verb} \"${relation.key}\", a many relation; name a one relation that points here`,\n )\n if (!isSameEntity(relation.target(), entity))\n fail(\n entity,\n `\"${key}\" ${verb} \"${relation.owner.name}.${relation.key}\", which points at ${relation.target().name}`,\n )\n }\n Derivation.$match(spec.derives, {\n Supplied: () => undefined,\n Count: ({ relation }) => pointingHere(relation, 'counts'),\n Exists: ({ relation, viewer }) => {\n pointingHere(relation, 'reads')\n if (viewer.owner.token !== relation.owner.token || viewer.key === relation.key)\n fail(\n entity,\n `\"${key}\"'s viewer \"${viewer.owner.name}.${viewer.key}\" must be another one relation of ${relation.owner.name}`,\n )\n },\n })\n return Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n derives: spec.derives,\n metadata: Metadata.empty,\n })\n })\n extend(entity, { derived: added })\n return entity as never\n }\n\n/**\n * Says which members take their value from the write's context, never its\n * input: `Expr.viewer(User)`, whoever asks (a `one` relation to a User, or a\n * field holding their id), and `Expr.now`, when (a field stored as a\n * number). `on` says which writes set them: `'create'`, every insert, or\n * `'write'`, every insert and every update.\n *\n * ```ts\n * const Post = Blog.Post.pipe(\n * Entity.sets({ author: Expr.viewer(User), createdAt: Expr.now }, { on: 'create' }),\n * Entity.sets({ editedAt: Expr.now }, { on: 'write' }),\n * )\n * ```\n *\n * Every write of the Entity follows from it: a server writes the values and\n * a client predicts them, and a write whose input sets one is refused where\n * it is declared. Refused here: the id, a member set already, a `many`\n * relation, a relation set to anything but the viewer of its target, and a\n * field that cannot hold its value. Added after `Entity.relate` to set a\n * relation.\n */\nexport const sets =\n <E extends AnyEntity>(values: EntitySets<E>, options: { readonly on: SetOn }) =>\n (entity: E): E => {\n const given: Readonly<Record<string, unknown>> = values\n const added: Record<string, EntitySet> = {}\n for (const [key, value] of Object.entries(given)) {\n if (value === undefined) continue\n put(added, key, checkedSet(entity, key, value, options.on))\n }\n extend(entity, { sets: added })\n return entity\n }\n\n/** Attaches an interpreter's metadata to the Entity itself. */\nexport const annotate =\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n remake(entity, { metadata: Metadata.combine([entity.metadata, metadata]) }) as E\n\n/** Attaches an interpreter's metadata to members, by key. */\nexport const 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 parts = partsOf.get(entity)!\n const fields = mapValues(entity.fields, (member: EntityMember, key) => {\n const extra = own(given, key)\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n // A relation or derived member is the Entity's own, so its metadata here is this descriptor's.\n const annotated: Record<string, Metadata> = { ...parts.annotated }\n for (const [key, extra] of Object.entries(given)) {\n if (extra === undefined || Object.hasOwn(entity.fields, key)) continue\n const earlier = own(parts.annotated, key)\n put(annotated, key, earlier === undefined ? extra : Metadata.combine([earlier, extra]))\n }\n return remake(entity, { fields, annotated }) 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 */\nexport const 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 (!Object.hasOwn(schema.fields, key))\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 own(given, key) ??\n own(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/**\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 */\nexport const fields = <\n E extends AnyEntity,\n const Keys extends ReadonlyArray<keyof E['fields'] & string>,\n>(\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 own(\n entity.fields as Readonly<Record<string, EntityField<string, string, Schema.Constraint>>>,\n key,\n ) ?? 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 * `also` names members to read beside them, each with `true` (what a lock\n * reads). The Selection is typed as the input's alone: what it reads has\n * those members, and these besides.\n */\nexport const selectFor = <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n options: { readonly also?: Readonly<Record<string, true>> | undefined } = {},\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, selectFor(member.input)]]\n : [],\n ),\n )\n return select(input.entity, { ...spec, ...options.also } 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 */\nexport const 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 ? 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\nexport { isEntity as is, isSameEntity as same }\nexport {\n check,\n invariant,\n invariantsOf as invariants,\n judge,\n judgeAgainst,\n judgeInput,\n readsBefore,\n} from './invariant.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8UA,MAAM,cAAc,WAAkC;CAEpD,MAAM,KAD6D,OAAO,OACxD;CAClB,IAAI,OAAO,KAAA,KAAa,GAAG,SAAS,SAAS,OAAO,OAAO;CAC3D,MAAM,OAAO,OAAO,OAAO,GAAG,MAAoB;CAClD,OAAO,YAAY,OAAO,KAAK,GAAG,IAAI,OAAO,OAAO;AACtD;;;;;;;;;;;;;AAcA,MAAa,mBACX,QACA,aAEA,OAAO,MAAMA,aAAmB,OAAO,QAAQ,GAAG;CAChD,cAAc,OAAO,OAAO,QAAQ;CACpC,SAAQ,aAAY,iBAAiB,QAAQ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SAAS,OACjC,UAAU,OAAO,OAAO,IAAyC,IACjE;IACN,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,CAAU;GAC/E;GACA,KAAK,iBAAiB;IACpB,MAAM,MAAM,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;IAG5D,QADc,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,SAAS,KAAA,CAAS,IAAI,QAAQ,KAAA,KACvD,CAAC,CAAC,KAAK,GAAG,CAAU,IAAI,CAAC;GAC1C;EACF;CACF,CAAC;CACD,OAAO,OAAO,YAAY,OAAO;AACnC"}
|
|
1
|
+
{"version":3,"file":"entity.js","names":["variantsOfIdentity"],"sources":["../src/entity.ts"],"sourcesContent":["/**\n * The `Entity` namespace: declaring Entities, their relations and derived\n * members, and Selections and inputs over them. An ES module rather than an\n * object, so a page keeps only the members it calls: one that declares and\n * reads Entities keeps none of the invariant judge or its expression\n * evaluator (#378).\n */\nimport { Match, Option, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\nimport { extend, make, mapValues, partsOf, remake, variantBases } from './descriptor.js'\nimport type { OneRelation } from './expr.js'\nimport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\nimport {\n Derivation,\n type AnyEntity,\n type Cardinality,\n type DerivedSpec,\n type DerivedSpecs,\n type Entities,\n type Entity,\n type EntityDerived,\n type EntityField,\n type EntityIdentity,\n type EntityInput,\n type EntityMember,\n type EntityRelation,\n type EntitySets,\n type IdOf,\n type IdSchemaOf,\n type InputMember,\n type NestedInput,\n type OnDelete,\n type PageWindow,\n type Related,\n type RelationInput,\n type RelationMap,\n type RelationSpec,\n type RelationSpecs,\n type Selection,\n type SelectionPage,\n type Unmapped,\n type VariantEntity,\n} from './index.js'\nimport { own, put } from './record.js'\nimport { checkedSet, type EntitySet, type SetOn } from './sets.js'\nimport { SchemaShape } from './shape.js'\nimport {\n declareVariants,\n registerVariants,\n variantsOf as variantsOfIdentity,\n type CheckCases,\n type EntityVariants,\n type StoredFields,\n type VariantCases,\n type VariantUnion,\n} from './variants.js'\n\n// What the signatures below check with. Not exported: a consumer's declaration\n// then writes out what one resolves to instead of naming a module the\n// package does not export.\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\n/** Unsatisfiable when a `Derived.count` or `Derived.exists` names a relation pointing at another Entity. */\ntype PointsHere<E extends AnyEntity, New extends DerivedSpecs> = {\n [K in keyof New]: New[K]['derives'] extends {\n readonly _tag: 'Count' | 'Exists'\n readonly relation: EntityRelation<any, any, infer Target, any, any>\n }\n ? [Target['name']] extends [E['name']]\n ? never\n : K\n : never\n}[keyof New] extends infer Wrong\n ? [Wrong] extends [never]\n ? unknown\n : { readonly countsRowsPointingAtAnotherEntity: Wrong }\n : never\n\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends VariantEntity<infer Name, infer Fields, infer R, infer D, infer U>\n ? VariantEntity<Name, Fields, R, D & New, U>\n : E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\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\ntype RefSchema<Target extends AnyEntity> = Schema.Struct<{\n readonly entity: Schema.Literal<Target['name']>\n readonly id: IdSchemaOf<Target>\n}>\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\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\n/** A variant Entity's cases, by tag, as the field sets of its union (`_tag` among them); never for one shape. */\ntype CaseFieldSets<E> = E extends {\n readonly variants: {\n readonly cases: infer C extends Readonly<\n Record<string, { readonly fields: Schema.Struct.Fields }>\n >\n }\n}\n ? { readonly [T in keyof C & string]: C[T]['fields'] }\n : never\n\n/** Whether `K` is a field only some cases have, selected without `_tag` to say which case a row is. */\ntype CaseOnlyWithoutTag<E extends AnyEntity, K, Spec> = [CaseFieldSets<E>] extends [never]\n ? false\n : '_tag' extends keyof Spec\n ? false\n : K extends keyof E['fields']\n ? K extends keyof CaseFieldSets<E>[keyof CaseFieldSets<E>]\n ? false\n : true\n : false\n\n/** `true` for any member; a relation also takes a Selection of its target. */\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 ? CaseOnlyWithoutTag<E, K, Spec> extends true\n ? `\"${K & string}\" is a field of some cases of ${E['name']}; select _tag with it`\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 FlatSelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>\n}>\n\n/** What one case holds of a Selection: the selected fields it has, as it holds them, and every other member. */\ntype CaseSelectionFields<E extends AnyEntity, Spec, Fields> = {\n readonly [\n K in Exclude<keyof Spec & keyof E['members'], '_tag'> as K extends keyof E['fields']\n ? K extends keyof Fields\n ? K\n : never\n : K\n ]: K extends keyof Fields ? Fields[K] : SelectedSchema<E['members'][K], Spec[K]>\n}\n\n/**\n * A Selection's schema: a Struct, or, for a variant Entity whose `_tag` is\n * selected, a tagged union with a case per variant.\n */\ntype SelectionSchema<E extends AnyEntity, Spec> = [CaseFieldSets<E>] extends [never]\n ? FlatSelectionSchema<E, Spec>\n : '_tag' extends keyof Spec\n ? Schema.TaggedUnion<{\n readonly [T in keyof CaseFieldSets<E> & string]: Schema.TaggedStruct<\n T,\n CaseSelectionFields<E, Spec, CaseFieldSets<E>[T]>\n >\n }>\n : FlatSelectionSchema<E, Spec>\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\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/**\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 ? Held<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\n/** The member each key of an input writes, as `Entity.input` reads it from a mapping. */\nexport type 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/** 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\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\n/**\n * The schema a Selection of `entity` reads, given each selected member's\n * schema by key: a Struct, or, for a variant Entity whose `_tag` is among\n * them, its tagged union (each case keeps the selected fields it has, as it\n * holds them). An interpreter that reads members its own way (Remote reads a\n * relation as a ref) builds a Selection's value with it.\n *\n * A variant Entity's Selection: with `_tag`, a tagged union whose cases hold\n * the selected fields they have, each as the case holds it, and every\n * selected relation and derived member; without it, the stored row's Struct,\n * refused when it selects a field only some cases have.\n */\nexport const selectionSchema = (\n entity: AnyEntity,\n selected: Readonly<Record<string, Schema.Constraint>>,\n): Schema.Top =>\n Option.match(variantsOfIdentity(entity.identity), {\n onNone: () => Schema.Struct(selected),\n onSome: variants => variantSelection(entity, variants, selected),\n })\n\nconst variantSelection = (\n entity: AnyEntity,\n variants: EntityVariants,\n selected: Readonly<Record<string, Schema.Constraint>>,\n): Schema.Top => {\n const caseOnly = (key: string) =>\n Object.hasOwn(entity.fields, key) &&\n key !== '_tag' &&\n variants.tags.some(tag => !Object.hasOwn(variants.cases[tag]!, key))\n if (!Object.hasOwn(selected, '_tag')) {\n const untold = Object.keys(selected).filter(caseOnly)\n if (untold.length > 0)\n fail(\n entity,\n `${untold.join(', ')} ${untold.length === 1 ? 'is a field' : 'are fields'} of some cases; select _tag with ${untold.length === 1 ? 'it' : 'them'}`,\n )\n return Schema.Struct(selected)\n }\n const cases: Record<string, Schema.Struct.Fields> = {}\n for (const tag of variants.tags) {\n const own = variants.cases[tag]!\n const fields: Record<string, Schema.Constraint> = {}\n for (const [key, schema] of Object.entries(selected)) {\n if (key === '_tag') continue\n if (!Object.hasOwn(entity.fields, key)) put(fields, key, schema)\n else if (Object.hasOwn(own, key)) put(fields, key, own[key]!)\n }\n put(cases, tag, fields)\n }\n return Schema.TaggedUnion(cases)\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/** For an input key that is about the operation rather than the Entity. */\nexport const unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\n/** True when both descriptors are versions of one Entity. */\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\n/** Declares an Entity from its intrinsic fields. Each call is a new identity. */\nexport const 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 annotated: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n}\n\n/**\n * Declares an Entity whose rows are one of several shapes, each case's fields\n * by its tag:\n *\n * ```ts\n * const Domain = Entity.defineVariants('Domain', {\n * Available: { ...DomainName.fields, ...DomainQuote.fields },\n * Unconfirmed: DomainName.fields,\n * })\n * Domain.variants.match(row, { Available: ({ price }) => price, Unconfirmed: () => 0 })\n * ```\n *\n * A row is `Domain.variants`, Effect's tagged union of the cases. The stored\n * row is `fields` and `schema`: `_tag`, the fields every case has, and each\n * other field nullable, null on a row of another case. Each case with fields\n * of its own gets an invariant saying so (`variant_Available`), which a\n * database binding writes as a CHECK. A key in several cases is one stored\n * field, so it is declared with one schema, spread into each case. Refused\n * here: fewer than two cases, a case declaring `_tag`, an optional key.\n */\nexport const defineVariants = <const Name extends string, const Cases extends VariantCases>(\n name: Name,\n cases: Cases & CheckCases<Cases>,\n): VariantEntity<Name, StoredFields<Cases>, {}, {}, VariantUnion<Cases>> => {\n const { fields, variants } = declareVariants(name, cases)\n const declared = define(name, Schema.Struct(fields))\n registerVariants(declared.identity, declared.schema, variants)\n // Made again so the descriptor reads the variants just registered.\n const entity = remake(declared, {})\n // Each case's invariant is built from it when first read (`Entity.invariants`).\n variantBases.set(entity.identity, entity)\n return entity as never\n}\n\n/**\n * An Entity's variants as an interpreter reads them: the union, each case's\n * fields, and the codec from a stored row to its case. None for an Entity of\n * one shape.\n */\nexport const variantsOf = (entity: AnyEntity): Option.Option<EntityVariants> =>\n variantsOfIdentity(entity.identity)\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 */\nexport const 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 (!Object.hasOwn(entities, owner))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n // Every relation is checked before any is added, so a refused call adds none.\n const additions: Array<readonly [AnyEntity, Readonly<Record<string, EntityMember>>]> = []\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = own(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 onDelete: spec.onDelete,\n authorizedBy: spec.authorizedBy,\n metadata: Metadata.empty,\n })\n },\n )\n additions.push([entity, added])\n put(related, ownerKey, entity)\n }\n for (const [entity, added] of additions) extend(entity, { relations: added })\n // Once every relation is added, so each target is the one `relate` returns.\n for (const [entity, added] of additions)\n for (const member of Object.values(added))\n if (member._tag === 'Relation' && Option.isSome(member.onDelete))\n pointInto(member.onDelete.value, member.target().identity, {\n relation: member as OneRelation,\n owner: entity,\n })\n return Object.freeze(related) as never\n}\n\n/** A `one` relation a delete acts through (it cascades, restricts or clears), and the Entity that owns it. */\nexport interface Cascade {\n readonly relation: OneRelation\n readonly owner: AnyEntity\n}\n\nconst pointing: Readonly<Record<OnDelete, WeakMap<EntityIdentity<string>, Array<Cascade>>>> = {\n cascade: new WeakMap(),\n restrict: new WeakMap(),\n setNull: new WeakMap(),\n}\nconst pointInto = (action: OnDelete, target: EntityIdentity<string>, edge: Cascade): void => {\n const known = pointing[action].get(target) ?? []\n known.push(edge)\n pointing[action].set(target, known)\n}\n\n/**\n * The `one` relations, of any Entity, declared `onDelete: 'cascade'` that point\n * at `entity`: deleting one of its rows deletes each row pointing at it through\n * one, and so on from those. The owner is the Entity as it was related, whose\n * members every descriptor of it shares.\n */\nexport const cascading = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n pointing.cascade.get(entity.identity) ?? []\n\n/**\n * The `one` relations, of any Entity, declared `onDelete: 'restrict'` that\n * point at `entity`: a delete of one of its rows is refused while a row points\n * at it through one (#467).\n */\nexport const restricting = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n pointing.restrict.get(entity.identity) ?? []\n\n/**\n * The optional `one` relations, of any Entity, declared `onDelete: 'setNull'`\n * that point at `entity`: deleting one of its rows clears the link on each row\n * pointing at it through one, which stays (#467).\n */\nexport const clearing = (entity: AnyEntity): ReadonlyArray<Cascade> =>\n pointing.setNull.get(entity.identity) ?? []\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 */\nexport const 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 = own(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)) 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: selectionSchema(entity, 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 */\nexport const 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/**\n * Adds readable members that are not part of `entity.schema`. A\n * `Derived.count` or `Derived.exists` must read rows pointing at this\n * Entity: one over a relation to another is refused here, as is an exists\n * whose viewer is not another `one` relation of the same pointing Entity.\n */\nexport const derived =\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New> & PointsHere<E, New>): WithDerived<E, New> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n // The very spec added again (`Guards.may` on a second view of the Entity) is the member it added.\n const fresh: DerivedSpecs = Object.fromEntries(\n Object.entries(specs).filter(([key, spec]) => {\n const taken = own(members, key)\n return !(\n taken?._tag === 'Derived' &&\n taken.schema === spec.schema &&\n taken.derives === spec.derives\n )\n }),\n )\n assertFree(entity, Object.keys(fresh), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(fresh, (spec, key) => {\n const pointingHere = (relation: OneRelation, verb: string): void => {\n if (relation.cardinality !== 'one')\n fail(\n entity,\n `\"${key}\" ${verb} \"${relation.key}\", a many relation; name a one relation that points here`,\n )\n if (!isSameEntity(relation.target(), entity))\n fail(\n entity,\n `\"${key}\" ${verb} \"${relation.owner.name}.${relation.key}\", which points at ${relation.target().name}`,\n )\n }\n Derivation.$match(spec.derives, {\n Supplied: () => undefined,\n Count: ({ relation }) => pointingHere(relation, 'counts'),\n Exists: ({ relation, viewer }) => {\n pointingHere(relation, 'reads')\n if (viewer.owner.token !== relation.owner.token || viewer.key === relation.key)\n fail(\n entity,\n `\"${key}\"'s viewer \"${viewer.owner.name}.${viewer.key}\" must be another one relation of ${relation.owner.name}`,\n )\n },\n })\n return Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n derives: spec.derives,\n metadata: Metadata.empty,\n })\n })\n extend(entity, { derived: added })\n return entity as never\n }\n\n/**\n * Says which members take their value from the write's context, never its\n * input: `Expr.viewer(User)`, whoever asks (a `one` relation to a User, or a\n * field holding their id), and `Expr.now`, when (a field stored as a\n * number). `on` says which writes set them: `'create'`, every insert, or\n * `'write'`, every insert and every update.\n *\n * ```ts\n * const Post = Blog.Post.pipe(\n * Entity.sets({ author: Expr.viewer(User), createdAt: Expr.now }, { on: 'create' }),\n * Entity.sets({ editedAt: Expr.now }, { on: 'write' }),\n * )\n * ```\n *\n * Every write of the Entity follows from it: a server writes the values and\n * a client predicts them, and a write whose input sets one is refused where\n * it is declared. Refused here: the id, a member set already, a `many`\n * relation, a relation set to anything but the viewer of its target, and a\n * field that cannot hold its value. Added after `Entity.relate` to set a\n * relation.\n */\nexport const sets =\n <E extends AnyEntity>(values: EntitySets<E>, options: { readonly on: SetOn }) =>\n (entity: E): E => {\n const given: Readonly<Record<string, unknown>> = values\n const added: Record<string, EntitySet> = {}\n for (const [key, value] of Object.entries(given)) {\n if (value === undefined) continue\n put(added, key, checkedSet(entity, key, value, options.on))\n }\n extend(entity, { sets: added })\n return entity\n }\n\n/** Attaches an interpreter's metadata to the Entity itself. */\nexport const annotate =\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n remake(entity, { metadata: Metadata.combine([entity.metadata, metadata]) }) as E\n\n/** Attaches an interpreter's metadata to members, by key. */\nexport const 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 parts = partsOf.get(entity)!\n const fields = mapValues(entity.fields, (member: EntityMember, key) => {\n const extra = own(given, key)\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n // A relation or derived member is the Entity's own, so its metadata here is this descriptor's.\n const annotated: Record<string, Metadata> = { ...parts.annotated }\n for (const [key, extra] of Object.entries(given)) {\n if (extra === undefined || Object.hasOwn(entity.fields, key)) continue\n const earlier = own(parts.annotated, key)\n put(annotated, key, earlier === undefined ? extra : Metadata.combine([earlier, extra]))\n }\n return remake(entity, { fields, annotated }) 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 */\nexport const 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 (!Object.hasOwn(schema.fields, key))\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 own(given, key) ??\n own(fields, key) ??\n fail(entity, `input key \"${key}\" names no field; map it to a member or Entity.unmapped`)\n const owned = Match.value(member).pipe(\n Match.tag('Field', field => field),\n Match.tags({\n RelationInput: ({ relation }) => relation,\n NestedInput: ({ relation }) => relation,\n }),\n Match.tag('Unmapped', () => undefined),\n Match.orElse(() =>\n fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n ),\n ),\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/**\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 */\nexport const fields = <\n E extends AnyEntity,\n const Keys extends ReadonlyArray<keyof E['fields'] & string>,\n>(\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 own(\n entity.fields as Readonly<Record<string, EntityField<string, string, Schema.Constraint>>>,\n key,\n ) ?? 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 * `also` names members to read beside them, each with `true` (what a lock\n * reads). The Selection is typed as the input's alone: what it reads has\n * those members, and these besides.\n */\nexport const selectFor = <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n options: { readonly also?: Readonly<Record<string, true>> | undefined } = {},\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 Match.valueTags(member, {\n Field: ({ key }) => [[key, true] as const],\n RelationInput: ({ relation }) => [[relation.key, true] as const],\n // What the nested input writes of the target, so its keys can be shown too.\n NestedInput: ({ relation, input: nested }) => [[relation.key, selectFor(nested)] as const],\n Unmapped: () => [],\n }),\n ),\n )\n return select(input.entity, { ...spec, ...options.also } 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 */\nexport const 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 = Match.valueTags(member, {\n Field: ({ key: field }) => field,\n RelationInput: ({ relation }) => relation.key,\n NestedInput: ({ relation }) => relation.key,\n })\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 ? 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\nexport { isEntity as is, isSameEntity as same }\nexport {\n check,\n invariant,\n invariantsOf as invariants,\n judge,\n judgeAgainst,\n judgeInput,\n readsBefore,\n} from './invariant.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+UA,MAAM,cAAc,WAAkC;CAEpD,MAAM,KAD6D,OAAO,OACxD;CAClB,IAAI,OAAO,KAAA,KAAa,GAAG,SAAS,SAAS,OAAO,OAAO;CAC3D,MAAM,OAAO,OAAO,OAAO,GAAG,MAAoB;CAClD,OAAO,YAAY,OAAO,KAAK,GAAG,IAAI,OAAO,OAAO;AACtD;;;;;;;;;;;;;AAcA,MAAa,mBACX,QACA,aAEA,OAAO,MAAMA,aAAmB,OAAO,QAAQ,GAAG;CAChD,cAAc,OAAO,OAAO,QAAQ;CACpC,SAAQ,aAAY,iBAAiB,QAAQ,UAAU,QAAQ;AACjE,CAAC;AAEH,MAAM,oBACJ,QACA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M,UAAU,OAAO,QAAQ,OAAO,CAAC,CAAC,SAAS,CAAC,KAAK,YAAY;EACjE,IAAI,OAAO,SAAS,YAAY,OAAO,CAAC;EACxC,MAAM,UAAU,MAAM,UAAU,QAAQ;GACtC,QAAQ,EAAE,KAAK,YAAY;GAC3B,gBAAgB,EAAE,eAAe,SAAS;GAC1C,cAAc,EAAE,eAAe,SAAS;EAC1C,CAAC;EACD,IAAI,EAAE,WAAW,QAAQ,OAAO,CAAC;EACjC,MAAM,OAAO,MAAM;EACnB,QAAQ,OAAO,MAAf;GACE,KAAK,SACH,OAAO,CAAC,CAAC,KAAK,IAAI,CAAU;GAC9B,KAAK,eAAe;IAClB,MAAM,UAAU,SACd,OAAO,SAAS,YAAY,SAAS,OACjC,UAAU,OAAO,OAAO,IAAyC,IACjE;IACN,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,CAAU;GAC/E;GACA,KAAK,iBAAiB;IACpB,MAAM,MAAM,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;IAG5D,QADc,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,SAAS,KAAA,CAAS,IAAI,QAAQ,KAAA,KACvD,CAAC,CAAC,KAAK,GAAG,CAAU,IAAI,CAAC;GAC1C;EACF;CACF,CAAC;CACD,OAAO,OAAO,YAAY,OAAO;AACnC"}
|
package/dist/evaluate.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ import { Option } from "effect";
|
|
|
2
2
|
import { Collation } from "./collation.js";
|
|
3
3
|
import { AnyQuery, Operandish, Operation, OperatorDescriptor, OperatorTable, OrderTerm, Predicate } from "./expr.js";
|
|
4
4
|
import { HeldRow, HeldRows, Pinned } from "./held.js";
|
|
5
|
-
import { MemoryOperators } from "./operators.js";
|
|
6
5
|
import { ExprContext, NowExpr, ViewerExpr } from "./context.js";
|
|
6
|
+
import { MemoryOperators } from "./operators.js";
|
|
7
7
|
/** A row as this interpreter reads one: values by field key. */
|
|
8
8
|
export type Row = Readonly<Record<string, unknown>>;
|
|
9
9
|
export declare class QueryEvaluateError extends Error {
|
package/dist/evaluate.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evaluate.d.ts","names":[],"sources":["../src/evaluate.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"evaluate.d.ts","names":[],"sources":["../src/evaluate.ts"],"mappings":";;;;;;;YAkDY,MAAM,SAAS;qBAEd,2BAA2B;EACtC,YAAY;;;;;;;qBAWD,6BAA6B;WAC/B,UAAU;;WAEV;;EAET,YAAY,UAAU,oBAAoB,YAAW;;;;;;qBAyC1C,4BAA4B;EACvC,YAAY,MAAM,sBAAsB,kBAAkB;;;iBAyF3C;WACN,MAAM;WACN;;;;;;;qBAiIE,yBAAyB;EACpC,YAAY;;;;;;;qBA+GD,gBAAa,UACd,oBAAkB,QACpB,wBAAsB;WAEnB,WAAW,OAAO,OAAO;WACzB,WAAW;;;KA+BnB;;;;;;;;qBAoDQ,iBAAc,MACnB,YAAU;WAEL,QAAQ;WACR,YAAY;WACZ,UAAU;;;YAsMX,iBAAiB;;;;;;;;qBAYhB,UAAO,MACZ,WAAS,OACR,KAAG,YACC,iBAAe,UAChB,gBACT,OAAO,OAAO;;qBA8BJ,YAAS,MACd,WAAS,KACV,KAAG,QACD,KAAG,OACJ,KAAG,YACE,oBACV;;;;;;YAiBS,QAAQ,IAAI;WACT;WAAwB,OAAO;;WAC/B;WAA0B;;;UAM/B;WACC,QAAQ;WACR,YAAY;;WAEZ,UAAU;;;;;WAKV,OAAO;;;;;;;;;qBAqBL;;EAEX,YAAS,WACI,WAAS,KACf,SAAO,UACH;aAA0B,OAAO;QACzC;;;;;;;;;EAqBH,QAAK,MACG,UAAQ,OACP,KAAG,KACL,SAAO,UACH,KAAK;aAAoC;QACjD;;;;;;;;EAgCH,OAAI,YACU,cAAc,YAAU;aA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