foldkit-entity 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +128 -17
  2. package/dist/conformance/index.d.ts.map +1 -1
  3. package/dist/conformance/index.js +20 -0
  4. package/dist/conformance/index.js.map +1 -1
  5. package/dist/conformance/operator.d.ts.map +1 -1
  6. package/dist/conformance/operator.js +13 -4
  7. package/dist/conformance/operator.js.map +1 -1
  8. package/dist/entity.d.ts +14 -2
  9. package/dist/entity.d.ts.map +1 -1
  10. package/dist/entity.js +41 -12
  11. package/dist/entity.js.map +1 -1
  12. package/dist/evaluate.d.ts +1 -1
  13. package/dist/evaluate.d.ts.map +1 -1
  14. package/dist/evaluate.js +22 -18
  15. package/dist/evaluate.js.map +1 -1
  16. package/dist/expr.d.ts +70 -20
  17. package/dist/expr.d.ts.map +1 -1
  18. package/dist/expr.js +67 -47
  19. package/dist/expr.js.map +1 -1
  20. package/dist/held.js +11 -3
  21. package/dist/held.js.map +1 -1
  22. package/dist/index.d.ts +38 -6
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +9 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/invariant.d.ts.map +1 -1
  27. package/dist/invariant.js +26 -20
  28. package/dist/invariant.js.map +1 -1
  29. package/dist/law.d.ts.map +1 -1
  30. package/dist/law.js +3 -9
  31. package/dist/law.js.map +1 -1
  32. package/dist/lawCore.d.ts +42 -0
  33. package/dist/lawCore.d.ts.map +1 -0
  34. package/dist/lawCore.js +12 -0
  35. package/dist/lawCore.js.map +1 -0
  36. package/dist/memoryTable.d.ts +11 -0
  37. package/dist/memoryTable.d.ts.map +1 -0
  38. package/dist/memoryTable.js +69 -0
  39. package/dist/memoryTable.js.map +1 -0
  40. package/dist/operators.d.ts.map +1 -1
  41. package/dist/operators.js +2 -66
  42. package/dist/operators.js.map +1 -1
  43. package/dist/sets.js.map +1 -1
  44. package/dist/write.d.ts +1 -1
  45. package/dist/write.d.ts.map +1 -1
  46. package/dist/write.js +40 -18
  47. package/dist/write.js.map +1 -1
  48. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"invariant.js","names":[],"sources":["../src/invariant.ts"],"sourcesContent":["/**\n * Invariants: what every stored row of an Entity must hold, and what every\n * change of one must, declared once on the Entity through its metadata and read\n * from there by each interpreter: the reference judge here, a Schema check, a\n * form, a server's writer.\n *\n * One is built over the row before a write (`before`, each field as `Expr.field`) and\n * the row after it (`after`, each field as `Expr.next`); each `one` relation is\n * there too, as the id it points at, so a judged row holds it as that id. What\n * it reads decides when it is judged:\n *\n * ```text\n * reads `after` only -> a state invariant: every create and update, a CHECK constraint\n * reads `before` too -> a transition invariant: every update, which has a row before\n * ```\n *\n * It reads no input and no principal. Who may write is a guard's; whether a\n * write applies now is its `when`'s.\n */\nimport { Metadata } from 'foldkit-metadata'\nimport { Option, Schema, type SchemaAST } from 'effect'\nimport { OperatorMissingError, truthOver, type Row } from './evaluate.js'\nimport { Operators, type MemoryOperators } from './operators.js'\nimport { put } from './record.js'\nimport {\n Expr,\n Query,\n dependenciesOf,\n type FieldExpr,\n type NextExpr,\n type OneRelation,\n type Predicate,\n type Reads,\n} from './expr.js'\nimport { remake, variantBases } from './descriptor.js'\nimport type {\n AnyEntity,\n EntityField,\n EntityIdentity,\n EntityInput,\n EntityMember,\n InputMember,\n} from './index.js'\nimport { storesNull, variantsOf } from './variants.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\n\n/** One invariant of an Entity, as its interpreters read it. */\nexport interface Invariant {\n /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */\n readonly id: string\n /** The Entity it is declared on: ids are unique only within one, so a refusal names both. */\n readonly entity: string\n readonly predicate: Predicate\n /** What someone the rules let write is told when a write would break it. */\n readonly message: string\n /** The members a form shows the failure beside. */\n readonly path: ReadonlyArray<string>\n /** The members it reads of the row before a write (fields, `one` relations); none for a state invariant. */\n readonly before: ReadonlyArray<string>\n /** The members it reads of the row after. */\n readonly after: ReadonlyArray<string>\n}\n\n/** The keys of an Entity's `one` relations: what a row holds as the id each points at. */\ntype LinkKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/** The id a `one` relation points at, as a row holds it: null for an optional one pointing nowhere. */\ntype LinkOf<\n E extends AnyEntity,\n K extends keyof E['relations'],\n> = E['relations'][K]['optional'] extends true ? string | null : string\n\n/**\n * Each field as the row before a write holds it, and each `one` relation as\n * the id it points at: what an invariant reads as `before`. Encoded, as the\n * store holds it and the judge reads it, so a literal is written so too (a\n * date as its ISO text).\n */\nexport type BeforeRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: FieldExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: FieldExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** Each field, and each `one` relation's id, as the row after a write holds it: `after`. */\nexport type AfterRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: NextExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: NextExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** A row, or a change from one row to another, as an invariant is judged over it. */\nexport interface Change {\n readonly after: Row\n /** The row before an update; none for a create, which judges no transition invariant. */\n readonly before?: Row\n}\n\nconst Invariants = Metadata.key<Invariant>('foldkit-entity/invariants', {\n // The same invariant reached twice (two annotated copies combined) is one.\n merge: values => [...new Set(values)],\n summarize: invariant => invariant.id,\n})\n\n/** What a row, or a change, comes to under an Entity's invariants. */\nexport type Judgement =\n | { readonly _tag: 'Valid' }\n | { readonly _tag: 'Invalid'; readonly failures: ReadonlyArray<Invariant> }\n /**\n * Validity is not known: some invariant reads a field the row does not have\n * (`fields`), or calls an operator the table does not run (`operators`, by name).\n */\n | {\n readonly _tag: 'Undecided'\n readonly fields: ReadonlyArray<string>\n readonly operators: ReadonlyArray<string>\n }\n\n/** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */\nexport const readsBefore = (held: Invariant): boolean => held.before.length > 0\n\n/**\n * An invariant as declared: the step that attaches it to its Entity, carrying\n * its id and, once attached, that Entity's name, so a refusal is matched\n * against the declaration rather than a string spelled again\n * (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`). An id is unique\n * only within an Entity, so the name is part of what a refusal names; reading\n * it before the declaration is attached throws.\n */\nexport interface DeclaredInvariant<E extends AnyEntity> {\n (entity: E): E\n readonly id: string\n readonly entity: string\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`)\n}\n\n/** How an invariant is declared: what `build` returns over the rows, and what a failure says. */\ntype Build<E extends AnyEntity> = (rows: {\n readonly before: BeforeRow<E>\n readonly after: AfterRow<E>\n}) => Predicate & Reads<E['name']>\n\ninterface Options<E extends AnyEntity> {\n readonly message: string\n readonly path?: ReadonlyArray<(keyof E['fields'] & string) | LinkKeys<E>>\n}\n\n/** The invariant `build` declares over `entity`'s rows, refused where it could judge nothing. */\nconst declareOn = <E extends AnyEntity>(\n entity: E,\n id: string,\n build: Build<E>,\n options: Options<E>,\n): Invariant => {\n const fields = entity.fields as Readonly<Record<string, E['fields'][string]>>\n const relations = entity.relations as Readonly<Record<string, EntityMember>>\n // A `one` relation reads as the id it points at; a `many` holds no one value.\n const links = Object.values(relations).flatMap(member =>\n member._tag === 'Relation' && member.cardinality === 'one' ? [member as OneRelation] : [],\n )\n const nexts = [\n ...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)] as const),\n ...links.map(link => [link.key, Expr.next(link)] as const),\n ]\n const after = Object.fromEntries(nexts) as unknown as AfterRow<E>\n // Before a write, each is what its `after` reads after it: the same operand, unmoved.\n const before = Object.fromEntries(\n nexts.map(([key, next]) => [key, next.field]),\n ) as unknown as BeforeRow<E>\n const predicate = build({ before, after }) as Predicate\n // `where` refuses a predicate over another Entity, which the type allows when it is unmarked.\n const body = Query.from(entity).pipe(Query.where(predicate))\n const dependencies = Query.dependencies(body)\n if (dependencies.inputs.length > 0) {\n fail(entity, `\"${id}\" reads the input ${dependencies.inputs.join(', ')}; it judges stored rows`)\n }\n const beforeReads = dependencies.predicate.map(field => field.key)\n const afterReads = dependencies.next.map(field => field.key)\n // Reading the row before alone, it says which rows a write may start from: a write's `when`.\n // Judged as an invariant, a create would skip it and a repair would be refused by it.\n if (afterReads.length === 0) {\n fail(entity, `\"${id}\" reads no field of \\`after\\`; what a write may start from is its \\`when\\``)\n }\n const path = options.path ?? [...new Set([...afterReads, ...beforeReads])]\n for (const key of path) {\n if (!Object.hasOwn(fields, key) && !links.some(link => link.key === key))\n fail(entity, `\"${id}\"'s path names \"${key}\", neither a field nor a one relation`)\n }\n return Object.freeze({\n id,\n entity: entity.name,\n predicate,\n message: options.message,\n path: Object.freeze([...path]),\n before: Object.freeze(beforeReads),\n after: Object.freeze(afterReads),\n })\n}\n\n/**\n * Declares what every stored row, or every change of one, must hold:\n * `Entity.invariant('reservedWithinQuantity', ({ after }) =>\n * Expr.lte(after.reserved, after.quantity), { message })` over the row a\n * write leaves, or with `before` too over the change an update makes.\n * Refused where it is declared: an id declared twice, a predicate over another\n * Entity, one reading an input or nothing of `after` (that is a `when`), a path\n * naming no field.\n */\nexport const invariant = <E extends AnyEntity>(\n id: string,\n build: Build<E>,\n options: Options<E>,\n): DeclaredInvariant<E> => {\n let attached: string | undefined\n const declared = (entity: E): E => {\n if (id.length === 0) fail(entity, 'an invariant needs an id')\n if (attached !== undefined && attached !== entity.name)\n fail(entity, `\"${id}\" is declared on ${attached} already: declare it again for this Entity`)\n if (invariantsOf(entity).some(held => held.id === id)) fail(entity, `\"${id}\" is declared twice`)\n const held = declareOn(entity, id, build, options)\n attached = entity.name\n return remake(entity, {\n metadata: Metadata.combine([entity.metadata, Invariants.of(held)]),\n }) as E\n }\n return Object.defineProperties(declared, {\n id: { value: id, enumerable: true },\n entity: {\n enumerable: true,\n get: () => {\n if (attached === undefined) {\n throw new Error(\n `[foldkit-entity] Entity.invariant \"${id}\" names no Entity until it is attached to one`,\n )\n }\n return attached\n },\n },\n }) as DeclaredInvariant<E>\n}\n\nconst ofCases = new WeakMap<EntityIdentity<string>, ReadonlyArray<Invariant>>()\n\n/**\n * Each case's invariant of a variant Entity (`variant_Available`): a field\n * of its own is held, and one of another case is null. Built when first\n * read, so declaring variants reaches no expression code.\n */\nconst caseInvariants = (identity: EntityIdentity<string>): ReadonlyArray<Invariant> => {\n const base = variantBases.get(identity)\n if (base === undefined) return []\n const known = ofCases.get(identity)\n if (known !== undefined) return known\n const variants = Option.getOrThrow(variantsOf(identity))\n const { name } = base\n const separate = Object.keys(base.fields).filter(\n key => key !== '_tag' && variants.tags.some(tag => !Object.hasOwn(variants.cases[tag]!, key)),\n )\n const built = variants.tags.flatMap(tag => {\n const own = variants.cases[tag]!\n const reads = separate.filter(key => !Object.hasOwn(own, key) || !storesNull(own[key]!))\n if (reads.length === 0) return []\n const held = reads.filter(key => Object.hasOwn(own, key))\n const foreign = reads.filter(key => !Object.hasOwn(own, key))\n return [\n declareOn<AnyEntity>(\n base,\n `variant_${tag}`,\n ({ after }) => {\n const row = after as Readonly<Record<string, NextExpr<unknown>>>\n const checks = [\n ...held.map(key => Expr.isNotNull(row[key]!)),\n ...foreign.map(key => Expr.isNull(row[key]!)),\n ]\n return Expr.or(\n Expr.not(Expr.eq(row._tag!, tag)),\n Expr.and(checks[0]!, ...checks.slice(1)),\n )\n },\n {\n message: `A ${name} that is ${tag} ${[\n ...(held.length > 0 ? [`holds ${held.join(', ')}`] : []),\n ...(foreign.length > 0 ? [`holds none of ${foreign.join(', ')}`] : []),\n ].join(' and ')}`,\n path: reads,\n },\n ),\n ]\n })\n ofCases.set(identity, built)\n return built\n}\n\n/** The Entity's invariants, in the order they were declared. */\nexport const invariantsOf = (entity: AnyEntity): ReadonlyArray<Invariant> => {\n const cases = caseInvariants(entity.identity)\n const declared = Invariants.get(entity.metadata)\n return cases.length === 0 ? declared : [...cases, ...declared]\n}\n\n/** `Entity.judge` against invariants already read, such as those a database binding keeps. */\nexport const judgeAgainst = (\n invariants: ReadonlyArray<Invariant>,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const missing = new Set<string>()\n const unrun = new Set<string>()\n const failures: Array<Invariant> = []\n const { after, before } = change\n for (const held of invariants) {\n // A create has no row before, so a transition invariant has nothing to judge.\n if (readsBefore(held) && before === undefined) continue\n const absent = [\n ...held.after.filter(key => !Object.hasOwn(after, key)),\n ...held.before.filter(key => !Object.hasOwn(before ?? {}, key)),\n ]\n if (absent.length > 0) absent.forEach(key => missing.add(key))\n else {\n try {\n if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) {\n failures.push(held)\n }\n } catch (error) {\n // An operator this table does not run is a judgement it cannot make, as a\n // field the row lacks is: a form passes it, and a server's checks refuse to\n // start without the operator (expr-operations-DESIGN §5.6).\n if (!(error instanceof OperatorMissingError)) throw error\n unrun.add(error.named)\n }\n }\n }\n if (failures.length > 0) return { _tag: 'Invalid', failures }\n if (missing.size > 0 || unrun.size > 0) {\n return { _tag: 'Undecided', fields: [...missing], operators: [...unrun] }\n }\n return { _tag: 'Valid' }\n}\n\n/**\n * A row, or a change, under every invariant (each row as the store holds it,\n * encoded): valid only when each is true. SQL's unknown, from a null, fails\n * one, as a `WHERE` drops the row; a field a row does not have leaves it\n * undecided, never valid. Without `before` (a create), transition invariants\n * are not judged.\n */\nexport const judge = (\n entity: AnyEntity,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => judgeAgainst(invariantsOf(entity), change, operators)\n\n/**\n * The row an input's value describes, judged under its Entity's state\n * invariants: each key mapped to a field, encoded as the store holds it, and\n * each mapped to a `one` relation as the id it points at. An\n * invariant over a field the input does not set (an `Option` holding nothing, a\n * key left out) is undecided, so a partial input is never called valid on its\n * account. It has no row before, so it judges no transition.\n */\nexport const judgeInput = (\n input: EntityInput<AnyEntity, any, any>,\n value: Readonly<Record<string, unknown>>,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const invariants = invariantsOf(input.entity)\n if (invariants.length === 0) return { _tag: 'Valid' }\n const members = input.members as Readonly<Record<string, InputMember>>\n const row: Record<string, unknown> = {}\n for (const [key, member] of Object.entries(members)) {\n if (!Object.hasOwn(value, key)) continue\n // A `one` relation's key holds the id it points at: the row holds that id, or null.\n if (member._tag === 'RelationInput' && member.relation.cardinality === 'one') {\n const given = value[key]\n const id = Option.isOption(given) ? Option.getOrNull(given) : given\n if (id === null || typeof id === 'string') put(row, member.relation.key, id)\n continue\n }\n if (member._tag !== 'Field') continue\n const encode = Schema.encodeUnknownOption(\n member.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n const given = value[key]\n const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given)\n // The value as the field holds it: itself for a field typed `Option`, else what it holds.\n // One the field cannot hold is no row the store would keep, so it decides nothing here.\n const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode))\n Option.map(\n Option.flatMap(held, () => stored),\n encoded => put(row, member.key, encoded),\n )\n }\n return judgeAgainst(invariants, { after: row }, operators)\n}\n\n/**\n * The Entity's state invariants as an Effect Schema check over its row type:\n * each failure at its path, with its message. The value is encoded first,\n * field by field, so it is judged as the store would hold it. Refused where it\n * is made when an invariant calls an operator `operators` does not run: such a\n * check would pass every value.\n */\nexport const check = <E extends AnyEntity>(\n entity: E,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): SchemaAST.Filter<Schema.Schema.Type<E['schema']>> => {\n const predicates = invariantsOf(entity).map(held => held.predicate)\n // The judge runs every operation an invariant reads; an operator alone can be missing.\n const missing = Expr.unsupported(predicates, {\n operations: dependenciesOf(...predicates).operations,\n operators: options.operators ?? Operators.kernel,\n })\n if (missing.length > 0) {\n throw new Error(\n `[foldkit-entity] Entity.check of ${entity.name}: its invariants call ${missing.join(', ')}, which the operator table does not run; pass one that does as \\`operators\\``,\n )\n }\n return Schema.makeFilter(value => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const decoded = value as Readonly<Record<string, unknown>>\n const row: Record<string, unknown> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (!Object.hasOwn(decoded, key)) continue\n put(\n row,\n key,\n Schema.encodeUnknownSync(field.schema as unknown as Schema.Codec<unknown, unknown>)(\n decoded[key],\n ),\n )\n }\n const judged = judge(entity, { after: row }, options.operators)\n if (judged._tag !== 'Invalid') return undefined\n return judged.failures.flatMap((failure): ReadonlyArray<Schema.FilterIssue> =>\n failure.path.length === 0\n ? [failure.message]\n : failure.path.map(key => ({ path: [key], issue: failure.message })),\n )\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,MAAM,aAAa,SAAS,IAAe,6BAA6B;CAEtE,QAAO,WAAU,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;CACpC,YAAW,cAAa,UAAU;AACpC,CAAC;;AAiBD,MAAa,eAAe,SAA6B,KAAK,OAAO,SAAS;AAgB9E,MAAM,QAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,wCAAwC,OAAO,KAAK,IAAI,SAAS;AACnF;;AAcA,MAAM,aACJ,QACA,IACA,OACA,YACc;CACd,MAAM,SAAS,OAAO;CACtB,MAAM,YAAY,OAAO;CAEzB,MAAM,QAAQ,OAAO,OAAO,SAAS,CAAC,CAAC,SAAQ,WAC7C,OAAO,SAAS,cAAc,OAAO,gBAAgB,QAAQ,CAAC,MAAqB,IAAI,CAAC,CAC1F;CACA,MAAM,QAAQ,CACZ,GAAG,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,KAAK,KAAK,KAAK,CAAC,CAAU,GAChF,GAAG,MAAM,KAAI,SAAQ,CAAC,KAAK,KAAK,KAAK,KAAK,IAAI,CAAC,CAAU,CAC3D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AS;EAC9D,IAAI,OAAO,SAAS,WAAW,OAAO,KAAA;EACtC,OAAO,OAAO,SAAS,SAAS,YAC9B,QAAQ,KAAK,WAAW,IACpB,CAAC,QAAQ,OAAO,IAChB,QAAQ,KAAK,KAAI,SAAQ;GAAE,MAAM,CAAC,GAAG;GAAG,OAAO,QAAQ;EAAQ,EAAE,CACvE;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"invariant.js","names":["fail"],"sources":["../src/invariant.ts"],"sourcesContent":["/**\n * Invariants: what every stored row of an Entity must hold, and what every\n * change of one must, declared once on the Entity through its metadata and read\n * from there by each interpreter: the reference judge here, a Schema check, a\n * form, a server's writer.\n *\n * One is built over the row before a write (`before`, each field as `Expr.field`) and\n * the row after it (`after`, each field as `Expr.next`); each `one` relation is\n * there too, as the id it points at, so a judged row holds it as that id. What\n * it reads decides when it is judged:\n *\n * ```text\n * reads `after` only -> a state invariant: every create and update, a CHECK constraint\n * reads `before` too -> a transition invariant: every update, which has a row before\n * ```\n *\n * It reads no input and no principal. Who may write is a guard's; whether a\n * write applies now is its `when`'s.\n */\nimport { Metadata } from 'foldkit-metadata'\nimport { Match, Option, Schema, type SchemaAST } from 'effect'\nimport { OperatorMissingError, truthOver, type Row } from './evaluate.js'\nimport { kernelOperators } from './memoryTable.js'\nimport type { MemoryOperators } from './operators.js'\nimport { put } from './record.js'\nimport {\n Expr,\n Query,\n dependenciesOf,\n type FieldExpr,\n type NextExpr,\n type OneRelation,\n type Predicate,\n type Reads,\n} from './expr.js'\nimport { remake, variantBases } from './descriptor.js'\nimport type {\n AnyEntity,\n EntityField,\n EntityIdentity,\n EntityInput,\n EntityMember,\n InputMember,\n} from './index.js'\nimport { storesNull, variantsOf } from './variants.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\n\n/** One invariant of an Entity, as its interpreters read it. */\nexport interface Invariant {\n /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */\n readonly id: string\n /** The Entity it is declared on: ids are unique only within one, so a refusal names both. */\n readonly entity: string\n readonly predicate: Predicate\n /** What someone the rules let write is told when a write would break it. */\n readonly message: string\n /** The members a form shows the failure beside. */\n readonly path: ReadonlyArray<string>\n /** The members it reads of the row before a write (fields, `one` relations); none for a state invariant. */\n readonly before: ReadonlyArray<string>\n /** The members it reads of the row after. */\n readonly after: ReadonlyArray<string>\n}\n\n/** The keys of an Entity's `one` relations: what a row holds as the id each points at. */\ntype LinkKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/** The id a `one` relation points at, as a row holds it: null for an optional one pointing nowhere. */\ntype LinkOf<\n E extends AnyEntity,\n K extends keyof E['relations'],\n> = E['relations'][K]['optional'] extends true ? string | null : string\n\n/**\n * Each field as the row before a write holds it, and each `one` relation as\n * the id it points at: what an invariant reads as `before`. Encoded, as the\n * store holds it and the judge reads it, so a literal is written so too (a\n * date as its ISO text).\n */\nexport type BeforeRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: FieldExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: FieldExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** Each field, and each `one` relation's id, as the row after a write holds it: `after`. */\nexport type AfterRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: NextExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: NextExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** A row, or a change from one row to another, as an invariant is judged over it. */\nexport interface Change {\n readonly after: Row\n /** The row before an update; none for a create, which judges no transition invariant. */\n readonly before?: Row\n}\n\nconst Invariants = Metadata.key<Invariant>('foldkit-entity/invariants', {\n // The same invariant reached twice (two annotated copies combined) is one.\n merge: values => [...new Set(values)],\n summarize: invariant => invariant.id,\n})\n\n/** What a row, or a change, comes to under an Entity's invariants. */\nexport type Judgement =\n | { readonly _tag: 'Valid' }\n | { readonly _tag: 'Invalid'; readonly failures: ReadonlyArray<Invariant> }\n /**\n * Validity is not known: some invariant reads a field the row does not have\n * (`fields`), or calls an operator the table does not run (`operators`, by name).\n */\n | {\n readonly _tag: 'Undecided'\n readonly fields: ReadonlyArray<string>\n readonly operators: ReadonlyArray<string>\n }\n\n/** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */\nexport const readsBefore = (held: Invariant): boolean => held.before.length > 0\n\n/**\n * An invariant as declared: the step that attaches it to its Entity, carrying\n * its id and, once attached, that Entity's name, so a refusal is matched\n * against the declaration rather than a string spelled again\n * (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`). An id is unique\n * only within an Entity, so the name is part of what a refusal names; reading\n * it before the declaration is attached throws.\n */\nexport interface DeclaredInvariant<E extends AnyEntity> {\n (entity: E): E\n readonly id: string\n readonly entity: string\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`)\n}\n\n/** How an invariant is declared: what `build` returns over the rows, and what a failure says. */\ntype Build<E extends AnyEntity> = (rows: {\n readonly before: BeforeRow<E>\n readonly after: AfterRow<E>\n}) => Predicate & Reads<E['name']>\n\ninterface Options<E extends AnyEntity> {\n readonly message: string\n readonly path?: ReadonlyArray<(keyof E['fields'] & string) | LinkKeys<E>>\n}\n\n/** The invariant `build` declares over `entity`'s rows, refused where it could judge nothing. */\nconst declareOn = <E extends AnyEntity>(\n entity: E,\n id: string,\n build: Build<E>,\n options: Options<E>,\n): Invariant => {\n const fields = entity.fields as Readonly<Record<string, E['fields'][string]>>\n const relations = entity.relations as Readonly<Record<string, EntityMember>>\n // A `one` relation reads as the id it points at; a `many` holds no one value.\n const links = Object.values(relations).flatMap(member => {\n if (member._tag !== 'Relation' || member.cardinality !== 'one') return []\n return [member as OneRelation]\n })\n const nexts = [\n ...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)] as const),\n ...links.map(link => [link.key, Expr.next(link)] as const),\n ]\n const after = Object.fromEntries(nexts) as unknown as AfterRow<E>\n // Before a write, each is what its `after` reads after it: the same operand, unmoved.\n const before = Object.fromEntries(\n nexts.map(([key, next]) => [key, next.field]),\n ) as unknown as BeforeRow<E>\n const predicate = build({ before, after }) as Predicate\n // `where` refuses a predicate over another Entity, which the type allows when it is unmarked.\n const body = Query.from(entity).pipe(Query.where(predicate))\n const dependencies = Query.dependencies(body)\n if (dependencies.inputs.length > 0) {\n fail(entity, `\"${id}\" reads the input ${dependencies.inputs.join(', ')}; it judges stored rows`)\n }\n const beforeReads = dependencies.predicate.map(field => field.key)\n const afterReads = dependencies.next.map(field => field.key)\n // Reading the row before alone, it says which rows a write may start from: a write's `when`.\n // Judged as an invariant, a create would skip it and a repair would be refused by it.\n if (afterReads.length === 0) {\n fail(entity, `\"${id}\" reads no field of \\`after\\`; what a write may start from is its \\`when\\``)\n }\n const path = options.path ?? [...new Set([...afterReads, ...beforeReads])]\n for (const key of path) {\n if (!Object.hasOwn(fields, key) && !links.some(link => link.key === key))\n fail(entity, `\"${id}\"'s path names \"${key}\", neither a field nor a one relation`)\n }\n return Object.freeze({\n id,\n entity: entity.name,\n predicate,\n message: options.message,\n path: Object.freeze([...path]),\n before: Object.freeze(beforeReads),\n after: Object.freeze(afterReads),\n })\n}\n\n/**\n * Declares what every stored row, or every change of one, must hold:\n * `Entity.invariant('reservedWithinQuantity', ({ after }) =>\n * Expr.lte(after.reserved, after.quantity), { message })` over the row a\n * write leaves, or with `before` too over the change an update makes.\n * Refused where it is declared: an id declared twice, a predicate over another\n * Entity, one reading an input or nothing of `after` (that is a `when`), a path\n * naming no field.\n */\nexport const invariant = <E extends AnyEntity>(\n id: string,\n build: Build<E>,\n options: Options<E>,\n): DeclaredInvariant<E> => {\n let attached: string | undefined\n const declared = (entity: E): E => {\n if (id.length === 0) fail(entity, 'an invariant needs an id')\n if (attached !== undefined && attached !== entity.name)\n fail(entity, `\"${id}\" is declared on ${attached} already: declare it again for this Entity`)\n if (invariantsOf(entity).some(held => held.id === id)) fail(entity, `\"${id}\" is declared twice`)\n const held = declareOn(entity, id, build, options)\n attached = entity.name\n return remake(entity, {\n metadata: Metadata.combine([entity.metadata, Invariants.of(held)]),\n }) as E\n }\n return Object.defineProperties(declared, {\n id: { value: id, enumerable: true },\n entity: {\n enumerable: true,\n get: () => {\n if (attached === undefined) {\n throw new Error(\n `[foldkit-entity] Entity.invariant \"${id}\" names no Entity until it is attached to one`,\n )\n }\n return attached\n },\n },\n }) as DeclaredInvariant<E>\n}\n\nconst ofCases = new WeakMap<EntityIdentity<string>, ReadonlyArray<Invariant>>()\n\n/**\n * Each case's invariant of a variant Entity (`variant_Available`): a field\n * of its own is held, and one of another case is null. Built when first\n * read, so declaring variants reaches no expression code.\n */\nconst caseInvariants = (identity: EntityIdentity<string>): ReadonlyArray<Invariant> => {\n const base = variantBases.get(identity)\n if (base === undefined) return []\n const known = ofCases.get(identity)\n if (known !== undefined) return known\n const variants = Option.getOrThrow(variantsOf(identity))\n const { name } = base\n const separate = Object.keys(base.fields).filter(\n key => key !== '_tag' && variants.tags.some(tag => !Object.hasOwn(variants.cases[tag]!, key)),\n )\n const built = variants.tags.flatMap(tag => {\n const own = variants.cases[tag]!\n const reads = separate.filter(key => !Object.hasOwn(own, key) || !storesNull(own[key]!))\n if (reads.length === 0) return []\n const held = reads.filter(key => Object.hasOwn(own, key))\n const foreign = reads.filter(key => !Object.hasOwn(own, key))\n return [\n declareOn<AnyEntity>(\n base,\n `variant_${tag}`,\n ({ after }) => {\n const row = after as Readonly<Record<string, NextExpr<unknown>>>\n const checks = [\n ...held.map(key => Expr.isNotNull(row[key]!)),\n ...foreign.map(key => Expr.isNull(row[key]!)),\n ]\n return Expr.or(\n Expr.not(Expr.eq(row._tag!, tag)),\n Expr.and(checks[0]!, ...checks.slice(1)),\n )\n },\n {\n message: `A ${name} that is ${tag} ${[\n ...(held.length > 0 ? [`holds ${held.join(', ')}`] : []),\n ...(foreign.length > 0 ? [`holds none of ${foreign.join(', ')}`] : []),\n ].join(' and ')}`,\n path: reads,\n },\n ),\n ]\n })\n ofCases.set(identity, built)\n return built\n}\n\n/** The Entity's invariants, in the order they were declared. */\nexport const invariantsOf = (entity: AnyEntity): ReadonlyArray<Invariant> => {\n const cases = caseInvariants(entity.identity)\n const declared = Invariants.get(entity.metadata)\n return cases.length === 0 ? declared : [...cases, ...declared]\n}\n\n/** `Entity.judge` against invariants already read, such as those a database binding keeps. */\nexport const judgeAgainst = (\n invariants: ReadonlyArray<Invariant>,\n change: Change,\n operators: MemoryOperators = kernelOperators,\n): Judgement => {\n const missing = new Set<string>()\n const unrun = new Set<string>()\n const failures: Array<Invariant> = []\n const { after, before } = change\n for (const held of invariants) {\n // A create has no row before, so a transition invariant has nothing to judge.\n if (readsBefore(held) && before === undefined) continue\n const absent = [\n ...held.after.filter(key => !Object.hasOwn(after, key)),\n ...held.before.filter(key => !Object.hasOwn(before ?? {}, key)),\n ]\n if (absent.length > 0) absent.forEach(key => missing.add(key))\n else {\n try {\n if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) {\n failures.push(held)\n }\n } catch (error) {\n // An operator this table does not run is a judgement it cannot make, as a\n // field the row lacks is: a form passes it, and a server's checks refuse to\n // start without the operator (expr-operations-DESIGN §5.6).\n if (!(error instanceof OperatorMissingError)) throw error\n unrun.add(error.named)\n }\n }\n }\n if (failures.length > 0) return { _tag: 'Invalid', failures }\n if (missing.size > 0 || unrun.size > 0) {\n return { _tag: 'Undecided', fields: [...missing], operators: [...unrun] }\n }\n return { _tag: 'Valid' }\n}\n\n/**\n * A row, or a change, under every invariant (each row as the store holds it,\n * encoded): valid only when each is true. SQL's unknown, from a null, fails\n * one, as a `WHERE` drops the row; a field a row does not have leaves it\n * undecided, never valid. Without `before` (a create), transition invariants\n * are not judged.\n */\nexport const judge = (\n entity: AnyEntity,\n change: Change,\n operators: MemoryOperators = kernelOperators,\n): Judgement => judgeAgainst(invariantsOf(entity), change, operators)\n\n/**\n * The row an input's value describes, judged under its Entity's state\n * invariants: each key mapped to a field, encoded as the store holds it, and\n * each mapped to a `one` relation as the id it points at. An\n * invariant over a field the input does not set (an `Option` holding nothing, a\n * key left out) is undecided, so a partial input is never called valid on its\n * account. It has no row before, so it judges no transition.\n */\nexport const judgeInput = (\n input: EntityInput<AnyEntity, any, any>,\n value: Readonly<Record<string, unknown>>,\n operators: MemoryOperators = kernelOperators,\n): Judgement => {\n const invariants = invariantsOf(input.entity)\n if (invariants.length === 0) return { _tag: 'Valid' }\n const members = input.members as Readonly<Record<string, InputMember>>\n const row: Record<string, unknown> = {}\n for (const [key, member] of Object.entries(members)) {\n if (!Object.hasOwn(value, key)) continue\n // A `one` relation's key holds the id it points at: the row holds that id, or null.\n if (member._tag === 'RelationInput' && member.relation.cardinality === 'one') {\n const given = value[key]\n const id = Option.isOption(given) ? Option.getOrUndefined(given) : given\n if (id === null || typeof id === 'string') put(row, member.relation.key, id)\n continue\n }\n if (member._tag !== 'Field') continue\n const encode = Schema.encodeUnknownOption(\n member.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n const given = value[key]\n const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given)\n // The value as the field holds it: itself for a field typed `Option`, else what it holds.\n // One the field cannot hold is no row the store would keep, so it decides nothing here.\n const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode))\n Option.map(\n Option.flatMap(held, () => stored),\n encoded => put(row, member.key, encoded),\n )\n }\n return judgeAgainst(invariants, { after: row }, operators)\n}\n\n/**\n * The Entity's state invariants as an Effect Schema check over its row type:\n * each failure at its path, with its message. The value is encoded first,\n * field by field, so it is judged as the store would hold it. Refused where it\n * is made when an invariant calls an operator `operators` does not run: such a\n * check would pass every value.\n */\nexport const check = <E extends AnyEntity>(\n entity: E,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): SchemaAST.Filter<Schema.Schema.Type<E['schema']>> => {\n const predicates = invariantsOf(entity).map(held => held.predicate)\n // The judge runs every operation an invariant reads; an operator alone can be missing.\n const missing = Expr.unsupported(predicates, {\n operations: dependenciesOf(...predicates).operations,\n operators: options.operators ?? kernelOperators,\n })\n if (missing.length > 0) {\n throw new Error(\n `[foldkit-entity] Entity.check of ${entity.name}: its invariants call ${missing.join(', ')}, which the operator table does not run; pass one that does as \\`operators\\``,\n )\n }\n return Schema.makeFilter(value => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const decoded = value as Readonly<Record<string, unknown>>\n const row: Record<string, unknown> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (!Object.hasOwn(decoded, key)) continue\n put(\n row,\n key,\n Schema.encodeUnknownSync(field.schema as unknown as Schema.Codec<unknown, unknown>)(\n decoded[key],\n ),\n )\n }\n const judged = judge(entity, { after: row }, options.operators)\n return Match.valueTags(judged, {\n Invalid: ({ failures }) =>\n failures.flatMap((failure): ReadonlyArray<Schema.FilterIssue> =>\n failure.path.length === 0\n ? [failure.message]\n : failure.path.map(key => ({ path: [key], issue: failure.message })),\n ),\n Valid: () => undefined,\n Undecided: () => undefined,\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA,MAAM,aAAa,SAAS,IAAe,6BAA6B;CAEtE,QAAO,WAAU,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;CACpC,YAAW,cAAa,UAAU;AACpC,CAAC;;AAiBD,MAAa,eAAe,SAA6B,KAAK,OAAO,SAAS;AAgB9E,MAAMA,UAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,wCAAwC,OAAO,KAAK,IAAI,SAAS;AACnF;;AAcA,MAAM,aACJ,QACA,IACA,OACA,YACc;CACd,MAAM,SAAS,OAAO;CACtB,MAAM,YAAY,OAAO;CAEzB,MAAM,QAAQ,OAAO,OAAO,SAAS,CAAC,CAAC,SAAQ,WAAU;EACvD,IAAI,OAAO,SAAS,cAAc,OAAO,gBAAgB,OAAO,OAAO,CAAC;EACxE,OAAO,CAAC,MA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OAAO,QAAM;EAGxC;;;eAzEmB,QAAA,OAAO,OAAO,OAAO;eACtB;eACD,MAAA;;;eAfe,QAAA,OAAO,OAAO,OAAO;;;eAErB,QAAA,OAAO,OAAO,OAAO;;;eAsBrB,QAAA,OAAO,OAAO,OAAO;eAAqB,MAAA;;;eApB3C,QAAA,OAAO,OAAO,OAAO;;;eAGjC,QAAA,OAAO,OAAO,OAAO;eACtB;eACD,MAAA;;;eAUE,QAAA,OAAO,OAAO,OAAO;eACtB,OAAA;eACG;;;eAMF,QAAA,OAAO,OAAO,OAAO;eAClB;eACD;;;eAGkB,QAAA,OAAO,OAAO,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAnBzC,QAAA,OAAO,OAAO,OAAO;eACtB;eACD,MAAA;;;eAfe,QAAA,OAAO,OAAO,OAAO;;;eAErB,QAAA,OAAO,OAAO,OAAO;;;eAsBrB,QAAA,OAAO,OAAO,OAAO;eAAqB,MAAA;;;eApB3C,QAAA,OAAO,OAAO,OAAO;;;eAGjC,QAAA,OAAO,OAAO,OAAO;eACtB;eACD,MAAA;;;eAUE,QAAA,OAAO,OAAO,OAAO;eACtB,OAAA;eACG;;;eAMF,QAAA,OAAO,OAAO,OAAO;eAClB;eACD;;;eAGkB,QAAA,OAAO,OAAO,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6D5D,iBAAc,KAAQ,mBAAiB;;EAMvC,WAAQ,KAAQ,QAAM"}
package/dist/law.js CHANGED
@@ -1,13 +1,7 @@
1
- import { Data, Option, Schema } from "effect";
1
+ import { Option, Schema } from "effect";
2
+ import { Laws, lawKind } from "./lawCore.js";
2
3
  import { jsonSchemaOf } from "./jsonSchema.js";
3
4
  // src/law.ts
4
- /**
5
- * Laws an operator declares (expr-operations-DESIGN §10): equations every
6
- * implementation of it keeps over a domain. A law describes; nothing rewrites a
7
- * body by one. `Conformance.laws` tests an implementation against them, and
8
- * what it finds is evidence recorded in that implementation's table.
9
- */
10
- const Laws = Data.taggedEnum();
11
5
  const unnarrowed = { domain: Option.none() };
12
6
  /**
13
7
  * A law as JSON says it: what `Operators.describe` lists and evidence names.
@@ -97,7 +91,7 @@ const Law = {
97
91
  })
98
92
  });
99
93
  return {
100
- kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),
94
+ kind: lawKind(law),
101
95
  witnesses,
102
96
  domain: Option.match(law.domain, {
103
97
  onNone: () => null,
package/dist/law.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"law.js","names":[],"sources":["../src/law.ts"],"sourcesContent":["/**\n * Laws an operator declares (expr-operations-DESIGN §10): equations every\n * implementation of it keeps over a domain. A law describes; nothing rewrites a\n * body by one. `Conformance.laws` tests an implementation against them, and\n * what it finds is evidence recorded in that implementation's table.\n */\nimport { Data, Option, Schema } from 'effect'\nimport type { Operator } from './expr.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\n\n/** An operator a law names as a witness: the inverse, or the operator distributed over. */\ntype AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>\n\n/** Which argument a witness stands in. */\nexport type Side = 'left' | 'right' | 'both'\n\n/**\n * A law, over its domain: by default every non-null value of the operator's\n * input schemas; narrowed by `Law.within`.\n */\nexport type Law = Data.TaggedEnum<{\n /** `op(op(a, b), c) = op(a, op(b, c))` */\n Associative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, b) = op(b, a)` */\n Commutative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, a) = a` */\n Idempotent: { readonly domain: Option.Option<Schema.Top> }\n /** `op(e, a) = a` (left), `op(a, e) = a` (right), or both. */\n Identity: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(z, a) = z` (left), `op(a, z) = z` (right), or both. */\n Absorbing: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(a, other(a)) = identity` */\n Inverse: {\n readonly domain: Option.Option<Schema.Top>\n readonly other: AnyOperator\n readonly identity: unknown\n }\n /** `op(a, over(b, c)) = over(op(a, b), op(a, c))` */\n Distributes: { readonly domain: Option.Option<Schema.Top>; readonly over: AnyOperator }\n /** `a ≤ b` at `position` implies `op(…a…) ≤ op(…b…)`, or `≥` when decreasing. */\n Monotonic: {\n readonly domain: Option.Option<Schema.Top>\n readonly direction: 'increasing' | 'decreasing'\n readonly position: number\n }\n /** Folding the result equals folding the arguments first: its text keeps their collation (§7). */\n PreservesCollation: { readonly domain: Option.Option<Schema.Top> }\n}>\n\nconst Laws = Data.taggedEnum<Law>()\nconst unnarrowed = { domain: Option.none<Schema.Top>() }\n\n/**\n * A law as JSON says it: what `Operators.describe` lists and evidence names.\n * Its witnesses are values as stored and operators by name; its domain is a\n * JSON Schema, or `null` for the operator's whole input.\n */\nexport const LawDescription = Schema.Struct({\n kind: Schema.String,\n witnesses: Schema.Record(Schema.String, Schema.Unknown),\n domain: Schema.Unknown,\n})\nexport type LawDescription = typeof LawDescription.Type\n\n/** An operator by its id, and its version when that is not the first. */\nconst nameOf = (operator: AnyOperator): string =>\n operator.descriptor.version === 1\n ? operator.descriptor.id\n : `${operator.descriptor.id}@${operator.descriptor.version}`\n\nexport const Law = {\n associative: Laws.Associative(unnarrowed),\n commutative: Laws.Commutative(unnarrowed),\n idempotent: Laws.Idempotent(unnarrowed),\n preservesCollation: Laws.PreservesCollation(unnarrowed),\n /** `value` leaves the other argument as it is, from `side` (both by default). */\n identity: (value: unknown, side: Side = 'both'): Law =>\n Laws.Identity({ ...unnarrowed, value, side }),\n /** `value` is the answer whatever the other argument, from `side` (both by default). */\n absorbing: (value: unknown, side: Side = 'both'): Law =>\n Laws.Absorbing({ ...unnarrowed, value, side }),\n /** `other` undoes the operator: `op(a, other(a))` is `identity`. */\n inverse: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n other: Operator<In, Out>,\n identity: unknown,\n ): Law => Laws.Inverse({ ...unnarrowed, other, identity }),\n /** The operator distributes over `over`, from the left. */\n distributes: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n over: Operator<In, Out>,\n ): Law => Laws.Distributes({ ...unnarrowed, over }),\n /** Moving the argument at `position` up moves the result up (or down, decreasing). */\n monotonic: (direction: 'increasing' | 'decreasing', position: number): Law =>\n Laws.Monotonic({ ...unnarrowed, direction, position }),\n /**\n * The law over the values `domain` accepts only: a law that holds of the\n * integers and not of every number, say, narrowed so it is tested where it\n * is claimed.\n */\n within: (law: Law, domain: Schema.Top): Law =>\n Object.freeze({ ...law, domain: Option.some(domain) }),\n\n $match: Laws.$match,\n\n /**\n * The operators a law, as JSON, calls besides its own (`inverse`'s and\n * `distributes`' witnesses), by name: evidence of it is of their\n * implementations too, and goes when one of them is replaced.\n */\n witnessesNamed: (law: LawDescription): ReadonlyArray<string> =>\n [law.witnesses['other'], law.witnesses['over']].filter(\n (name): name is string => typeof name === 'string',\n ),\n\n /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */\n describe: (law: Law): LawDescription => {\n const witnesses: Record<string, unknown> = Laws.$match(law, {\n Associative: () => ({}),\n Commutative: () => ({}),\n Idempotent: () => ({}),\n PreservesCollation: () => ({}),\n Identity: ({ value, side }) => ({ value, side }),\n Absorbing: ({ value, side }) => ({ value, side }),\n Inverse: ({ other, identity }) => ({ other: nameOf(other), identity }),\n Distributes: ({ over }) => ({ over: nameOf(over) }),\n Monotonic: ({ direction, position }) => ({ direction, position }),\n })\n return {\n kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),\n witnesses,\n domain: Option.match(law.domain, {\n onNone: () => null,\n onSome: jsonSchemaOf,\n }),\n }\n },\n}\n"],"mappings":";;;;;;;;;AAyDA,MAAM,OAAO,KAAK,WAAgB;AAClC,MAAM,aAAa,EAAE,QAAQ,OAAO,KAAiB,EAAE;;;;;;AAOvD,MAAa,iBAAiB,OAAO,OAAO;CAC1C,MAAM,OAAO;CACb,WAAW,OAAO,OAAO,OAAO,Q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E,YAAY,EAAE,MAAM,OAAO,IAAI,EAAE;GACjD,YAAY,EAAE,WAAW,gBAAgB;IAAE;IAAW;GAAS;EACjE,CAAC;EACD,OAAO;GACL,MAAM,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,KAAK,MAAM,CAAC;GACzD;GACA,QAAQ,OAAO,MAAM,IAAI,QAAQ;IAC/B,cAAc;IACd,QAAQ;GACV,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"law.js","names":[],"sources":["../src/law.ts"],"sourcesContent":["/**\n * Laws an operator declares (expr-operations-DESIGN §10): equations every\n * implementation of it keeps over a domain. A law describes; nothing rewrites a\n * body by one. `Conformance.laws` tests an implementation against them, and\n * what it finds is evidence recorded in that implementation's table.\n */\nimport type { Data } from 'effect'\nimport { Option, Schema } from 'effect'\nimport type { Operator } from './expr.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\nimport { Laws, lawKind } from './lawCore.js'\n\n/** An operator a law names as a witness: the inverse, or the operator distributed over. */\ntype AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>\n\n/** Which argument a witness stands in. */\nexport type Side = 'left' | 'right' | 'both'\n\n/**\n * A law, over its domain: by default every non-null value of the operator's\n * input schemas; narrowed by `Law.within`.\n */\nexport type Law = Data.TaggedEnum<{\n /** `op(op(a, b), c) = op(a, op(b, c))` */\n Associative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, b) = op(b, a)` */\n Commutative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, a) = a` */\n Idempotent: { readonly domain: Option.Option<Schema.Top> }\n /** `op(e, a) = a` (left), `op(a, e) = a` (right), or both. */\n Identity: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(z, a) = z` (left), `op(a, z) = z` (right), or both. */\n Absorbing: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(a, other(a)) = identity` */\n Inverse: {\n readonly domain: Option.Option<Schema.Top>\n readonly other: AnyOperator\n readonly identity: unknown\n }\n /** `op(a, over(b, c)) = over(op(a, b), op(a, c))` */\n Distributes: { readonly domain: Option.Option<Schema.Top>; readonly over: AnyOperator }\n /** `a ≤ b` at `position` implies `op(…a…) ≤ op(…b…)`, or `≥` when decreasing. */\n Monotonic: {\n readonly domain: Option.Option<Schema.Top>\n readonly direction: 'increasing' | 'decreasing'\n readonly position: number\n }\n /** Folding the result equals folding the arguments first: its text keeps their collation (§7). */\n PreservesCollation: { readonly domain: Option.Option<Schema.Top> }\n}>\n\nconst unnarrowed = { domain: Option.none<Schema.Top>() }\n\n/**\n * A law as JSON says it: what `Operators.describe` lists and evidence names.\n * Its witnesses are values as stored and operators by name; its domain is a\n * JSON Schema, or `null` for the operator's whole input.\n */\nexport const LawDescription = Schema.Struct({\n kind: Schema.String,\n witnesses: Schema.Record(Schema.String, Schema.Unknown),\n domain: Schema.Unknown,\n})\nexport type LawDescription = typeof LawDescription.Type\n\n/** An operator by its id, and its version when that is not the first. */\nconst nameOf = (operator: AnyOperator): string =>\n operator.descriptor.version === 1\n ? operator.descriptor.id\n : `${operator.descriptor.id}@${operator.descriptor.version}`\n\nexport const Law = {\n associative: Laws.Associative(unnarrowed),\n commutative: Laws.Commutative(unnarrowed),\n idempotent: Laws.Idempotent(unnarrowed),\n preservesCollation: Laws.PreservesCollation(unnarrowed),\n /** `value` leaves the other argument as it is, from `side` (both by default). */\n identity: (value: unknown, side: Side = 'both'): Law =>\n Laws.Identity({ ...unnarrowed, value, side }),\n /** `value` is the answer whatever the other argument, from `side` (both by default). */\n absorbing: (value: unknown, side: Side = 'both'): Law =>\n Laws.Absorbing({ ...unnarrowed, value, side }),\n /** `other` undoes the operator: `op(a, other(a))` is `identity`. */\n inverse: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n other: Operator<In, Out>,\n identity: unknown,\n ): Law => Laws.Inverse({ ...unnarrowed, other, identity }),\n /** The operator distributes over `over`, from the left. */\n distributes: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n over: Operator<In, Out>,\n ): Law => Laws.Distributes({ ...unnarrowed, over }),\n /** Moving the argument at `position` up moves the result up (or down, decreasing). */\n monotonic: (direction: 'increasing' | 'decreasing', position: number): Law =>\n Laws.Monotonic({ ...unnarrowed, direction, position }),\n /**\n * The law over the values `domain` accepts only: a law that holds of the\n * integers and not of every number, say, narrowed so it is tested where it\n * is claimed.\n */\n within: (law: Law, domain: Schema.Top): Law =>\n Object.freeze({ ...law, domain: Option.some(domain) }),\n\n $match: Laws.$match,\n\n /**\n * The operators a law, as JSON, calls besides its own (`inverse`'s and\n * `distributes`' witnesses), by name: evidence of it is of their\n * implementations too, and goes when one of them is replaced.\n */\n witnessesNamed: (law: LawDescription): ReadonlyArray<string> =>\n [law.witnesses['other'], law.witnesses['over']].filter(\n (name): name is string => typeof name === 'string',\n ),\n\n /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */\n describe: (law: Law): LawDescription => {\n const witnesses: Record<string, unknown> = Laws.$match(law, {\n Associative: () => ({}),\n Commutative: () => ({}),\n Idempotent: () => ({}),\n PreservesCollation: () => ({}),\n Identity: ({ value, side }) => ({ value, side }),\n Absorbing: ({ value, side }) => ({ value, side }),\n Inverse: ({ other, identity }) => ({ other: nameOf(other), identity }),\n Distributes: ({ over }) => ({ over: nameOf(over) }),\n Monotonic: ({ direction, position }) => ({ direction, position }),\n })\n return {\n kind: lawKind(law),\n witnesses,\n domain: Option.match(law.domain, {\n onNone: () => null,\n onSome: jsonSchemaOf,\n }),\n }\n },\n}\n"],"mappings":";;;;AA2DA,MAAM,aAAa,EAAE,QAAQ,OAAO,KAAiB,EAAE;;;;;;AAOvD,MAAa,iBAAiB,OAAO,OAAO;CAC1C,MAAM,OAAO;CACb,WAAW,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CACtD,QAAQ,OAAO;AACjB,CAAC;;AAID,MAAM,UAAU,aACd,SAAS,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AAW;GAAS;EACjE,CAAC;EACD,OAAO;GACL,MAAM,QAAQ,GAAG;GACjB;GACA,QAAQ,OAAO,MAAM,IAAI,QAAQ;IAC/B,cAAc;IACd,QAAQ;GACV,CAAC;EACH;CACF;AACF"}
@@ -0,0 +1,42 @@
1
+ import { Data } from "effect";
2
+ import { Law } from "./law.js";
3
+ export declare const Laws: Data.TaggedEnum.Constructor<{
4
+ readonly _tag: "Absorbing";
5
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
6
+ readonly value: unknown;
7
+ readonly side: import("./law.js").Side;
8
+ } | {
9
+ readonly _tag: "Associative";
10
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
11
+ } | {
12
+ readonly _tag: "Commutative";
13
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
14
+ } | {
15
+ readonly _tag: "Distributes";
16
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
17
+ readonly over: import("./expr.js").Operator<readonly import("effect/Schema").Top[], import("effect/Schema").Top>;
18
+ } | {
19
+ readonly _tag: "Idempotent";
20
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
21
+ } | {
22
+ readonly _tag: "Identity";
23
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
24
+ readonly value: unknown;
25
+ readonly side: import("./law.js").Side;
26
+ } | {
27
+ readonly _tag: "Inverse";
28
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
29
+ readonly other: import("./expr.js").Operator<readonly import("effect/Schema").Top[], import("effect/Schema").Top>;
30
+ readonly identity: unknown;
31
+ } | {
32
+ readonly _tag: "Monotonic";
33
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
34
+ readonly direction: 'increasing' | 'decreasing';
35
+ readonly position: number;
36
+ } | {
37
+ readonly _tag: "PreservesCollation";
38
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
39
+ }>;
40
+ /** The law's kind as a name: `Associative` is `associative`. */
41
+ export declare const lawKind: (law: Law) => string;
42
+ //# sourceMappingURL=lawCore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lawCore.d.ts","names":[],"sources":["../src/lawCore.ts"],"mappings":";;qBAOa,MAAI,KAAA,WAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAGJ,UAAO,KAAS"}
@@ -0,0 +1,12 @@
1
+ import { Data } from "effect";
2
+ // src/lawCore.ts
3
+ /**
4
+ * What evaluating a body needs of a law: its variants and its kind. Apart from
5
+ * `Law.describe` so a client that never describes one keeps no JSON Schema.
6
+ */
7
+ const Laws = Data.taggedEnum();
8
+ /** The law's kind as a name: `Associative` is `associative`. */
9
+ const lawKind = (law) => law._tag.charAt(0).toLowerCase() + law._tag.slice(1);
10
+ export { Laws, lawKind };
11
+
12
+ //# sourceMappingURL=lawCore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lawCore.js","names":[],"sources":["../src/lawCore.ts"],"sourcesContent":["/**\n * What evaluating a body needs of a law: its variants and its kind. Apart from\n * `Law.describe` so a client that never describes one keeps no JSON Schema.\n */\nimport { Data } from 'effect'\nimport type { Law } from './law.js'\n\nexport const Laws = Data.taggedEnum<Law>()\n\n/** The law's kind as a name: `Associative` is `associative`. */\nexport const lawKind = (law: Law): string => law._tag.charAt(0).toLowerCase() + law._tag.slice(1)\n"],"mappings":";;;;;;AAOA,MAAa,OAAO,KAAK,WAAgB;;AAGzC,MAAa,WAAW,QAAqB,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,KAAK,MAAM,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { OperatorDescriptor } from "./expr.js";
2
+ import { Evidence, MemoryImplementation, MemoryOperators } from "./operators.js";
3
+ /** An operator by its id, and its version when that is not the first. */
4
+ export declare const nameOf: (operator: OperatorDescriptor) => string;
5
+ export declare const fail: (what: string) => never;
6
+ export declare const table: (implementations: ReadonlyArray<MemoryImplementation>, checked: boolean, evidence: ReadonlyArray<Evidence>) => MemoryOperators;
7
+ /** An implementation, its operator's null rule checked against the function chosen for it. */
8
+ export declare const implementation: (operator: OperatorDescriptor, nulls: OperatorDescriptor['nulls'], run: (...args: ReadonlyArray<unknown>) => unknown) => MemoryImplementation;
9
+ /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
10
+ export declare const kernelOperators: MemoryOperators;
11
+ //# sourceMappingURL=memoryTable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memoryTable.d.ts","names":[],"sources":["../src/memoryTable.ts"],"mappings":";;;qBAgBa,SAAM,UAAc;qBAGpB,OAAI;qBAIJ,QAAK,iBACC,cAAc,uBAAqB,kBACpC,UACN,cAAc,cACvB;;qBA+BU,iBAAc,UACf,oBAAkB,OACrB,6BAA2B,SACzB,MAAM,uCACd;;qBAoDU,iBAAe"}
@@ -0,0 +1,69 @@
1
+ import { Option } from "effect";
2
+ import { Collation } from "./collation.js";
3
+ import { Text } from "./text.js";
4
+ // src/memoryTable.ts
5
+ /**
6
+ * The in-memory operator table and the kernel's own operators. Apart from
7
+ * `Operators` so evaluating a body keeps none of what describes an operator.
8
+ */
9
+ /** An operator by its id, and its version when that is not the first. */
10
+ const nameOf = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
11
+ const fail = (what) => {
12
+ throw new Error(`[foldkit-entity] Operators: ${what}`);
13
+ };
14
+ const table = (implementations, checked, evidence) => {
15
+ const byOperator = /* @__PURE__ */ new Map();
16
+ const byName = /* @__PURE__ */ new Map();
17
+ for (const { operator, run } of implementations) {
18
+ if (byOperator.has(operator)) fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`);
19
+ const named = byName.get(nameOf(operator));
20
+ if (named !== void 0 && named !== operator) fail(`two operators are named ${nameOf(operator)}; give one another id or version`);
21
+ byName.set(nameOf(operator), operator);
22
+ byOperator.set(operator, run);
23
+ }
24
+ return Object.freeze({
25
+ _tag: "MemoryOperators",
26
+ has: (operator) => byOperator.has(operator),
27
+ versions: (id) => implementations.filter(({ operator }) => operator.id === id).map(({ operator }) => operator.version),
28
+ get: (operator) => Option.fromUndefinedOr(byOperator.get(operator)),
29
+ named: (name) => Option.fromUndefinedOr(byName.get(name)),
30
+ checked,
31
+ implementations: Object.freeze([...implementations]),
32
+ evidence: Object.freeze([...evidence])
33
+ });
34
+ };
35
+ /** An implementation, its operator's null rule checked against the function chosen for it. */
36
+ const implementation = (operator, nulls, run) => {
37
+ if (Option.isSome(operator.definedAs)) fail(`${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`);
38
+ if (operator.nulls !== nulls) fail(nulls === "strict" ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls` : `${nameOf(operator)} is strict about null; implement it with Operators.implement`);
39
+ return Object.freeze({
40
+ operator,
41
+ run: (args, context) => run(...args, context)
42
+ });
43
+ };
44
+ const REPLACEMENT = String.fromCharCode(65533);
45
+ /**
46
+ * Text's characters as a database holds them: a lone surrogate, which UTF-8
47
+ * cannot encode, as U+FFFD, which SQLite's and Postgres's drivers send instead.
48
+ */
49
+ const charactersOf = (text) => Array.from(text, (each) => {
50
+ const code = each.codePointAt(0);
51
+ return code >= 55296 && code <= 57343 ? REPLACEMENT : each;
52
+ });
53
+ /**
54
+ * Whether `text` begins with `prefix` by character, as SQL's `substr` and
55
+ * `left` count: `String.prototype.startsWith` compares UTF-16 units, so half
56
+ * of an astral character would begin the text that holds all of it.
57
+ */
58
+ const beginsWith = (text, prefix) => {
59
+ const [characters, start] = [charactersOf(text), charactersOf(prefix)];
60
+ return start.length <= characters.length && start.every((each, i) => each === characters[i]);
61
+ };
62
+ /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
63
+ const kernelOperators = table([implementation(Text.startsWith.descriptor, "strict", (...given) => {
64
+ const [text, prefix, { collation }] = given;
65
+ return Option.exists(collation, (each) => each._tag === "AsciiFold") ? beginsWith(Collation.foldAscii(text), Collation.foldAscii(prefix)) : beginsWith(text, prefix);
66
+ })], false, []);
67
+ export { fail, implementation, kernelOperators, nameOf, table };
68
+
69
+ //# sourceMappingURL=memoryTable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memoryTable.js","names":[],"sources":["../src/memoryTable.ts"],"sourcesContent":["/**\n * The in-memory operator table and the kernel's own operators. Apart from\n * `Operators` so evaluating a body keeps none of what describes an operator.\n */\nimport { Option } from 'effect'\nimport { Collation } from './collation.js'\nimport type { OperatorDescriptor } from './expr.js'\nimport type {\n Evidence,\n MemoryImplementation,\n MemoryOperators,\n OperatorContext,\n} from './operators.js'\nimport { Text } from './text.js'\n\n/** An operator by its id, and its version when that is not the first. */\nexport const nameOf = (operator: OperatorDescriptor): string =>\n operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`\n\nexport const fail = (what: string): never => {\n throw new Error(`[foldkit-entity] Operators: ${what}`)\n}\n\nexport const table = (\n implementations: ReadonlyArray<MemoryImplementation>,\n checked: boolean,\n evidence: ReadonlyArray<Evidence>,\n): MemoryOperators => {\n const byOperator = new Map<OperatorDescriptor, MemoryImplementation['run']>()\n const byName = new Map<string, OperatorDescriptor>()\n for (const { operator, run } of implementations) {\n if (byOperator.has(operator)) {\n fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`)\n }\n // Two descriptors under one name would leave a body's call ambiguous.\n const named = byName.get(nameOf(operator))\n if (named !== undefined && named !== operator) {\n fail(`two operators are named ${nameOf(operator)}; give one another id or version`)\n }\n byName.set(nameOf(operator), operator)\n byOperator.set(operator, run)\n }\n return Object.freeze({\n _tag: 'MemoryOperators',\n has: (operator: OperatorDescriptor) => byOperator.has(operator),\n versions: (id: string) =>\n implementations\n .filter(({ operator }) => operator.id === id)\n .map(({ operator }) => operator.version),\n get: (operator: OperatorDescriptor) => Option.fromUndefinedOr(byOperator.get(operator)),\n named: (name: string) => Option.fromUndefinedOr(byName.get(name)),\n checked,\n implementations: Object.freeze([...implementations]),\n evidence: Object.freeze([...evidence]),\n })\n}\n\n/** An implementation, its operator's null rule checked against the function chosen for it. */\nexport const implementation = (\n operator: OperatorDescriptor,\n nulls: OperatorDescriptor['nulls'],\n run: (...args: ReadonlyArray<unknown>) => unknown,\n): MemoryImplementation => {\n // SQL compiles what a defined operator means, so an implementation here would\n // be a second meaning that only memory runs.\n if (Option.isSome(operator.definedAs)) {\n fail(\n `${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`,\n )\n }\n if (operator.nulls !== nulls) {\n fail(\n nulls === 'strict'\n ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls`\n : `${nameOf(operator)} is strict about null; implement it with Operators.implement`,\n )\n }\n return Object.freeze({\n operator,\n run: (args: ReadonlyArray<unknown>, context: OperatorContext) => run(...args, context),\n })\n}\n\nconst REPLACEMENT = String.fromCharCode(0xfffd)\n\n/**\n * Text's characters as a database holds them: a lone surrogate, which UTF-8\n * cannot encode, as U+FFFD, which SQLite's and Postgres's drivers send instead.\n */\nconst charactersOf = (text: string): ReadonlyArray<string> =>\n Array.from(text, each => {\n const code = each.codePointAt(0)!\n return code >= 0xd800 && code <= 0xdfff ? REPLACEMENT : each\n })\n\n/**\n * Whether `text` begins with `prefix` by character, as SQL's `substr` and\n * `left` count: `String.prototype.startsWith` compares UTF-16 units, so half\n * of an astral character would begin the text that holds all of it.\n */\nconst beginsWith = (text: string, prefix: string): boolean => {\n const [characters, start] = [charactersOf(text), charactersOf(prefix)]\n return start.length <= characters.length && start.every((each, i) => each === characters[i])\n}\n\nconst startsWith = implementation(Text.startsWith.descriptor, 'strict', (...given) => {\n const [text, prefix, { collation }] = given as [string, string, OperatorContext]\n const folded = Option.exists(collation, each => each._tag === 'AsciiFold')\n return folded\n ? beginsWith(Collation.foldAscii(text), Collation.foldAscii(prefix))\n : beginsWith(text, prefix)\n})\n\n/** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */\nexport const kernelOperators = table([startsWith], false, [])\n"],"mappings":";;;;;;;;;AAgBA,MAAa,UAAU,aACrB,SAAS,YAAY,IAAI,SAA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;WACW;WACT;WACD;;;YAYP,iBAAiB,QAAQ;WAAqB;;;;;;;;qBAW7C,qBAAmB,OAAA;;;;;;;;;;;;;;;;;YAapB,6BAA6B,oBAAoB;;iBAG5C,4BAA4B;WAClC,UAAU,cAAc;;;iBAiBlB,wBAAwB;WAC9B;WACA,MAAM,UAAU,uBAAuB,OAAO,OAAO;;;;;WAKrD,QAAQ,iBAAiB,OAAO,OAAO;;WAEvC;WACA,iBAAiB,cAAc;;WAE/B,UAAU,cAAc;;KAG9B,SAAS,UAAU,OAAO,OAAO,OAAO,MAAM,QAAQ;qBAY9C;;;;;;;;;;EAUC,YAAA,WAAW,cAAc,OAAO,MAAM,YAAY,OAAO,KAAG,UAC5D,SAAS,IAAI,MAAI,SAEtB,sBAAsB,WAAW,KAAK,YAAY,SAAS,GAAG,SAAQ,qBACtE,SAAS,SACb;;;;;EAWsB,yBAAA,WAAW,cAAc,OAAO,MAAM,YAAY,OAAO,KAAG,UACzE,SAAS,IAAI,MAAI,SAEtB,sBAAsB,WAAW,KAAK,SAAS,GAAG,QAAO,qBACzD,SAAS,gBACb;;EAQ0B,YAAA,iBAAA,cAAc,0BAAwB;;EAIrD,QAAA,MAAA,iBAAe,OAAS,oBAAkB;;;;;;EAoBhD,WAAA,MAAA,oBAAe,iBACD,cAAc,0BACjC;;;;;;;;EAwBkB,eAAA,MAAA,iBAAe,UAAY,cAAc,cAAY;;;;;EAmCvD,WAAA,QAAA,aAAW,OAAO,OAAO;;;;;;;;;;;;EAmBtB,gBAAA,MAAA,oBAAkB,cAAc;;;;;;;;EAajC,WAAA;aAAW,YAAY;QAAuB;;;;;;EAQnD,UAAA,MAAA,oBAAkB"}
package/dist/operators.js CHANGED
@@ -1,16 +1,9 @@
1
1
  import { Data, Equivalence, Option, Schema } from "effect";
2
- import { Collation } from "./collation.js";
2
+ import { fail, implementation, kernelOperators, nameOf, table } from "./memoryTable.js";
3
3
  import { Law, LawDescription } from "./law.js";
4
- import { Text } from "./text.js";
5
4
  import { jsonSchemaOf } from "./jsonSchema.js";
6
5
  import { tableTested, testedByRunner } from "./tested.js";
7
6
  // src/operators.ts
8
- /**
9
- * How the in-memory interpreter runs primitive operators: a table of
10
- * implementations, passed to `evaluate` and every judge as a value. A table is
11
- * immutable and implements each operator once; nothing registers anything
12
- * globally. See `docs/design/expr-operations-DESIGN.md` §5.4.
13
- */
14
7
  const Evidence = Data.taggedEnum();
15
8
  /** A JSON Schema document's root: an object (`$defs` holds what it refers to). */
16
9
  const JsonSchema = Schema.Record(Schema.String, Schema.Unknown);
@@ -49,68 +42,11 @@ const described = (operator) => ({
49
42
  laws: operator.laws.map(Law.describe),
50
43
  defined: Option.isSome(operator.definedAs)
51
44
  });
52
- /** An operator by its id, and its version when that is not the first. */
53
- const nameOf = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
54
- const fail = (what) => {
55
- throw new Error(`[foldkit-entity] Operators: ${what}`);
56
- };
57
- const table = (implementations, checked, evidence) => {
58
- const byOperator = /* @__PURE__ */ new Map();
59
- const byName = /* @__PURE__ */ new Map();
60
- for (const { operator, run } of implementations) {
61
- if (byOperator.has(operator)) fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`);
62
- const named = byName.get(nameOf(operator));
63
- if (named !== void 0 && named !== operator) fail(`two operators are named ${nameOf(operator)}; give one another id or version`);
64
- byName.set(nameOf(operator), operator);
65
- byOperator.set(operator, run);
66
- }
67
- return Object.freeze({
68
- _tag: "MemoryOperators",
69
- has: (operator) => byOperator.has(operator),
70
- versions: (id) => implementations.filter(({ operator }) => operator.id === id).map(({ operator }) => operator.version),
71
- get: (operator) => Option.fromUndefinedOr(byOperator.get(operator)),
72
- named: (name) => Option.fromUndefinedOr(byName.get(name)),
73
- checked,
74
- implementations: Object.freeze([...implementations]),
75
- evidence: Object.freeze([...evidence])
76
- });
77
- };
78
45
  /** Whether two laws, as JSON, are the same law. */
79
46
  const sameLaw = (left, right) => JSON.stringify(left) === JSON.stringify(right);
80
47
  /** What a table runs for the operator under `name`: none when it implements none. */
81
48
  const runNamed = (operators, name) => Option.flatMap(operators.named(name), operators.get);
82
49
  const sameRun = Option.makeEquivalence(Equivalence.strictEqual());
83
- /** An implementation, its operator's null rule checked against the function chosen for it. */
84
- const implementation = (operator, nulls, run) => {
85
- if (Option.isSome(operator.definedAs)) fail(`${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`);
86
- if (operator.nulls !== nulls) fail(nulls === "strict" ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls` : `${nameOf(operator)} is strict about null; implement it with Operators.implement`);
87
- return Object.freeze({
88
- operator,
89
- run: (args, context) => run(...args, context)
90
- });
91
- };
92
- const REPLACEMENT = String.fromCharCode(65533);
93
- /**
94
- * Text's characters as a database holds them: a lone surrogate, which UTF-8
95
- * cannot encode, as U+FFFD, which SQLite's and Postgres's drivers send instead.
96
- */
97
- const charactersOf = (text) => Array.from(text, (each) => {
98
- const code = each.codePointAt(0);
99
- return code >= 55296 && code <= 57343 ? REPLACEMENT : each;
100
- });
101
- /**
102
- * Whether `text` begins with `prefix` by character, as SQL's `substr` and
103
- * `left` count: `String.prototype.startsWith` compares UTF-16 units, so half
104
- * of an astral character would begin the text that holds all of it.
105
- */
106
- const beginsWith = (text, prefix) => {
107
- const [characters, start] = [charactersOf(text), charactersOf(prefix)];
108
- return start.length <= characters.length && start.every((each, i) => each === characters[i]);
109
- };
110
- const startsWith = implementation(Text.startsWith.descriptor, "strict", (...given) => {
111
- const [text, prefix, { collation }] = given;
112
- return Option.exists(collation, (each) => each._tag === "AsciiFold") ? beginsWith(Collation.foldAscii(text), Collation.foldAscii(prefix)) : beginsWith(text, prefix);
113
- });
114
50
  const Operators = {
115
51
  /**
116
52
  * An implementation of a strict operator: a pure function of its arguments'
@@ -200,7 +136,7 @@ const Operators = {
200
136
  */
201
137
  checked: (base) => table(base.implementations, true, base.evidence),
202
138
  /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
203
- kernel: table([startsWith], false, [])
139
+ kernel: kernelOperators
204
140
  };
205
141
  export { Evidence, OperatorDescription, Operators };
206
142
 
@@ -1 +1 @@
1
- {"version":3,"file":"operators.js","names":[],"sources":["../src/operators.ts"],"sourcesContent":["/**\n * How the in-memory interpreter runs primitive operators: a table of\n * implementations, passed to `evaluate` and every judge as a value. A table is\n * immutable and implements each operator once; nothing registers anything\n * globally. See `docs/design/expr-operations-DESIGN.md` §5.4.\n */\nimport { Data, Equivalence, Option, Schema } from 'effect'\nimport { Collation } from './collation.js'\nimport type { Operator, OperatorDescriptor, OperatorTable } from './expr.js'\nimport { Law, LawDescription } from './law.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\nimport { tableTested, testedByRunner } from './tested.js'\nimport { Text } from './text.js'\n\n/** What an implementation is told besides its arguments. */\nexport interface OperatorContext {\n /** The collation the call compares text under, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/** One operator's in-memory implementation: a pure function of stored values. */\nexport interface MemoryImplementation {\n readonly operator: OperatorDescriptor\n readonly run: (args: ReadonlyArray<unknown>, context: OperatorContext) => unknown\n}\n\n/**\n * What is known of a law of an implementation, past its operator claiming it\n * (expr-operations-DESIGN §10.3): `Tested`, it passed `Conformance.laws`'\n * cases; `Proven`, a proof elsewhere says so under its assumptions, recorded\n * and never checked here.\n */\nexport type Evidence = Data.TaggedEnum<{\n Tested: {\n readonly operator: string\n readonly law: LawDescription\n readonly implementation: string\n readonly cases: number\n readonly seed: number\n }\n Proven: {\n readonly operator: string\n readonly law: LawDescription\n readonly reference: string\n readonly assumptions: ReadonlyArray<string>\n }\n}>\nexport const Evidence = Data.taggedEnum<Evidence>()\n\n/** A record of a law passing `Conformance.laws`' cases. */\nexport type TestedEvidence = Extract<Evidence, { readonly _tag: 'Tested' }>\n\n/** A JSON Schema document's root: an object (`$defs` holds what it refers to). */\nconst JsonSchema = Schema.Record(Schema.String, Schema.Unknown)\n\n/**\n * An operator as JSON, by its signature and never its body (a defined\n * operator says `defined`, not what it means): what a server can publish of\n * what a body may call, and a client compare with what it runs. Its schemas\n * are each argument's and the result's stored side, as JSON Schemas.\n */\nexport const OperatorDescription = Schema.Struct({\n /** By id, and `@version` past the first: what tables, evidence and refusals name. */\n name: Schema.String,\n id: Schema.String,\n version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n description: Schema.NullOr(Schema.String),\n input: Schema.Array(JsonSchema),\n output: JsonSchema,\n nulls: Schema.Literals(['strict', 'handled']),\n collation: Schema.Literals(['none', 'operands', 'required']),\n laws: Schema.Array(LawDescription),\n defined: Schema.Boolean,\n})\nexport type OperatorDescription = typeof OperatorDescription.Type\n\n/** One operator a table implements, as `Operators.describeTable` lists it: described, with its evidence. */\nexport interface ImplementedOperator extends OperatorDescription {\n readonly evidence: ReadonlyArray<Evidence>\n}\n\nconst described = (operator: OperatorDescriptor): OperatorDescription => ({\n name: nameOf(operator),\n id: operator.id,\n version: operator.version,\n description: Option.getOrNull(operator.description),\n input: operator.input.map(jsonSchemaOf),\n output: jsonSchemaOf(operator.output),\n nulls: operator.nulls,\n collation: operator.collation,\n laws: operator.laws.map(Law.describe),\n defined: Option.isSome(operator.definedAs),\n})\n\n/** The in-memory interpreter's implementations, by operator. */\nexport interface MemoryOperators extends OperatorTable {\n readonly _tag: 'MemoryOperators'\n readonly get: (operator: OperatorDescriptor) => Option.Option<MemoryImplementation['run']>\n /**\n * The operator it implements under a name (`id`, or `id@version` past the\n * first): how a computed assignment carried as data finds what to run.\n */\n readonly named: (name: string) => Option.Option<OperatorDescriptor>\n /** Whether each answer is checked against its operator's output schema: for tests. */\n readonly checked: boolean\n readonly implementations: ReadonlyArray<MemoryImplementation>\n /** What is known of its implementations' laws: `Operators.withEvidence`. */\n readonly evidence: ReadonlyArray<Evidence>\n}\n\ntype StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>\n\n/** An operator by its id, and its version when that is not the first. */\nconst nameOf = (operator: OperatorDescriptor): string =>\n operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`\n\nconst fail = (what: string): never => {\n throw new Error(`[foldkit-entity] Operators: ${what}`)\n}\n\nconst table = (\n implementations: ReadonlyArray<MemoryImplementation>,\n checked: boolean,\n evidence: ReadonlyArray<Evidence>,\n): MemoryOperators => {\n const byOperator = new Map<OperatorDescriptor, MemoryImplementation['run']>()\n const byName = new Map<string, OperatorDescriptor>()\n for (const { operator, run } of implementations) {\n if (byOperator.has(operator)) {\n fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`)\n }\n // Two descriptors under one name would leave a body's call ambiguous.\n const named = byName.get(nameOf(operator))\n if (named !== undefined && named !== operator) {\n fail(`two operators are named ${nameOf(operator)}; give one another id or version`)\n }\n byName.set(nameOf(operator), operator)\n byOperator.set(operator, run)\n }\n return Object.freeze({\n _tag: 'MemoryOperators',\n has: (operator: OperatorDescriptor) => byOperator.has(operator),\n versions: (id: string) =>\n implementations\n .filter(({ operator }) => operator.id === id)\n .map(({ operator }) => operator.version),\n get: (operator: OperatorDescriptor) => Option.fromUndefinedOr(byOperator.get(operator)),\n named: (name: string) => Option.fromUndefinedOr(byName.get(name)),\n checked,\n implementations: Object.freeze([...implementations]),\n evidence: Object.freeze([...evidence]),\n })\n}\n\n/** Whether two laws, as JSON, are the same law. */\nconst sameLaw = (left: LawDescription, right: LawDescription): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** What a table runs for the operator under `name`: none when it implements none. */\nconst runNamed = (operators: MemoryOperators, name: string) =>\n Option.flatMap(operators.named(name), operators.get)\n\nconst sameRun = Option.makeEquivalence(Equivalence.strictEqual<MemoryImplementation['run']>())\n\n/** An implementation, its operator's null rule checked against the function chosen for it. */\nconst implementation = (\n operator: OperatorDescriptor,\n nulls: OperatorDescriptor['nulls'],\n run: (...args: ReadonlyArray<unknown>) => unknown,\n): MemoryImplementation => {\n // SQL compiles what a defined operator means, so an implementation here would\n // be a second meaning that only memory runs.\n if (Option.isSome(operator.definedAs)) {\n fail(\n `${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`,\n )\n }\n if (operator.nulls !== nulls) {\n fail(\n nulls === 'strict'\n ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls`\n : `${nameOf(operator)} is strict about null; implement it with Operators.implement`,\n )\n }\n return Object.freeze({\n operator,\n run: (args: ReadonlyArray<unknown>, context: OperatorContext) => run(...args, context),\n })\n}\n\nconst REPLACEMENT = String.fromCharCode(0xfffd)\n\n/**\n * Text's characters as a database holds them: a lone surrogate, which UTF-8\n * cannot encode, as U+FFFD, which SQLite's and Postgres's drivers send instead.\n */\nconst charactersOf = (text: string): ReadonlyArray<string> =>\n Array.from(text, each => {\n const code = each.codePointAt(0)!\n return code >= 0xd800 && code <= 0xdfff ? REPLACEMENT : each\n })\n\n/**\n * Whether `text` begins with `prefix` by character, as SQL's `substr` and\n * `left` count: `String.prototype.startsWith` compares UTF-16 units, so half\n * of an astral character would begin the text that holds all of it.\n */\nconst beginsWith = (text: string, prefix: string): boolean => {\n const [characters, start] = [charactersOf(text), charactersOf(prefix)]\n return start.length <= characters.length && start.every((each, i) => each === characters[i])\n}\n\nconst startsWith = implementation(Text.startsWith.descriptor, 'strict', (...given) => {\n const [text, prefix, { collation }] = given as [string, string, OperatorContext]\n const folded = Option.exists(collation, each => each._tag === 'AsciiFold')\n return folded\n ? beginsWith(Collation.foldAscii(text), Collation.foldAscii(prefix))\n : beginsWith(text, prefix)\n})\n\nexport const Operators = {\n /**\n * An implementation of a strict operator: a pure function of its arguments'\n * stored values, never given a null (the kernel answers null, or unknown, for\n * one first), and told the call's collation last.\n *\n * ```ts\n * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))\n * ```\n */\n implement: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: NonNullable<StoredOf<In[K]>> }, OperatorContext]\n ) => StoredOf<Out>,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'strict',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /**\n * An implementation of an operator declared `nulls: 'handled'`: given nulls\n * as they are, it answers for them; a predicate answers `null` for unknown.\n */\n implementHandlingNulls: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: StoredOf<In[K]> }, OperatorContext]\n ) => StoredOf<Out> | null,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'handled',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /** A table of implementations. One operator implemented twice, or two under one name, is refused. */\n memory: (...implementations: ReadonlyArray<MemoryImplementation>): MemoryOperators =>\n table(implementations, false, []),\n\n /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */\n merge: (left: MemoryOperators, right: MemoryOperators): MemoryOperators => {\n const both = right.implementations.filter(({ operator }) => left.has(operator))\n if (both.length > 0) {\n fail(\n `both tables implement ${both.map(({ operator }) => nameOf(operator)).join(', ')}; replace with Operators.override`,\n )\n }\n return table(\n [...left.implementations, ...right.implementations],\n left.checked || right.checked,\n [...left.evidence, ...right.evidence],\n )\n },\n\n /**\n * The table with these implementations in place of its own for the same\n * operators. Evidence of a replaced implementation goes with it: it was\n * that implementation's.\n */\n override: (\n base: MemoryOperators,\n ...implementations: ReadonlyArray<MemoryImplementation>\n ): MemoryOperators => {\n const replaced = new Set(implementations.map(({ operator }) => operator))\n const names = new Set([...replaced].map(nameOf))\n return table(\n [\n ...base.implementations.filter(({ operator }) => !replaced.has(operator)),\n ...implementations,\n ],\n base.checked,\n // A replaced operator's evidence goes, and so does a law's that called it as a witness.\n base.evidence.filter(\n ({ operator, law }) =>\n !names.has(operator) && !Law.witnessesNamed(law).some(name => names.has(name)),\n ),\n )\n },\n\n /**\n * The table with what is known of its implementations' laws recorded: each\n * record of an operator it implements and a law that operator declares.\n * `Conformance.laws` gives `Tested` records, each of the implementation it\n * ran, and a table takes only those of its own; `Evidence.Proven` says a\n * proof elsewhere covers one.\n */\n withEvidence: (base: MemoryOperators, evidence: ReadonlyArray<Evidence>): MemoryOperators => {\n const own = new Map(base.implementations.map(each => [nameOf(each.operator), each]))\n for (const record of evidence) {\n const implemented =\n own.get(record.operator) ??\n fail(`evidence names ${record.operator}, which this table does not implement`)\n if (!implemented.operator.laws.map(Law.describe).some(law => sameLaw(law, record.law))) {\n fail(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`)\n }\n if (record._tag !== 'Tested') continue\n // Evidence of another implementation, or of a runner, says nothing of this one.\n const tested = tableTested(record)\n if (!Option.exists(tested, table => table.implementations.includes(implemented))) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was not tested on this table's implementation; test it with Conformance.laws(op, table)`,\n )\n }\n // Nor with another implementation of a witness the law calls (`distributes`, `inverse`).\n const other = Law.witnessesNamed(record.law).find(\n name =>\n !Option.exists(tested, table => sameRun(runNamed(table, name), runNamed(base, name))),\n )\n if (other !== undefined) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was tested with another implementation of ${other}, which it calls; test it with Conformance.laws(op, table)`,\n )\n }\n }\n return table(base.implementations, base.checked, [...base.evidence, ...evidence])\n },\n\n /**\n * The memory implementation `Conformance.laws` tested a record on; none for\n * a record of a runner (`Conformance.lawsBy`) or a proof.\n */\n testedOn: (record: Evidence): Option.Option<MemoryImplementation> =>\n Option.flatMap(tableTested(record), table =>\n Option.fromUndefinedOr(\n table.implementations.find(({ operator }) => nameOf(operator) === record.operator),\n ),\n ),\n\n /**\n * Whether `Conformance.lawsBy` made a record, through a runner: what an SQL\n * table takes. Which runner it was, the database's or another, is the\n * caller's word; a record built by hand, copied, or tested in memory is not.\n */\n testedByRunner,\n\n /**\n * Each operator the table implements, by name, with the laws it declares and\n * the evidence the table records of them: what a server can publish of how\n * it runs a body. JSON as it is.\n */\n describeTable: (base: MemoryOperators): ReadonlyArray<ImplementedOperator> =>\n base.implementations.map(({ operator }) => ({\n ...described(operator),\n evidence: base.evidence.filter(record => record.operator === nameOf(operator)),\n })),\n\n /**\n * An operator as JSON (`OperatorDescription`): its name, version and\n * description, each argument's and its result's stored side as a JSON\n * Schema (as JSON carries it: a number also admits the strings `\"Infinity\"`,\n * `\"-Infinity\"` and `\"NaN\"`), its null and collation rules, its laws, and\n * whether it is defined. Its signature, never its body.\n */\n describe: (operator: { readonly descriptor: OperatorDescriptor }): OperatorDescription =>\n described(operator.descriptor),\n\n /**\n * The table, checking every answer against its operator's output schema, so\n * an implementation that answers the wrong kind fails where it answered. For\n * tests: it costs a decode per call.\n */\n checked: (base: MemoryOperators): MemoryOperators =>\n table(base.implementations, true, base.evidence),\n\n /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */\n kernel: table([startsWith], false, []),\n}\n"],"mappings":";;;;;;;;;;;;;AA+CA,MAAa,WAAW,KAAK,WAAqB;;AAMlD,MAAM,aAAa,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;;;;;;;AAQ9D,MAAa,sBAAsB,OAAO,OAAO;;CAE/C,MAAM,OAAO;CACb,IAAI,OAAO;CACX,SAAS,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC1D,aAAa,OAAO,OAAO,OAAO,MAAM;CACxC,OAAO,OAAO,MAAM,UAAU;CAC9B,QAAQ;CACR,OAAO,OAAO,SAAS,CAAC,UAAU,SAAS,CAAC;CAC5C,WAAW,OAAO,SAAS;EAAC;EAAQ;EAAY;CAAU,CAAC;CAC3D,MAAM,OAAO,MAAM,cAAc;CACjC,SAAS,OAAO;AAClB,CAAC;AAQD,MAAM,aAAa,cAAuD;CACxE,MAAM,OAAO,QAAQ;CACrB,IAAI,SAAS;CACb,SAAS,SAAS;CAClB,aAAa,OAAO,UAAU,SAAS,WAAW;CAClD,OAAO,SAAS,MAAM,IAAI,YAAY;CACtC,QAAQ,aAAa,SAAS,MAAM;CACpC,OAAO,SAAS;CAChB,WAAW,SAAS;CACpB,MAAM,SAAS,KAAK,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B,OAAO,IAAI,KAAK,EAAE;GAE5F,IAAI,OAAO,SAAS,UAAU;GAE9B,MAAM,SAAS,YAAY,MAAM;GACjC,IAAI,CAAC,OAAO,OAAO,SAAQ,UAAS,MAAM,gBAAgB,SAAS,WAAW,CAAC,GAC7E,KACE,eAAe,OAAO,SAAS,KAAK,OAAO,IAAI,KAAK,6FACtD;GAGF,MAAM,QAAQ,IAAI,eAAe,OAAO,GAAG,CAAC,CAAC,MAC3C,SACE,CAAC,OAAO,OAAO,SAAQ,UAAS,QAAQ,SAAS,OAAO,IAAI,GAAG,SAAS,MAAM,IAAI,CAAC,CAAC,CACxF;GACA,IAAI,UAAU,KAAA,GACZ,KACE,eAAe,OAAO,SAAS,KAAK,OAAO,IAAI,KAAK,iDAAiD,MAAM,2DAC7G;EAEJ;EACA,OAAO,MAAM,KAAK,iBAAiB,KAAK,SAAS,CAAC,GAAG,KAAK,UAAU,GAAG,QAAQ,CAAC;CAClF;;;;;CAMA,WAAW,WACT,OAAO,QAAQ,YAAY,MAAM,IAAG,UAClC,OAAO,gBACL,MAAM,gBAAgB,MAAM,EAAE,eAAe,OAAO,QAAQ,MAAM,OAAO,QAAQ,CACnF,CACF;;;;;;CAOF;;;;;;CAOA,gBAAgB,SACd,KAAK,gBAAgB,KAAK,EAAE,gBAAgB;EAC1C,GAAG,UAAU,QAAQ;EACrB,UAAU,KAAK,SAAS,QAAO,WAAU,OAAO,aAAa,OAAO,QAAQ,CAAC;CAC/E,EAAE;;;;;;;;CASJ,WAAW,aACT,UAAU,SAAS,UAAU;;;;;;CAO/B,UAAU,SACR,MAAM,KAAK,iBAAiB,MAAM,KAAK,QAAQ;;CAGjD,QAAQ,MAAM,CAAC,UAAU,GAAG,OAAO,CAAC,CAAC;AACvC"}
1
+ {"version":3,"file":"operators.js","names":[],"sources":["../src/operators.ts"],"sourcesContent":["/**\n * How the in-memory interpreter runs primitive operators: a table of\n * implementations, passed to `evaluate` and every judge as a value. A table is\n * immutable and implements each operator once; nothing registers anything\n * globally. See `docs/design/expr-operations-DESIGN.md` §5.4.\n */\nimport type { Collation } from './collation.js'\nimport { Data, Equivalence, Option, Schema } from 'effect'\nimport type { Operator, OperatorDescriptor, OperatorTable } from './expr.js'\nimport { Law, LawDescription } from './law.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\nimport { tableTested, testedByRunner } from './tested.js'\nimport { fail, implementation, kernelOperators, nameOf, table } from './memoryTable.js'\n\n/** What an implementation is told besides its arguments. */\nexport interface OperatorContext {\n /** The collation the call compares text under, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/** One operator's in-memory implementation: a pure function of stored values. */\nexport interface MemoryImplementation {\n readonly operator: OperatorDescriptor\n readonly run: (args: ReadonlyArray<unknown>, context: OperatorContext) => unknown\n}\n\n/**\n * What is known of a law of an implementation, past its operator claiming it\n * (expr-operations-DESIGN §10.3): `Tested`, it passed `Conformance.laws`'\n * cases; `Proven`, a proof elsewhere says so under its assumptions, recorded\n * and never checked here.\n */\nexport type Evidence = Data.TaggedEnum<{\n Tested: {\n readonly operator: string\n readonly law: LawDescription\n readonly implementation: string\n readonly cases: number\n readonly seed: number\n }\n Proven: {\n readonly operator: string\n readonly law: LawDescription\n readonly reference: string\n readonly assumptions: ReadonlyArray<string>\n }\n}>\nexport const Evidence = Data.taggedEnum<Evidence>()\n\n/** A record of a law passing `Conformance.laws`' cases. */\nexport type TestedEvidence = Extract<Evidence, { readonly _tag: 'Tested' }>\n\n/** A JSON Schema document's root: an object (`$defs` holds what it refers to). */\nconst JsonSchema = Schema.Record(Schema.String, Schema.Unknown)\n\n/**\n * An operator as JSON, by its signature and never its body (a defined\n * operator says `defined`, not what it means): what a server can publish of\n * what a body may call, and a client compare with what it runs. Its schemas\n * are each argument's and the result's stored side, as JSON Schemas.\n */\nexport const OperatorDescription = Schema.Struct({\n /** By id, and `@version` past the first: what tables, evidence and refusals name. */\n name: Schema.String,\n id: Schema.String,\n version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n description: Schema.NullOr(Schema.String),\n input: Schema.Array(JsonSchema),\n output: JsonSchema,\n nulls: Schema.Literals(['strict', 'handled']),\n collation: Schema.Literals(['none', 'operands', 'required']),\n laws: Schema.Array(LawDescription),\n defined: Schema.Boolean,\n})\nexport type OperatorDescription = typeof OperatorDescription.Type\n\n/** One operator a table implements, as `Operators.describeTable` lists it: described, with its evidence. */\nexport interface ImplementedOperator extends OperatorDescription {\n readonly evidence: ReadonlyArray<Evidence>\n}\n\nconst described = (operator: OperatorDescriptor): OperatorDescription => ({\n name: nameOf(operator),\n id: operator.id,\n version: operator.version,\n description: Option.getOrNull(operator.description),\n input: operator.input.map(jsonSchemaOf),\n output: jsonSchemaOf(operator.output),\n nulls: operator.nulls,\n collation: operator.collation,\n laws: operator.laws.map(Law.describe),\n defined: Option.isSome(operator.definedAs),\n})\n\n/** The in-memory interpreter's implementations, by operator. */\nexport interface MemoryOperators extends OperatorTable {\n readonly _tag: 'MemoryOperators'\n readonly get: (operator: OperatorDescriptor) => Option.Option<MemoryImplementation['run']>\n /**\n * The operator it implements under a name (`id`, or `id@version` past the\n * first): how a computed assignment carried as data finds what to run.\n */\n readonly named: (name: string) => Option.Option<OperatorDescriptor>\n /** Whether each answer is checked against its operator's output schema: for tests. */\n readonly checked: boolean\n readonly implementations: ReadonlyArray<MemoryImplementation>\n /** What is known of its implementations' laws: `Operators.withEvidence`. */\n readonly evidence: ReadonlyArray<Evidence>\n}\n\ntype StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>\n\n/** Whether two laws, as JSON, are the same law. */\nconst sameLaw = (left: LawDescription, right: LawDescription): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** What a table runs for the operator under `name`: none when it implements none. */\nconst runNamed = (operators: MemoryOperators, name: string) =>\n Option.flatMap(operators.named(name), operators.get)\n\nconst sameRun = Option.makeEquivalence(Equivalence.strictEqual<MemoryImplementation['run']>())\n\nexport const Operators = {\n /**\n * An implementation of a strict operator: a pure function of its arguments'\n * stored values, never given a null (the kernel answers null, or unknown, for\n * one first), and told the call's collation last.\n *\n * ```ts\n * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))\n * ```\n */\n implement: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: NonNullable<StoredOf<In[K]>> }, OperatorContext]\n ) => StoredOf<Out>,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'strict',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /**\n * An implementation of an operator declared `nulls: 'handled'`: given nulls\n * as they are, it answers for them; a predicate answers `null` for unknown.\n */\n implementHandlingNulls: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: StoredOf<In[K]> }, OperatorContext]\n ) => StoredOf<Out> | null,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'handled',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /** A table of implementations. One operator implemented twice, or two under one name, is refused. */\n memory: (...implementations: ReadonlyArray<MemoryImplementation>): MemoryOperators =>\n table(implementations, false, []),\n\n /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */\n merge: (left: MemoryOperators, right: MemoryOperators): MemoryOperators => {\n const both = right.implementations.filter(({ operator }) => left.has(operator))\n if (both.length > 0) {\n fail(\n `both tables implement ${both.map(({ operator }) => nameOf(operator)).join(', ')}; replace with Operators.override`,\n )\n }\n return table(\n [...left.implementations, ...right.implementations],\n left.checked || right.checked,\n [...left.evidence, ...right.evidence],\n )\n },\n\n /**\n * The table with these implementations in place of its own for the same\n * operators. Evidence of a replaced implementation goes with it: it was\n * that implementation's.\n */\n override: (\n base: MemoryOperators,\n ...implementations: ReadonlyArray<MemoryImplementation>\n ): MemoryOperators => {\n const replaced = new Set(implementations.map(({ operator }) => operator))\n const names = new Set([...replaced].map(nameOf))\n return table(\n [\n ...base.implementations.filter(({ operator }) => !replaced.has(operator)),\n ...implementations,\n ],\n base.checked,\n // A replaced operator's evidence goes, and so does a law's that called it as a witness.\n base.evidence.filter(\n ({ operator, law }) =>\n !names.has(operator) && !Law.witnessesNamed(law).some(name => names.has(name)),\n ),\n )\n },\n\n /**\n * The table with what is known of its implementations' laws recorded: each\n * record of an operator it implements and a law that operator declares.\n * `Conformance.laws` gives `Tested` records, each of the implementation it\n * ran, and a table takes only those of its own; `Evidence.Proven` says a\n * proof elsewhere covers one.\n */\n withEvidence: (base: MemoryOperators, evidence: ReadonlyArray<Evidence>): MemoryOperators => {\n const own = new Map(base.implementations.map(each => [nameOf(each.operator), each]))\n for (const record of evidence) {\n const implemented =\n own.get(record.operator) ??\n fail(`evidence names ${record.operator}, which this table does not implement`)\n if (!implemented.operator.laws.map(Law.describe).some(law => sameLaw(law, record.law))) {\n fail(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`)\n }\n if (record._tag !== 'Tested') continue\n // Evidence of another implementation, or of a runner, says nothing of this one.\n const tested = tableTested(record)\n if (!Option.exists(tested, table => table.implementations.includes(implemented))) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was not tested on this table's implementation; test it with Conformance.laws(op, table)`,\n )\n }\n // Nor with another implementation of a witness the law calls (`distributes`, `inverse`).\n const other = Law.witnessesNamed(record.law).find(\n name =>\n !Option.exists(tested, table => sameRun(runNamed(table, name), runNamed(base, name))),\n )\n if (other !== undefined) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was tested with another implementation of ${other}, which it calls; test it with Conformance.laws(op, table)`,\n )\n }\n }\n return table(base.implementations, base.checked, [...base.evidence, ...evidence])\n },\n\n /**\n * The memory implementation `Conformance.laws` tested a record on; none for\n * a record of a runner (`Conformance.lawsBy`) or a proof.\n */\n testedOn: (record: Evidence): Option.Option<MemoryImplementation> =>\n Option.flatMap(tableTested(record), table =>\n Option.fromUndefinedOr(\n table.implementations.find(({ operator }) => nameOf(operator) === record.operator),\n ),\n ),\n\n /**\n * Whether `Conformance.lawsBy` made a record, through a runner: what an SQL\n * table takes. Which runner it was, the database's or another, is the\n * caller's word; a record built by hand, copied, or tested in memory is not.\n */\n testedByRunner,\n\n /**\n * Each operator the table implements, by name, with the laws it declares and\n * the evidence the table records of them: what a server can publish of how\n * it runs a body. JSON as it is.\n */\n describeTable: (base: MemoryOperators): ReadonlyArray<ImplementedOperator> =>\n base.implementations.map(({ operator }) => ({\n ...described(operator),\n evidence: base.evidence.filter(record => record.operator === nameOf(operator)),\n })),\n\n /**\n * An operator as JSON (`OperatorDescription`): its name, version and\n * description, each argument's and its result's stored side as a JSON\n * Schema (as JSON carries it: a number also admits the strings `\"Infinity\"`,\n * `\"-Infinity\"` and `\"NaN\"`), its null and collation rules, its laws, and\n * whether it is defined. Its signature, never its body.\n */\n describe: (operator: { readonly descriptor: OperatorDescriptor }): OperatorDescription =>\n described(operator.descriptor),\n\n /**\n * The table, checking every answer against its operator's output schema, so\n * an implementation that answers the wrong kind fails where it answered. For\n * tests: it costs a decode per call.\n */\n checked: (base: MemoryOperators): MemoryOperators =>\n table(base.implementations, true, base.evidence),\n\n /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */\n kernel: kernelOperators,\n}\n"],"mappings":";;;;;;AA+CA,MAAa,WAAW,KAAK,WAAqB;;AAMlD,MAAM,aAAa,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;;;;;;;AAQ9D,MAAa,sBAAsB,OAAO,OAAO;;CAE/C,MAAM,OAAO;CACb,IAAI,OAAO;CACX,SAAS,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC1D,aAAa,OAAO,OAAO,OAAO,MAAM;CACxC,OAAO,OAAO,MAAM,UAAU;CAC9B,QAAQ;CACR,OAAO,OAAO,SAAS,CAAC,UAAU,SAAS,CAAC;CAC5C,WAAW,OAAO,SAAS;EAAC;EAAQ;EAAY;CAAU,CAAC;CAC3D,MAAM,OAAO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IAAI,KAAK,iDAAiD,MAAM,2DAC7G;EAEJ;EACA,OAAO,MAAM,KAAK,iBAAiB,KAAK,SAAS,CAAC,GAAG,KAAK,UAAU,GAAG,QAAQ,CAAC;CAClF;;;;;CAMA,WAAW,WACT,OAAO,QAAQ,YAAY,MAAM,IAAG,UAClC,OAAO,gBACL,MAAM,gBAAgB,MAAM,EAAE,eAAe,OAAO,QAAQ,MAAM,OAAO,QAAQ,CACnF,CACF;;;;;;CAOF;;;;;;CAOA,gBAAgB,SACd,KAAK,gBAAgB,KAAK,EAAE,gBAAgB;EAC1C,GAAG,UAAU,QAAQ;EACrB,UAAU,KAAK,SAAS,QAAO,WAAU,OAAO,aAAa,OAAO,QAAQ,CAAC;CAC/E,EAAE;;;;;;;;CASJ,WAAW,aACT,UAAU,SAAS,UAAU;;;;;;CAO/B,UAAU,SACR,MAAM,KAAK,iBAAiB,MAAM,KAAK,QAAQ;;CAGjD,QAAQ;AACV"}
package/dist/sets.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sets.js","names":[],"sources":["../src/sets.ts"],"sourcesContent":["/**\n * What `Entity.sets` declares: members whose value is the write's context,\n * never its input, and the writes that set them.\n */\nimport { Match, Schema, SchemaAST } from 'effect'\nimport type { NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { AnyEntity, EntityMember } from './index.js'\nimport { SchemaShape } from './shape.js'\n\n/** The writes that set a member: every insert (`create`), or every insert and update (`write`). */\nexport type SetOn = 'create' | 'write'\n\n/** A value the write's context gives: who asks, what their row holds, or when. */\nexport type ContextValue = ViewerExpr<unknown> | ViewerPathExpr<unknown> | NowExpr<unknown>\n\n/** One member `Entity.sets` names: its value, and the writes that set it. */\nexport interface EntitySet {\n readonly value: ContextValue\n readonly on: SetOn\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\n/** How a field's values are stored, nulls aside: as text, as a number, or otherwise. */\nconst storedAs = (schema: Schema.Top): 'text' | 'number' | 'other' => {\n const stored = SchemaShape.present(Schema.toEncoded(schema).ast)\n if (stored.every(SchemaShape.isText)) return 'text'\n if (stored.every(SchemaAST.isNumber)) return 'number'\n return 'other'\n}\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && '_tag' in value ? value._tag : undefined\n\n/**\n * `value` checked against the member `key` it sets, as `Entity.sets` was\n * given them: a relation takes `Expr.viewer` of its target, a field stored as\n * text the viewer's id, a field stored as a number the time.\n */\nexport const checkedSet = (\n entity: AnyEntity,\n key: string,\n value: unknown,\n on: unknown,\n): EntitySet => {\n if (on !== 'create' && on !== 'write') {\n return fail(entity, `sets \"${key}\" on ${String(on)}; say on: 'create' or on: 'write'`)\n }\n if (key === 'id') return fail(entity, 'sets the id, which the client names')\n if (Object.hasOwn(entity.sets, key)) return fail(entity, `\"${key}\" is set already`)\n const tag = tagOf(value)\n if (tag !== 'Viewer' && tag !== 'Now' && tag !== 'ViewerPath') {\n return fail(\n entity,\n `sets \"${key}\" to what is no value of the write's context (Expr.viewer, a path from it, Expr.now); a value from the input is a computed assignment`,\n )\n }\n const context = value as ContextValue\n const relations: Readonly<Record<string, EntityMember>> = entity.relations\n const fields: Readonly<Record<string, EntityMember>> = entity.fields\n const member = Object.hasOwn(relations, key)\n ? relations[key]\n : Object.hasOwn(fields, key)\n ? fields[key]\n : undefined\n if (member === undefined) {\n return fail(entity, `sets \"${key}\", which is not a field or relation`)\n }\n if (member._tag === 'Relation') {\n if (member.cardinality !== 'one') return fail(entity, `sets \"${key}\", a many relation`)\n const target = member.target()\n if (context._tag !== 'Viewer' || context.entity.token !== target.identity.token) {\n return fail(entity, `sets the relation \"${key}\" to what is not Expr.viewer(${target.name})`)\n }\n return { value: context, on }\n }\n const stored = storedAs(member.schema as Schema.Top)\n Match.value(context).pipe(\n Match.tagsExhaustive({\n Now: () =>\n stored === 'number' ||\n fail(entity, `sets \"${key}\" to the time, but it is not stored as a number`),\n Viewer: () =>\n stored === 'text' ||\n fail(entity, `sets \"${key}\" to the viewer's id, but it is not stored as text`),\n ViewerPath: ({ field }) =>\n (stored !== 'other' && storedAs(field.schema as unknown as Schema.Top) === stored) ||\n fail(\n entity,\n `sets \"${key}\" to what ${field.owner.name}.${field.key} holds, which it is not stored as`,\n ),\n }),\n )\n return { value: context, on }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,QAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,WAAW,OAAO,KAAK,KAAK,SAAS;AACvD;;AAGA,MAAM,YAAY,WAAoD;CACpE,MAAM,SAAS,YAAY,QAAQ,OAAO,UAAU,MAAM,CAAC,CAAC,GAAG;CAC/D,IAAI,OAAO,MAAM,YAAY,MAAM,GAAG,OAAO;CAC7C,IAAI,OAAO,MAAM,UAAU,QAAQ,GAAG,OAAO;CAC7C,OAAO;AACT;AAEA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO,KAAA;;;;;;AAOhF,MAAa,cACX,QACA,KACA,OACA,OACc;CACd,IAAI,OAAO,YAAY,OAAO,SAC5B,OAAO,KAAK,QAAQ,SAAS,IAAI,OAAO,OAAO,EAAE,EAAE,kCAAkC;CAEvF,IAAI,QAAQ,MAAM,OAAO,KAAK,QAAQ,qCAAqC;CAC3E,IAAI,OAAO,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,KAAK,QAAQ,IAAI,IAAI,iBAAiB;CAClF,MAAM,MAAM,MAAM,KAAK;CACvB,IAAI,QAAQ,YAAY,QAAQ,SAAS,QAAQ,cAC/C,OAAO,KACL,QACA,SAAS,IAAI,sIACf;CAEF,MAAM,UAAU;CAChB,MAAM,YAAoD,OAAO;CACjE,MAAM,SAAiD,OAAO;CAC9D,MAAM,SAAS,OAAO,OAAO,WAAW,GAAG,IACvC,UAAU,OACV,OAAO,OAAO,QAAQ,GAAG,IACvB,OAAO,OACP,KAAA;CACN,IAAI,WAAW,KAAA,GACb,OAAO,KAAK,QAAQ,SAAS,IAAI,oCAAoC;CAEvE,IAAI,OAAO,SAAS,YAAY;EAC9B,IAAI,OAAO,gBAAgB,OAAO,OAAO,KAAK,QAAQ,SAAS,IAAI,mBAAmB;EACtF,MAAM,SAAS,OAAO,OAAO;EAC7B,IAAI,QAAQ,SAAS,YAAY,QAAQ,OAAO,UAAU,OAAO,SAAS,OACxE,OAAO,KAAK,QAAQ,sBAAsB,IAAI,+BAA+B,OAAO,KAAK,EAAE;EAE7F,OAAO;GAAE,OAAO;GAAS;EAAG;CAC9B;CACA,MAAM,SAAS,SAAS,OAAO,MAAoB;CACnD,MAAM,MAAM,OAAO,CAAC,CAAC,KACnB,MAAM,eAAe;EACnB,WACE,WAAW,YACX,KAAK,QAAQ,SAAS,IAAI,gDAAgD;EAC5E,cACE,WAAW,UACX,KAAK,QAAQ,SAAS,IAAI,mDAAmD;EAC/E,aAAa,EAAE,YACZ,WAAW,WAAW,SAAS,MAAM,MAA+B,MAAM,UAC3E,KACE,QACA,SAAS,IAAI,YAAY,MAAM,MAAM,KAAK,GAAG,MAAM,IAAI,kCACzD;CACJ,CAAC,CACH;CACA,OAAO;EAAE,OAAO;EAAS;CAAG;AAC9B"}
1
+ {"version":3,"file":"sets.js","names":[],"sources":["../src/sets.ts"],"sourcesContent":["/**\n * What `Entity.sets` declares: members whose value is the write's context,\n * never its input, and the writes that set them.\n */\nimport { Match, Schema, SchemaAST } from 'effect'\nimport type { NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { AnyEntity, EntityMember } from './index.js'\nimport { SchemaShape } from './shape.js'\n\n/** The writes that set a member: every insert (`create`), or every insert and update (`write`). */\nexport type SetOn = 'create' | 'write'\n\n/** A value the write's context gives: who asks, what their row holds, or when. */\nexport type ContextValue = ViewerExpr<unknown> | ViewerPathExpr<unknown> | NowExpr<unknown>\n\n/** One member `Entity.sets` names: its value, and the writes that set it. */\nexport interface EntitySet {\n readonly value: ContextValue\n readonly on: SetOn\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\n/** How a field's values are stored, nulls aside: as text, as a number, or otherwise. */\nconst storedAs = (schema: Schema.Top): 'text' | 'number' | 'other' => {\n const stored = SchemaShape.present(Schema.toEncoded(schema).ast)\n if (stored.every(SchemaShape.isText)) return 'text'\n if (stored.every(SchemaAST.isNumber)) return 'number'\n return 'other'\n}\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && '_tag' in value ? value._tag : undefined\n\n/**\n * `value` checked against the member `key` it sets, as `Entity.sets` was\n * given them: a relation takes `Expr.viewer` of its target, a field stored as\n * text the viewer's id, a field stored as a number the time.\n */\nexport const checkedSet = (\n entity: AnyEntity,\n key: string,\n value: unknown,\n on: unknown,\n): EntitySet => {\n if (on !== 'create' && on !== 'write') {\n return fail(entity, `sets \"${key}\" on ${String(on)}; say on: 'create' or on: 'write'`)\n }\n if (key === 'id') return fail(entity, 'sets the id, which the client names')\n if (Object.hasOwn(entity.sets, key)) return fail(entity, `\"${key}\" is set already`)\n const tag = tagOf(value)\n // tag-check: open, the value is whatever the application wrote\n if (tag !== 'Viewer' && tag !== 'Now' && tag !== 'ViewerPath') {\n return fail(\n entity,\n `sets \"${key}\" to what is no value of the write's context (Expr.viewer, a path from it, Expr.now); a value from the input is a computed assignment`,\n )\n }\n const context = value as ContextValue\n const relations: Readonly<Record<string, EntityMember>> = entity.relations\n const fields: Readonly<Record<string, EntityMember>> = entity.fields\n const member = Object.hasOwn(relations, key)\n ? relations[key]\n : Object.hasOwn(fields, key)\n ? fields[key]\n : undefined\n if (member === undefined) {\n return fail(entity, `sets \"${key}\", which is not a field or relation`)\n }\n if (member._tag === 'Relation') {\n if (member.cardinality !== 'one') return fail(entity, `sets \"${key}\", a many relation`)\n const target = member.target()\n if (context._tag !== 'Viewer' || context.entity.token !== target.identity.token) {\n return fail(entity, `sets the relation \"${key}\" to what is not Expr.viewer(${target.name})`)\n }\n return { value: context, on }\n }\n const stored = storedAs(member.schema as Schema.Top)\n Match.value(context).pipe(\n Match.tagsExhaustive({\n Now: () =>\n stored === 'number' ||\n fail(entity, `sets \"${key}\" to the time, but it is not stored as a number`),\n Viewer: () =>\n stored === 'text' ||\n fail(entity, `sets \"${key}\" to the viewer's id, but it is not stored as text`),\n ViewerPath: ({ field }) =>\n (stored !== 'other' && storedAs(field.schema as unknown as Schema.Top) === stored) ||\n fail(\n entity,\n `sets \"${key}\" to what ${field.owner.name}.${field.key} holds, which it is not stored as`,\n ),\n }),\n )\n return { value: context, on }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,QAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,WAAW,OAAO,KAAK,KAAK,SAAS;AACvD;;AAGA,MAAM,YAAY,WAAoD;CACpE,MAAM,SAAS,YAAY,QAAQ,OAAO,UAAU,MAAM,CAAC,CAAC,GAAG;CAC/D,IAAI,OAAO,MAAM,YAAY,MAAM,GAAG,OAAO;CAC7C,IAAI,OAAO,MAAM,UAAU,QAAQ,GAAG,OAAO;CAC7C,OAAO;AACT;AAEA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO,KAAA;;;;;;AAOhF,MAAa,cACX,QACA,KACA,OACA,OACc;CACd,IAAI,OAAO,YAAY,OAAO,SAC5B,OAAO,KAAK,QAAQ,SAAS,IAAI,OAAO,OAAO,EAAE,EAAE,kCAAkC;CAEvF,IAAI,QAAQ,MAAM,OAAO,KAAK,QAAQ,qCAAqC;CAC3E,IAAI,OAAO,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,KAAK,QAAQ,IAAI,IAAI,iBAAiB;CAClF,MAAM,MAAM,MAAM,KAAK;CAEvB,IAAI,QAAQ,YAAY,QAAQ,SAAS,QAAQ,cAC/C,OAAO,KACL,QACA,SAAS,IAAI,sIACf;CAEF,MAAM,UAAU;CAChB,MAAM,YAAoD,OAAO;CACjE,MAAM,SAAiD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