foldkit-entity 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
- import { Array as Array$1, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
1
+ import { Array as Array$1, Data, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
2
2
  import { Metadata } from "foldkit-metadata";
3
- //#region src/collation.ts
3
+ import { absurd } from "effect/Function";
4
+ // src/collation.ts
4
5
  /**
5
6
  * How text compares when a query orders by it, declared rather than left to
6
7
  * the backend. Left unsaid, SQLite compares bytes, Postgres follows the
@@ -32,10 +33,161 @@ const Collation = {
32
33
  /** Member metadata: how a text field orders, wherever a query orders by it. */
33
34
  of: (collation) => key$1.of(collation),
34
35
  /** The collation a member's metadata declares, if any. */
35
- declared: (metadata) => Option.fromUndefinedOr(key$1.get(metadata)[0])
36
+ declared: (metadata) => Option.fromUndefinedOr(key$1.get(metadata)[0]),
37
+ /**
38
+ * Text as `asciiFold` compares it: ASCII letters lowercased, every other
39
+ * character as it is, which is what SQLite's `lower` does without ICU and so
40
+ * what compiled SQL folds to. `toLowerCase` would fold `É` to `é` here and not
41
+ * there. An operator implementing `asciiFold` folds with this.
42
+ */
43
+ foldAscii: (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase())
44
+ };
45
+ // src/shape.ts
46
+ const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
47
+ const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
48
+ /** Whether any of these checks is `Schema.isInt`, alone or inside a group (`isInt32`). */
49
+ const checksInteger = (checks) => checks.some((check) => Match.value(check).pipe(Match.tagsExhaustive({
50
+ Filter: (filter) => filter.annotations?.representation?.id === "effect/schema/isInt",
51
+ FilterGroup: (group) => checksInteger(group.checks)
52
+ })));
53
+ /** What a schema's AST holds, read through Effect's own guards. */
54
+ const SchemaShape = {
55
+ /** True for the `null` and `undefined` members that make a schema optional. */
56
+ isNullish,
57
+ /**
58
+ * The members of a schema with `null` and `undefined` set aside, so optional
59
+ * text is still text; a schema that is not a union is its one member.
60
+ */
61
+ present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
62
+ /** True when every value the schema admits is a string. */
63
+ isText,
64
+ /**
65
+ * True when the AST is checked to hold integers (`Schema.isInt`, alone or in
66
+ * a group such as `isInt32`). Read it from a schema's encoded side to ask
67
+ * what the store holds.
68
+ */
69
+ holdsIntegers: (ast) => checksInteger(ast.checks ?? [])
70
+ };
71
+ // src/jsonSchema.ts
72
+ /**
73
+ * A schema's JSON Schema, of what it encodes to as JSON carries it, its
74
+ * definitions kept under `$defs` so a `$ref` in it resolves. Not exported from
75
+ * the package.
76
+ */
77
+ const jsonSchemaOf = (schema) => {
78
+ const document = Schema.toJsonSchemaDocument(schema);
79
+ return Object.keys(document.definitions).length === 0 ? document.schema : {
80
+ ...document.schema,
81
+ $defs: document.definitions
82
+ };
83
+ };
84
+ // src/law.ts
85
+ /**
86
+ * Laws an operator declares (expr-operations-DESIGN §10): equations every
87
+ * implementation of it keeps over a domain. A law describes; nothing rewrites a
88
+ * body by one. `Conformance.laws` tests an implementation against them, and
89
+ * what it finds is evidence recorded in that implementation's table.
90
+ */
91
+ const Laws = Data.taggedEnum();
92
+ const unnarrowed = { domain: Option.none() };
93
+ /**
94
+ * A law as JSON says it: what `Operators.describe` lists and evidence names.
95
+ * Its witnesses are values as stored and operators by name; its domain is a
96
+ * JSON Schema, or `null` for the operator's whole input.
97
+ */
98
+ const LawDescription = Schema.Struct({
99
+ kind: Schema.String,
100
+ witnesses: Schema.Record(Schema.String, Schema.Unknown),
101
+ domain: Schema.Unknown
102
+ });
103
+ /** An operator by its id, and its version when that is not the first. */
104
+ const nameOf$1 = (operator) => operator.descriptor.version === 1 ? operator.descriptor.id : `${operator.descriptor.id}@${operator.descriptor.version}`;
105
+ const Law = {
106
+ associative: Laws.Associative(unnarrowed),
107
+ commutative: Laws.Commutative(unnarrowed),
108
+ idempotent: Laws.Idempotent(unnarrowed),
109
+ preservesCollation: Laws.PreservesCollation(unnarrowed),
110
+ /** `value` leaves the other argument as it is, from `side` (both by default). */
111
+ identity: (value, side = "both") => Laws.Identity({
112
+ ...unnarrowed,
113
+ value,
114
+ side
115
+ }),
116
+ /** `value` is the answer whatever the other argument, from `side` (both by default). */
117
+ absorbing: (value, side = "both") => Laws.Absorbing({
118
+ ...unnarrowed,
119
+ value,
120
+ side
121
+ }),
122
+ /** `other` undoes the operator: `op(a, other(a))` is `identity`. */
123
+ inverse: (other, identity) => Laws.Inverse({
124
+ ...unnarrowed,
125
+ other,
126
+ identity
127
+ }),
128
+ /** The operator distributes over `over`, from the left. */
129
+ distributes: (over) => Laws.Distributes({
130
+ ...unnarrowed,
131
+ over
132
+ }),
133
+ /** Moving the argument at `position` up moves the result up (or down, decreasing). */
134
+ monotonic: (direction, position) => Laws.Monotonic({
135
+ ...unnarrowed,
136
+ direction,
137
+ position
138
+ }),
139
+ /**
140
+ * The law over the values `domain` accepts only: a law that holds of the
141
+ * integers and not of every number, say, narrowed so it is tested where it
142
+ * is claimed.
143
+ */
144
+ within: (law, domain) => Object.freeze({
145
+ ...law,
146
+ domain: Option.some(domain)
147
+ }),
148
+ $match: Laws.$match,
149
+ /**
150
+ * The operators a law, as JSON, calls besides its own (`inverse`'s and
151
+ * `distributes`' witnesses), by name: evidence of it is of their
152
+ * implementations too, and goes when one of them is replaced.
153
+ */
154
+ witnessesNamed: (law) => [law.witnesses["other"], law.witnesses["over"]].filter((name) => typeof name === "string"),
155
+ /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */
156
+ describe: (law) => {
157
+ const witnesses = Laws.$match(law, {
158
+ Associative: () => ({}),
159
+ Commutative: () => ({}),
160
+ Idempotent: () => ({}),
161
+ PreservesCollation: () => ({}),
162
+ Identity: ({ value, side }) => ({
163
+ value,
164
+ side
165
+ }),
166
+ Absorbing: ({ value, side }) => ({
167
+ value,
168
+ side
169
+ }),
170
+ Inverse: ({ other, identity }) => ({
171
+ other: nameOf$1(other),
172
+ identity
173
+ }),
174
+ Distributes: ({ over }) => ({ over: nameOf$1(over) }),
175
+ Monotonic: ({ direction, position }) => ({
176
+ direction,
177
+ position
178
+ })
179
+ });
180
+ return {
181
+ kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),
182
+ witnesses,
183
+ domain: Option.match(law.domain, {
184
+ onNone: () => null,
185
+ onSome: jsonSchemaOf
186
+ })
187
+ };
188
+ }
36
189
  };
37
- //#endregion
38
- //#region src/expr.ts
190
+ // src/expr.ts
39
191
  /**
40
192
  * `Expr` — a query's scalar computations as typed values.
41
193
  *
@@ -49,6 +201,23 @@ const Collation = {
49
201
  * operation here is one a real query in this repository needs; the set grows
50
202
  * from queries, not from what a database could express.
51
203
  */
204
+ /** A table implementing nothing: every primitive operator is unsupported by it. */
205
+ const noOperators = Object.freeze({
206
+ has: () => false,
207
+ versions: () => []
208
+ });
209
+ /**
210
+ * An operator `operators` does not implement, by name, with the versions of it
211
+ * the table does implement: `acme.slug@2 (this table has acme.slug)`.
212
+ */
213
+ const missingName = (operator, operators) => {
214
+ const held = operators.versions(operator.id);
215
+ if (held.includes(operator.version)) return `${operatorName$1(operator)} (this table has another declaration of it; declare an operator once and import it)`;
216
+ return held.length === 0 ? operatorName$1(operator) : `${operatorName$1(operator)} (this table has ${held.map((version) => operatorName$1({
217
+ ...operator,
218
+ version
219
+ })).join(", ")})`;
220
+ };
52
221
  const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
53
222
  /**
54
223
  * An Entity's field and a `FieldExpr` are the same three members under the same
@@ -82,7 +251,8 @@ const predicateTags = /* @__PURE__ */ new Set([
82
251
  "And",
83
252
  "Or",
84
253
  "Not",
85
- "Compare"
254
+ "Compare",
255
+ "Test"
86
256
  ]);
87
257
  /** Whether a value is a predicate, and so usable where a boolean is wanted. */
88
258
  const isPredicate = (value) => predicateTags.has(tagOf(value));
@@ -92,8 +262,9 @@ const isPredicate = (value) => predicateTags.has(tagOf(value));
92
262
  */
93
263
  const toOperand = (value) => {
94
264
  const tag = tagOf(value);
265
+ if (tag === "Field" && !Object.hasOwn(value, "metadata")) return value;
95
266
  if (tag === "Field") return fieldExpr(value);
96
- if (tag === "Literal" || tag === "Input" || tag === "Next" || predicateTags.has(tag)) return value;
267
+ if (tag === "Literal" || tag === "Input" || tag === "Next" || tag === "Call" || predicateTags.has(tag)) return value;
97
268
  return literal(value);
98
269
  };
99
270
  /** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
@@ -130,7 +301,8 @@ const sideKind = (side) => Match.value(side).pipe(Match.tagsExhaustive({
130
301
  Field: (field) => orderKindOf(Schema.toEncoded(field.schema).ast),
131
302
  Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),
132
303
  Input: (input) => orderKindOf(Schema.toEncoded(input.schema).ast),
133
- Literal: ({ value }) => literalKind(value)
304
+ Literal: ({ value }) => literalKind(value),
305
+ Call: ({ operator }) => orderKindOf(Schema.toEncoded(operator.output).ast)
134
306
  }));
135
307
  /**
136
308
  * How a comparison's text compares: the collation given, else the field's
@@ -144,14 +316,23 @@ const collationFor = (step, left, right, given) => {
144
316
  const kinds = new Set([sideKind(left), sideKind(right)].filter((kind) => kind !== "null"));
145
317
  if (kinds.has("none") || kinds.size > 1) throw new Error(`[foldkit-entity] Expr.${step}: only numbers with numbers, or text with text, order alike in every interpreter, as stored`);
146
318
  if (!kinds.has("text")) return Option.none();
147
- const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [field]), Match.tag("Next", (next) => [next.field]), Match.orElse(() => [])));
319
+ const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [{
320
+ name: `${field.owner.name}.${field.key}`,
321
+ collation: field.collation
322
+ }]), Match.tag("Next", ({ field }) => [{
323
+ name: `${field.owner.name}.${field.key}`,
324
+ collation: field.collation
325
+ }]), Match.tag("Call", (call) => [{
326
+ name: showExpr(call),
327
+ collation: call.collation
328
+ }]), Match.orElse(() => [])));
148
329
  const [first] = fields;
149
- if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field, whose collation would say how it orders`);
150
- const named = fields.map((field) => `${field.owner.name}.${field.key}`).join(" and ");
330
+ if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field, nor a call carrying a collation, to say how it orders`);
331
+ const named = fields.map((field) => field.name).join(" and ");
151
332
  const collations = Option.match(given, {
152
333
  onSome: (collation) => [collation],
153
334
  onNone: () => fields.map((field) => Option.getOrElse(field.collation, () => {
154
- throw new Error(`[foldkit-entity] Expr.${step}: ${field.owner.name}.${field.key} is text with no declared collation, so backends would order it differently; declare Collation.binary or Collation.asciiFold on it, or pass one`);
335
+ throw new Error(`[foldkit-entity] Expr.${step}: ${field.name} is text with no declared collation, so backends would order it differently; declare Collation.binary or Collation.asciiFold on it, or pass one`);
155
336
  }))
156
337
  });
157
338
  const [collation] = collations;
@@ -196,7 +377,337 @@ const connective = (step, kind) => (...given) => {
196
377
  operands
197
378
  });
198
379
  };
380
+ const collationTags = /* @__PURE__ */ new Set([
381
+ "Binary",
382
+ "AsciiFold",
383
+ "Locale"
384
+ ]);
385
+ /** A call's last value, when it is one past the arguments: its options, checked. */
386
+ const callOptionsOf = (id, value) => {
387
+ const collation = typeof value === "object" && value !== null && Object.hasOwn(value, "collation") ? value.collation : void 0;
388
+ if (!collationTags.has(tagOf(collation))) throw new Error(`[foldkit-entity] ${id}: a value past its arguments is \`{ collation }\`, a Collation`);
389
+ return collation;
390
+ };
391
+ /** A collation a call was given: one its operator compares by, and portable where required. */
392
+ const givenCollation = (id, descriptor, collation) => {
393
+ if (Option.isSome(descriptor.definedAs) || descriptor.collation === "none") throw new Error(`[foldkit-entity] ${id}: takes no collation; it compares no text of its own`);
394
+ if (collation._tag === "Locale") throw new Error(`[foldkit-entity] ${id}: compares by the backend's "${collation.locale}" collation, which only that backend has`);
395
+ return Option.some(collation);
396
+ };
397
+ /** Namespaced, lower camel case: `cms.published`, `text.startsWith`. */
398
+ const operatorId = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
399
+ /**
400
+ * Why `law` cannot be declared of an operator of this shape, if it cannot: an
401
+ * equation over two arguments of a unary operator, a witness that does not
402
+ * decode as the argument it stands in, or a collation law of an operator
403
+ * whose text keeps none.
404
+ */
405
+ const lawProblem = (law, input, output, collation) => {
406
+ const name = Law.describe(law).kind;
407
+ const binary = () => input.length === 2 ? Option.none() : Option.some(`${name} is a law of an operator of two arguments, and this one takes ${input.length}`);
408
+ const decodes = (value, schema, what) => Schema.is(Schema.toEncoded(schema))(value) ? Option.none() : Option.some(`${name}'s ${what} ${JSON.stringify(value)} does not decode as its schema`);
409
+ const sides = (value, side) => Option.orElse(binary(), () => Option.orElse(side === "right" ? Option.none() : decodes(value, input[0], "left witness"), () => side === "left" ? Option.none() : decodes(value, input[1], "right witness")));
410
+ return Law.$match(law, {
411
+ Associative: binary,
412
+ Commutative: binary,
413
+ Idempotent: binary,
414
+ Identity: ({ value, side }) => sides(value, side),
415
+ Absorbing: ({ value, side }) => sides(value, side),
416
+ Inverse: ({ other, identity }) => Option.orElse(binary(), () => other.descriptor.input.length === 1 ? decodes(identity, output, "identity") : Option.some(`${name}'s other operator takes one argument`)),
417
+ Distributes: ({ over }) => Option.orElse(binary(), () => over.descriptor.input.length === 2 ? Option.none() : Option.some(`${name} is over an operator of two arguments`)),
418
+ Monotonic: ({ position }) => Number.isSafeInteger(position) && position >= 0 && position < input.length ? Option.none() : Option.some(`${name}'s position ${position} is not an argument's`),
419
+ PreservesCollation: () => collation === "operands" ? Option.none() : Option.some(`${name} is a law of an operator declared \`collation: 'operands'\``)
420
+ });
421
+ };
422
+ /** Whether a schema's stored form is a boolean, which makes its operator a predicate. */
423
+ const storedAsBoolean = (schema) => SchemaAST.isBoolean(Schema.toEncoded(schema).ast);
424
+ /** What a schema stores, null aside: one kind an argument is checked by, or `other`. */
425
+ const storedKindOf = (schema) => {
426
+ const present = SchemaShape.present(Schema.toEncoded(schema).ast);
427
+ if (present.length === 0) return "other";
428
+ if (present.every(SchemaAST.isNumber)) return "number";
429
+ if (present.every(SchemaShape.isText)) return "text";
430
+ if (present.every(SchemaAST.isBoolean)) return "boolean";
431
+ return "other";
432
+ };
433
+ /** The schema a scalar's values are stored by. */
434
+ const scalarSchema = (scalar) => Match.value(scalar).pipe(Match.tagsExhaustive({
435
+ Field: (field) => field.schema,
436
+ Next: ({ field }) => field.schema,
437
+ Input: (input) => input.schema,
438
+ Literal: () => Schema.Unknown,
439
+ Call: ({ operator }) => operator.output
440
+ }));
441
+ /** Every field, field after a write, and input an expression reads, as keys to compare. */
442
+ const readKeys = (...nodes) => {
443
+ const read = dependenciesOf(...nodes);
444
+ const named = (prefix, fields) => fields.map((field) => `${prefix}${field.entity}.${field.key}`);
445
+ return /* @__PURE__ */ new Set([
446
+ ...named("", read.fields),
447
+ ...named("next ", read.next),
448
+ ...read.inputs.map((key) => `$${key}`)
449
+ ]);
450
+ };
451
+ /** One argument, checked against the schema it is passed for, as a node. */
452
+ const argumentFor = (id, position, schema, value) => {
453
+ const arg = toOperand(value);
454
+ const fail = (what) => {
455
+ throw new Error(`[foldkit-entity] ${id}: argument ${position + 1} ${what}`);
456
+ };
457
+ if (isPredicate(arg)) {
458
+ if (!storedAsBoolean(schema)) fail("is a predicate, but the operator does not take a boolean");
459
+ return arg;
460
+ }
461
+ if (arg._tag === "Literal") {
462
+ if (!Schema.is(Schema.toEncoded(schema))(arg.value)) fail(`is ${JSON.stringify(arg.value)}, which the operator's input schema does not admit`);
463
+ return arg;
464
+ }
465
+ const wanted = storedKindOf(schema);
466
+ const given = storedKindOf(scalarSchema(arg));
467
+ if (wanted !== "other" && given !== "other" && given !== wanted) fail(`is stored as ${given}, but the operator takes ${wanted}`);
468
+ return arg;
469
+ };
470
+ /** A scalar's collation: a field's declared one, or a call's. */
471
+ const collationOf = (scalar) => Match.value(scalar).pipe(Match.tagsExhaustive({
472
+ Field: (field) => field.collation,
473
+ Next: ({ field }) => field.collation,
474
+ Call: (call) => call.collation,
475
+ Literal: () => Option.none(),
476
+ Input: () => Option.none()
477
+ }));
478
+ /**
479
+ * The collation a primitive call compares text under: the one its collated
480
+ * text arguments share. A literal or an input carries none and does not vote.
481
+ * `required` refuses a call with none, or with a backend's locale.
482
+ */
483
+ const callCollation = (id, rule, args) => {
484
+ if (rule === "none") return Option.none();
485
+ const fail = (what) => {
486
+ throw new Error(`[foldkit-entity] ${id}: ${what}`);
487
+ };
488
+ const voters = args.flatMap((arg) => isPredicate(arg) || arg._tag === "Literal" || arg._tag === "Input" || sideKind(arg) !== "text" ? [] : [{
489
+ arg,
490
+ collation: collationOf(arg)
491
+ }]);
492
+ const collations = voters.flatMap(({ arg, collation }) => Option.match(collation, {
493
+ onSome: (each) => [each],
494
+ onNone: () => rule === "required" ? fail(`${showExpr(arg)} is text with no declared collation, so backends would compare it differently; declare Collation.binary or Collation.asciiFold on it`) : []
495
+ }));
496
+ const [shared] = collations;
497
+ if (shared === void 0) return rule === "required" ? fail("compares text with no field or call holding a collation") : Option.none();
498
+ if (collations.some((each) => each._tag !== shared._tag)) fail(`${voters.map((voter) => showExpr(voter.arg)).join(" and ")} declare different collations`);
499
+ if (shared._tag === "Locale") fail(`compares by the backend's "${shared.locale}" collation, which a call cannot carry`);
500
+ return Option.some(shared);
501
+ };
502
+ /** Builds an operator: checks what it is given once, then each call. */
503
+ const makeOperator = (id, options) => {
504
+ const fail = (what) => {
505
+ throw new Error(`[foldkit-entity] Expr.operator("${id}"): ${what}`);
506
+ };
507
+ if (!operatorId.test(id)) fail("an id is namespaced lower camel case, as `cms.published`");
508
+ if (id.startsWith("foldkit.")) fail("ids under `foldkit.` are reserved");
509
+ const version = options.version ?? 1;
510
+ if (!Number.isSafeInteger(version) || version < 1) fail("a version is a positive integer");
511
+ if (!Array.isArray(options.input) || !options.input.every(Schema.isSchema)) fail("`input` is one schema per argument");
512
+ if (!Schema.isSchema(options.output)) fail("`output` is a schema");
513
+ const definedAs = Option.fromUndefinedOr(options.definedAs);
514
+ if (Option.isSome(definedAs) && typeof definedAs.value !== "function") fail("`definedAs` builds what a call means");
515
+ if (Option.isSome(definedAs) && (options.nulls !== void 0 || options.collation !== void 0)) fail("a defined operator means its body, so `nulls` and `collation` are its body's");
516
+ const nulls = options.nulls ?? "strict";
517
+ const collation = options.collation ?? "none";
518
+ if (nulls !== "strict" && nulls !== "handled") fail("`nulls` is 'strict' or 'handled'");
519
+ if (collation !== "none" && collation !== "operands" && collation !== "required") fail("`collation` is 'none', 'operands' or 'required'");
520
+ const input = Object.freeze([...options.input]);
521
+ const predicate = storedAsBoolean(options.output);
522
+ if (collation === "operands" && orderKindOf(Schema.toEncoded(options.output).ast) !== "text") fail("`collation: 'operands'` describes a text result, and this one is not text");
523
+ const laws = Object.freeze([...options.laws ?? []]);
524
+ for (const law of laws) Option.match(lawProblem(law, input, options.output, collation), {
525
+ onNone: () => void 0,
526
+ onSome: fail
527
+ });
528
+ const descriptor = Object.freeze({
529
+ _tag: "Operator",
530
+ id,
531
+ version,
532
+ description: Option.fromUndefinedOr(options.description),
533
+ input,
534
+ output: options.output,
535
+ definedAs,
536
+ nulls,
537
+ collation,
538
+ laws
539
+ });
540
+ /** A defined call's expansion, checked: of its output's kind, reading only its arguments. */
541
+ const expand = (body, args) => {
542
+ const expansion = toOperand(body(...args));
543
+ if (predicate !== isPredicate(expansion)) throw new Error(`[foldkit-entity] ${id}: its output is ${predicate ? "a boolean, so `definedAs` returns a predicate" : "not a boolean, so `definedAs` returns a scalar"}`);
544
+ const allowed = readKeys(...args);
545
+ const hidden = [...readKeys(expansion)].filter((key) => !allowed.has(key));
546
+ if (hidden.length > 0) throw new Error(`[foldkit-entity] ${id}: \`definedAs\` reads ${hidden.join(", ")}, which no argument holds; pass it as one`);
547
+ return expansion;
548
+ };
549
+ const call = (...written) => {
550
+ const explicit = written.length === input.length + 1 ? Option.some(callOptionsOf(id, written[written.length - 1])) : Option.none();
551
+ const given = Option.isSome(explicit) ? written.slice(0, -1) : written;
552
+ if (given.length !== input.length) throw new Error(`[foldkit-entity] ${id}: takes ${input.length} argument${input.length === 1 ? "" : "s"}, given ${given.length}`);
553
+ const args = Object.freeze(given.map((value, position) => argumentFor(id, position, input[position], value)));
554
+ const expansion = Option.map(descriptor.definedAs, (body) => expand(body, args));
555
+ const carried = Option.match(explicit, {
556
+ onSome: (each) => givenCollation(id, descriptor, each),
557
+ onNone: () => Option.match(expansion, {
558
+ onSome: (body) => isPredicate(body) ? Option.none() : collationOf(body),
559
+ onNone: () => callCollation(id, collation, args)
560
+ })
561
+ });
562
+ return predicate ? node({
563
+ _tag: "Test",
564
+ operator: descriptor,
565
+ args,
566
+ expansion,
567
+ collation: carried
568
+ }) : node({
569
+ _tag: "Call",
570
+ operator: descriptor,
571
+ args,
572
+ expansion,
573
+ collation: carried
574
+ });
575
+ };
576
+ return Object.freeze(Object.assign(call, { descriptor }));
577
+ };
578
+ /** Each defined call replaced by its expansion, deeply; built once per node. */
579
+ const expandedCache = /* @__PURE__ */ new WeakMap();
580
+ const expandedScalar = (scalar) => {
581
+ const known = expandedCache.get(scalar);
582
+ if (known !== void 0) return known;
583
+ const result = scalar._tag === "Call" ? Option.match(scalar.expansion, {
584
+ onSome: expandedScalar,
585
+ onNone: () => node({
586
+ ...scalar,
587
+ args: scalar.args.map(expandedSide)
588
+ })
589
+ }) : scalar;
590
+ expandedCache.set(scalar, result);
591
+ return result;
592
+ };
593
+ const expandedSide = (side) => isPredicate(side) ? expandedPredicate(side) : expandedScalar(side);
594
+ const expandedPredicate = (predicate) => {
595
+ const known = expandedCache.get(predicate);
596
+ if (known !== void 0) return known;
597
+ const result = Match.value(predicate).pipe(Match.tagsExhaustive({
598
+ Eq: (eq) => node({
599
+ ...eq,
600
+ left: expandedSide(eq.left),
601
+ right: expandedSide(eq.right)
602
+ }),
603
+ Null: (nul) => node({
604
+ ...nul,
605
+ operand: expandedScalar(nul.operand)
606
+ }),
607
+ Contains: (contains) => node({
608
+ ...contains,
609
+ value: expandedScalar(contains.value),
610
+ search: expandedSide(contains.search)
611
+ }),
612
+ In: (inPredicate) => node({
613
+ ...inPredicate,
614
+ value: expandedScalar(inPredicate.value),
615
+ among: expandedScalar(inPredicate.among)
616
+ }),
617
+ And: (and) => node({
618
+ ...and,
619
+ operands: Array$1.map(and.operands, expandedPredicate)
620
+ }),
621
+ Or: (or) => node({
622
+ ...or,
623
+ operands: Array$1.map(or.operands, expandedPredicate)
624
+ }),
625
+ Not: (not) => node({
626
+ ...not,
627
+ operand: expandedPredicate(not.operand)
628
+ }),
629
+ Compare: (compare) => node({
630
+ ...compare,
631
+ left: expandedScalar(compare.left),
632
+ right: expandedScalar(compare.right)
633
+ }),
634
+ Test: (test) => Option.match(test.expansion, {
635
+ onSome: expandedPredicate,
636
+ onNone: () => node({
637
+ ...test,
638
+ args: test.args.map(expandedSide)
639
+ })
640
+ })
641
+ }));
642
+ expandedCache.set(predicate, result);
643
+ return result;
644
+ };
199
645
  const Expr = {
646
+ /**
647
+ * An operator, defined by what a call of it means: `definedAs` builds that
648
+ * expression from the call's arguments, once per call, and every interpreter
649
+ * runs it, so the operator needs no implementation anywhere. What it adds is
650
+ * a name: a query, a guard and an invariant that mean the same thing say so,
651
+ * and print it.
652
+ *
653
+ * ```ts
654
+ * const published = Expr.operator('cms.published', {
655
+ * input: [Schema.Unknown],
656
+ * output: Schema.Boolean,
657
+ * definedAs: publishedAt => Expr.isNotNull(publishedAt),
658
+ * })
659
+ * Query.where(published(Post.fields.publishedAt))
660
+ * ```
661
+ *
662
+ * Arguments are checked by their stored form: a field, scalar or plain value
663
+ * of the input's stored type, or a predicate where it takes a boolean. A
664
+ * boolean output makes a call a predicate. `definedAs` may read only what its
665
+ * arguments hold: a field or input it closes over instead is refused when
666
+ * called, since nothing asking what the call reads would see it. The id is
667
+ * namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)
668
+ * changes when what it means does.
669
+ *
670
+ * **Without `definedAs` it is primitive**: each interpreter implements it
671
+ * (`Operators.implement` in memory), and one without an implementation
672
+ * refuses the body by the operator's id. `nulls` (default `strict`: a null
673
+ * argument gives null, the implementation never sees one) and `collation`
674
+ * (`operands`: a text result carries its text arguments' shared collation;
675
+ * `required`: it compares text itself and needs one) are a primitive
676
+ * operator's; a defined one means its body for both.
677
+ */
678
+ operator: (id, options) => makeOperator(id, options),
679
+ /**
680
+ * The predicate or scalar (an order term's, say) with every call of a
681
+ * defined operator replaced by what it means, deeply. An interpreter that
682
+ * compiles a body expands it first, and compiles exactly what was written
683
+ * out. A call with no definition stays, for the interpreter to run or refuse
684
+ * by name.
685
+ */
686
+ /**
687
+ * Whether a constant written in these expressions is text holding a NUL, or
688
+ * a list holding one: SQL refuses such a parameter wherever it compiles, so
689
+ * an interpreter refuses the run, not one row.
690
+ */
691
+ givesNul: (...nodes) => {
692
+ const seen = /* @__PURE__ */ new Set();
693
+ const nul = (value) => typeof value === "string" && value.includes(String.fromCharCode(0));
694
+ const walk = (node) => {
695
+ if (seen.has(node)) return false;
696
+ seen.add(node);
697
+ if (node._tag === "Literal") return Array.isArray(node.value) ? node.value.some(nul) : nul(node.value);
698
+ return childrenOf(node).some(walk);
699
+ };
700
+ return nodes.some(walk);
701
+ },
702
+ expanded: (node) => isPredicate(node) ? expandedPredicate(node) : expandedScalar(node),
703
+ /**
704
+ * What these expressions need that an interpreter lacks, as `Query.unsupported`
705
+ * says it for a query: each kernel operation `supported` does not list, then
706
+ * each primitive operator `operators` does not implement, by name (`id`, or
707
+ * `id@version` past the first). For anything holding expressions that is not a
708
+ * query: a guard's rule, an invariant, a write's `when`.
709
+ */
710
+ unsupported: (nodes, interpreter) => unsupportedIn(nodes, interpreter.operations, interpreter.operators),
200
711
  /** A constant. Comparisons coerce a plain value, so this is rarely written. */
201
712
  literal,
202
713
  /**
@@ -265,11 +776,15 @@ const Expr = {
265
776
  * nullable column that should match everything on an empty search says so:
266
777
  * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.
267
778
  */
268
- contains: (value, search) => node({
269
- _tag: "Contains",
270
- value: toExpr(value, "contains"),
271
- search: toOperand(search)
272
- }),
779
+ contains: (value, search) => {
780
+ const operand = toOperand(search);
781
+ if (operand._tag !== "Literal" && operand._tag !== "Input") throw new Error(`[foldkit-entity] Expr.contains: the search is ${showExpr(operand)}; search for a value or an input`);
782
+ return node({
783
+ _tag: "Contains",
784
+ value: toExpr(value, "contains"),
785
+ search: operand
786
+ });
787
+ },
273
788
  /**
274
789
  * Whether a value is one of `among`: a list written out, or an input whose
275
790
  * value is one. Each element is compared as `eq` compares.
@@ -365,7 +880,16 @@ const Expr = {
365
880
  */
366
881
  substituteNext: (predicate, values) => substituted(predicate, (operand) => Match.value(operand).pipe(Match.tag("Next", ({ field }) => Object.hasOwn(values, field.key) ? literal(values[field.key]) : operand), Match.orElse(() => operand)))
367
882
  };
368
- const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) : rewrite(side);
883
+ const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) : substitutedScalar(side, rewrite);
884
+ /**
885
+ * A scalar rewritten: a call's arguments and expansion each, so a field read
886
+ * under it is rewritten as one read directly is; anything else by `rewrite`.
887
+ */
888
+ const substitutedScalar = (scalar, rewrite) => scalar._tag === "Call" ? node({
889
+ ...scalar,
890
+ args: Object.freeze(scalar.args.map((arg) => substitutedSide(arg, rewrite))),
891
+ expansion: Option.map(scalar.expansion, (expansion) => substitutedScalar(expansion, rewrite))
892
+ }) : rewrite(scalar);
369
893
  const substituted = (predicate, rewrite) => {
370
894
  switch (predicate._tag) {
371
895
  case "Eq": return node({
@@ -375,17 +899,17 @@ const substituted = (predicate, rewrite) => {
375
899
  });
376
900
  case "Null": return node({
377
901
  ...predicate,
378
- operand: rewrite(predicate.operand)
902
+ operand: substitutedScalar(predicate.operand, rewrite)
379
903
  });
380
904
  case "Contains": return node({
381
905
  ...predicate,
382
- value: rewrite(predicate.value),
906
+ value: substitutedScalar(predicate.value, rewrite),
383
907
  search: substitutedSide(predicate.search, rewrite)
384
908
  });
385
909
  case "In": return node({
386
910
  ...predicate,
387
- value: rewrite(predicate.value),
388
- among: rewrite(predicate.among)
911
+ value: substitutedScalar(predicate.value, rewrite),
912
+ among: substitutedScalar(predicate.among, rewrite)
389
913
  });
390
914
  case "And":
391
915
  case "Or": return node({
@@ -398,19 +922,50 @@ const substituted = (predicate, rewrite) => {
398
922
  });
399
923
  case "Compare": return node({
400
924
  ...predicate,
401
- left: rewrite(predicate.left),
402
- right: rewrite(predicate.right)
925
+ left: substitutedScalar(predicate.left, rewrite),
926
+ right: substitutedScalar(predicate.right, rewrite)
927
+ });
928
+ case "Test": return node({
929
+ ...predicate,
930
+ args: Object.freeze(predicate.args.map((arg) => substitutedSide(arg, rewrite))),
931
+ expansion: Option.map(predicate.expansion, (expansion) => substituted(expansion, rewrite))
403
932
  });
404
933
  }
405
934
  };
406
935
  /** A term, its nulls placed by `options` or by the direction's default. */
407
- const term = (direction, expr, options = {}) => node({
408
- _tag: "Term",
409
- direction,
410
- expr,
411
- nulls: options.nulls ?? (direction === "asc" ? "last" : "first"),
412
- collation: Option.orElse(Option.fromUndefinedOr(options.collation), () => Match.value(expr).pipe(Match.tag("Field", (field) => field.collation), Match.orElse(() => Option.none())))
413
- });
936
+ const term = (direction, expr, options = {}) => {
937
+ const number = sideKind(expr) === "number";
938
+ if (number && options.collation !== void 0) throw new Error(`[foldkit-entity] Order: ${showExpr(expr)} is a number, which needs no collation; a collation orders text`);
939
+ const collation = number ? Option.none() : Option.orElse(Option.fromUndefinedOr(options.collation), () => Match.value(expr).pipe(Match.tag("Field", (field) => field.collation), Match.tag("Call", (call) => call.collation), Match.orElse(() => Option.none())));
940
+ if (expr._tag === "Call") orderableCall(expr, collation);
941
+ return node({
942
+ _tag: "Term",
943
+ direction,
944
+ expr,
945
+ nulls: options.nulls ?? (direction === "asc" ? "last" : "first"),
946
+ collation
947
+ });
948
+ };
949
+ /**
950
+ * Refuses a call no interpreter could order alike (expr-operations-DESIGN §8):
951
+ * its result must be a number, or text under a collation every interpreter
952
+ * shares. A field's text may be left to the backend; a call's has no backend
953
+ * column to fall back on.
954
+ */
955
+ const orderableCall = (call, collation) => {
956
+ const fail = (why) => {
957
+ throw new Error(`[foldkit-entity] Order: ${showExpr(call)} ${why}`);
958
+ };
959
+ const kind = sideKind(call);
960
+ if (kind === "number") return;
961
+ if (kind !== "text") fail("is neither a number nor text, so it orders nowhere alike");
962
+ Option.match(collation, {
963
+ onNone: () => fail("is text with no collation, so backends would order it differently; give the term or its text Collation.binary or Collation.asciiFold"),
964
+ onSome: (each) => {
965
+ if (each._tag === "Locale") fail(`is ordered by the backend's "${each.locale}" collation, which a call cannot carry`);
966
+ }
967
+ });
968
+ };
414
969
  const Order = {
415
970
  /** Smallest first; rows without a value last, unless `nulls` says first. */
416
971
  asc: (expr, options) => term("asc", toExpr(expr, "asc"), options),
@@ -418,8 +973,8 @@ const Order = {
418
973
  desc: (expr, options) => term("desc", toExpr(expr, "desc"), options),
419
974
  /**
420
975
  * The order the input names, among `choices`: every name the sort can hold
421
- * maps to a field, so a name left out is a type error here, not a query that
422
- * silently orders by nothing. A `null` sort chooses none, and the terms after
976
+ * maps to a field or a call that orders, so a name left out is a type error
977
+ * here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after
423
978
  * it decide.
424
979
  *
425
980
  * ```ts
@@ -430,7 +985,8 @@ const Order = {
430
985
  const fields = Object.create(null);
431
986
  for (const [name, choice] of Object.entries(choices)) {
432
987
  const expr = toExpr(choice, "chosen");
433
- if (expr._tag !== "Field") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is not a field`);
988
+ if (expr._tag !== "Field" && expr._tag !== "Call") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is neither a field nor a call`);
989
+ if (expr._tag === "Call") orderableCall(expr, expr.collation);
434
990
  fields[name] = expr;
435
991
  }
436
992
  return node({
@@ -451,15 +1007,18 @@ const notPlaceable = (reason) => Object.freeze({
451
1007
  * every order term.
452
1008
  */
453
1009
  const ordersIntrinsically = (ast) => SchemaAST.isNumber(ast) || SchemaAST.isBoolean(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal !== "string" || SchemaAST.isUnion(ast) && ast.types.every((member) => SchemaAST.isNull(member) || ordersIntrinsically(member));
454
- /** Why a term cannot be placed by a client, if it cannot. */
455
- const unplaceable = (orderTerm) => Match.value(orderTerm.expr).pipe(Match.tag("Field", (field) => Option.match(orderTerm.collation, {
1010
+ /** Why a term cannot be placed by a client running `operators`, if it cannot. */
1011
+ const unplaceable = (orderTerm, operators) => Match.value(orderTerm.expr).pipe(Match.tag("Call", (call) => {
1012
+ const missing = missingFrom(dependenciesOf(call).operators, operators);
1013
+ return missing.length === 0 ? Option.none() : Option.some(`it orders by ${showExpr(call)}, and this client does not run ${missing.join(", ")}`);
1014
+ }), Match.tag("Field", (field) => Option.match(orderTerm.collation, {
456
1015
  onNone: () => ordersIntrinsically(Schema.toEncoded(field.schema).ast) ? Option.none() : Option.some(`it orders by ${field.owner.name}.${field.key}, text with no declared collation`),
457
1016
  onSome: (collation) => Match.value(collation).pipe(Match.tagsExhaustive({
458
1017
  Binary: () => Option.none(),
459
1018
  AsciiFold: () => Option.none(),
460
1019
  Locale: ({ locale }) => Option.some(`it orders ${field.owner.name}.${field.key} by the backend's "${locale}" collation`)
461
1020
  }))
462
- })), Match.orElse(() => Option.some("it orders by something that is not a field")));
1021
+ })), Match.orElse(() => Option.some("it orders by something that is neither a field nor a call")));
463
1022
  /** Each Entity's id tie-break, made once, so a resolved order reuses one term. */
464
1023
  const idTerms = /* @__PURE__ */ new WeakMap();
465
1024
  const idTermOf = (entity) => {
@@ -565,6 +1124,15 @@ const walk = (expr, found) => {
565
1124
  walk(expr.sort, found);
566
1125
  for (const choice of Object.values(expr.choices)) walk(choice, found);
567
1126
  return;
1127
+ case "Call":
1128
+ case "Test":
1129
+ found.operators.add(expr.operator);
1130
+ Option.match(expansionOf(expr), {
1131
+ onSome: (expansion) => walk(expansion, found),
1132
+ onNone: () => expr.args.forEach((arg) => walk(arg, found))
1133
+ });
1134
+ return;
1135
+ default: return absurd(expr);
568
1136
  }
569
1137
  };
570
1138
  /**
@@ -580,14 +1148,16 @@ const dependenciesOf = (...nodes) => {
580
1148
  inputs: /* @__PURE__ */ new Set(),
581
1149
  next: /* @__PURE__ */ new Map(),
582
1150
  nextOrder: [],
583
- operations: /* @__PURE__ */ new Set()
1151
+ operations: /* @__PURE__ */ new Set(),
1152
+ operators: /* @__PURE__ */ new Set()
584
1153
  };
585
1154
  for (const term of nodes) walk(term, found);
586
1155
  return {
587
1156
  fields: found.order,
588
1157
  next: found.nextOrder,
589
1158
  inputs: [...found.inputs],
590
- operations: [...found.operations]
1159
+ operations: [...found.operations],
1160
+ operators: [...found.operators]
591
1161
  };
592
1162
  };
593
1163
  /** Every field an expression reads, as the nodes themselves, each node visited once. */
@@ -635,6 +1205,11 @@ const fieldsIn = function* (expr, seen) {
635
1205
  case "Chosen":
636
1206
  for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen);
637
1207
  return;
1208
+ case "Call":
1209
+ case "Test":
1210
+ for (const arg of expr.args) yield* fieldsIn(arg, seen);
1211
+ return;
1212
+ default: return absurd(expr);
638
1213
  }
639
1214
  };
640
1215
  /**
@@ -669,6 +1244,11 @@ const childrenOf = (expr) => {
669
1244
  case "Or": return expr.operands;
670
1245
  case "Not": return [expr.operand];
671
1246
  case "Compare": return [expr.left, expr.right];
1247
+ case "Call":
1248
+ case "Test": return Option.match(expansionOf(expr), {
1249
+ onSome: (expansion) => [expansion],
1250
+ onNone: () => expr.args
1251
+ });
672
1252
  }
673
1253
  };
674
1254
  /** A node's size as a tree, each distinct node sized once. */
@@ -690,6 +1270,19 @@ const query = (entity, where, orderBy) => Object.freeze(Object.assign(Object.cre
690
1270
  where: Object.freeze(where),
691
1271
  orderBy: Object.freeze(orderBy)
692
1272
  }));
1273
+ /**
1274
+ * Refuses a query whose predicates and order terms (every chosen alternative
1275
+ * among them) expand past `maxQueryNodes`, counting a shared node on every
1276
+ * path that reaches it: what an interpreter walks, and SQL writes out.
1277
+ */
1278
+ const checkSize = (step, where, orderBy) => {
1279
+ const sizes = /* @__PURE__ */ new Map();
1280
+ const terms = orderBy.flatMap((ordering) => Match.valueTags(ordering, {
1281
+ Term: ({ expr }) => [expr],
1282
+ Chosen: ({ choices }) => Object.values(choices)
1283
+ }));
1284
+ if ([...where, ...terms].reduce((sum, each) => sum + expandedSize(each, sizes), 0) > 1e3) throw new Error(`[foldkit-entity] Query.${step}: the query expands to more than ${maxQueryNodes} nodes, counting a shared node on every path that reaches it`);
1285
+ };
693
1286
  const Query = {
694
1287
  /** Every row of an Entity: the query each transformation narrows. */
695
1288
  from: (entity) => query(entity, [], []),
@@ -707,8 +1300,7 @@ const Query = {
707
1300
  if (predicates.length === 0) return self;
708
1301
  checkOwnership("where", "a predicate", self.entity, predicates);
709
1302
  const where = [...self.where, ...predicates];
710
- const sizes = /* @__PURE__ */ new Map();
711
- if (where.reduce((sum, predicate) => sum + expandedSize(predicate, sizes), 0) > 1e3) throw new Error(`[foldkit-entity] Query.where: the predicates expand to more than ${maxQueryNodes} nodes, counting a shared node on every path that reaches it`);
1303
+ checkSize("where", where, self.orderBy);
712
1304
  return query(self.entity, where, self.orderBy);
713
1305
  },
714
1306
  /**
@@ -719,7 +1311,9 @@ const Query = {
719
1311
  orderBy: (...terms) => (self) => {
720
1312
  if (terms.length === 0) return self;
721
1313
  checkOwnership("orderBy", "a term", self.entity, terms);
722
- return query(self.entity, self.where, [...self.orderBy, ...terms]);
1314
+ const orderBy = [...self.orderBy, ...terms];
1315
+ checkSize("orderBy", self.where, orderBy);
1316
+ return query(self.entity, self.where, orderBy);
723
1317
  },
724
1318
  /**
725
1319
  * The fixed terms this query orders by for one input: each chosen order
@@ -739,18 +1333,26 @@ const Query = {
739
1333
  /**
740
1334
  * Whether a client can order this query's rows exactly as the server does,
741
1335
  * for one input: every term over a number or a boolean (a row may lack it), or over text with a
742
- * portable collation (`binary`, `asciiFold`). A body that names no order
743
- * leaves it to the server, and is never placeable.
1336
+ * portable collation (`binary`, `asciiFold`), or a call whose primitive
1337
+ * operators the client's table (`operators`; none when not given) runs. A
1338
+ * body that names no order leaves it to the server, and is never placeable.
744
1339
  */
745
- placement: (self, input) => {
1340
+ placement: (self, input, options = {}) => {
746
1341
  if (self.orderBy.length === 0) return notPlaceable("its order is the server's: the body names none");
1342
+ const operators = options.operators ?? noOperators;
747
1343
  for (const orderTerm of Query.orderFor(self, input)) {
748
- const reason = unplaceable(orderTerm);
1344
+ const reason = unplaceable(orderTerm, operators);
749
1345
  if (Option.isSome(reason)) return notPlaceable(reason.value);
750
1346
  }
751
1347
  return placeable;
752
1348
  },
753
1349
  /**
1350
+ * Each operator the body calls, by name (`id`, or `id@version` past the
1351
+ * first), in the order it first calls them: a defined one, and each
1352
+ * primitive one its expansion calls.
1353
+ */
1354
+ operators: (self) => Query.dependencies(self).operators.map(operatorName$1),
1355
+ /**
754
1356
  * What the whole query reads: the fields and inputs of every predicate and
755
1357
  * every ordering term, and the operations it uses, with the fields also
756
1358
  * split by role.
@@ -762,8 +1364,10 @@ const Query = {
762
1364
  }),
763
1365
  /**
764
1366
  * The operations this query needs that `supported` does not list, in the
765
- * order the query uses them. Empty means an interpreter declaring
766
- * `supported` can answer it.
1367
+ * order the query uses them, then each primitive operator `operators` does
1368
+ * not implement, by name. Without `operators`, every primitive operator is
1369
+ * named: a list of operations implements none. Empty means an interpreter
1370
+ * declaring both can answer it.
767
1371
  *
768
1372
  * An interpreter declares what it runs and refuses the rest, rather than
769
1373
  * ignoring an operation it does not implement — which would answer a
@@ -777,10 +1381,7 @@ const Query = {
777
1381
  * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
778
1382
  * ```
779
1383
  */
780
- unsupported: (self, supported) => {
781
- const runs = new Set(supported);
782
- return Query.dependencies(self).operations.filter((operation) => !runs.has(operation));
783
- },
1384
+ unsupported: (self, supported, operators = noOperators) => unsupportedIn([...self.where, ...self.orderBy], supported, operators),
784
1385
  /**
785
1386
  * The whole query as readable text, one clause per line:
786
1387
  *
@@ -833,8 +1434,29 @@ const showExpr = (node) => {
833
1434
  case "Or": return node.operands.map(showConnected).join(" or ");
834
1435
  case "Not": return `not (${showExpr(node.operand)})`;
835
1436
  case "Compare": return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`;
1437
+ case "Call":
1438
+ case "Test": return `${operatorName$1(node.operator)}(${node.args.map(showOperand).join(", ")})`;
836
1439
  }
837
1440
  };
1441
+ /** A call's expansion, scalar or predicate alike. */
1442
+ const expansionOf = (call) => call.expansion;
1443
+ /**
1444
+ * What `nodes` need that an interpreter lacks: each kernel operation it does
1445
+ * not list, then each primitive operator its table does not implement, by
1446
+ * name. A defined operator needs nothing: what it means is walked instead.
1447
+ */
1448
+ const unsupportedIn = (nodes, supported, operators) => {
1449
+ const read = dependenciesOf(...nodes);
1450
+ const runs = new Set(supported);
1451
+ return [...read.operations.filter((operation) => !runs.has(operation)), ...missingFrom(read.operators, operators)];
1452
+ };
1453
+ /**
1454
+ * The primitive operators among `read` that `operators` does not implement, by
1455
+ * name. A defined one needs nothing: what it means was walked into `read`.
1456
+ */
1457
+ const missingFrom = (read, operators) => read.filter((operator) => Option.isNone(operator.definedAs) && !operators.has(operator)).map((operator) => missingName(operator, operators));
1458
+ /** An operator by its id, and its version when that is not the first. */
1459
+ const operatorName$1 = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
838
1460
  const symbols = {
839
1461
  lt: "<",
840
1462
  lte: "<=",
@@ -847,8 +1469,230 @@ const showConnected = (node) => Match.value(node).pipe(Match.tags({
847
1469
  Or: () => `(${showExpr(node)})`
848
1470
  }), Match.orElse(() => showExpr(node)));
849
1471
  const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
850
- //#endregion
851
- //#region src/evaluate.ts
1472
+ // src/tested.ts
1473
+ /**
1474
+ * What made each `Tested` record: `Conformance.laws` over one memory
1475
+ * implementation, or `Conformance.lawsBy` through a runner. A table records
1476
+ * only evidence of its own kind, so a record built by hand, copied, or tested
1477
+ * on another implementation is refused. Kept beside the records rather than in
1478
+ * them: a record is JSON a server publishes, and an implementation is a
1479
+ * function. Not exported from the package.
1480
+ */
1481
+ const testedOn = /* @__PURE__ */ new WeakMap();
1482
+ const ranByRunner = /* @__PURE__ */ new WeakSet();
1483
+ const stampTested = (record, implementation) => {
1484
+ testedOn.set(record, implementation);
1485
+ };
1486
+ const stampRun = (record) => {
1487
+ ranByRunner.add(record);
1488
+ };
1489
+ const implementationTested = (record) => Option.fromUndefinedOr(testedOn.get(record));
1490
+ const testedByRunner = (record) => ranByRunner.has(record);
1491
+ // src/text.ts
1492
+ /**
1493
+ * The kernel's text operators: primitive, so each interpreter implements them,
1494
+ * and each states what it means here, where data-query §6.0.1 holds the rest.
1495
+ */
1496
+ const Text = {
1497
+ /**
1498
+ * Whether the first text begins with the second, under the first's collation.
1499
+ *
1500
+ * | Case | Answer |
1501
+ * | --- | --- |
1502
+ * | either is null | unknown |
1503
+ * | the prefix is `''` | true |
1504
+ * | otherwise | whether it begins so, compared under the collation |
1505
+ *
1506
+ * The collation is the one its text operands share (a field's declared one,
1507
+ * or a call's), or one given to the call. `binary` compares exactly;
1508
+ * `asciiFold` folds ASCII letters on both sides. Operands declaring
1509
+ * different collations, text with none, or a backend's locale are refused
1510
+ * where the call is written.
1511
+ * Prefixes are by character, so non-ASCII and astral text begin as they read.
1512
+ *
1513
+ * ```ts
1514
+ * Query.where(Text.startsWith(Product.fields.upc, input.search))
1515
+ * ```
1516
+ */
1517
+ startsWith: Expr.operator("text.startsWith", {
1518
+ input: [Schema.NullOr(Schema.String), Schema.NullOr(Schema.String)],
1519
+ output: Schema.Boolean,
1520
+ collation: "required",
1521
+ description: "Whether the first text begins with the second, under the first's collation."
1522
+ }) };
1523
+ // src/operators.ts
1524
+ /**
1525
+ * How the in-memory interpreter runs primitive operators: a table of
1526
+ * implementations, passed to `evaluate` and every judge as a value. A table is
1527
+ * immutable and implements each operator once; nothing registers anything
1528
+ * globally. See `docs/design/expr-operations-DESIGN.md` §5.4.
1529
+ */
1530
+ const Evidence = Data.taggedEnum();
1531
+ /** A JSON Schema document's root: an object (`$defs` holds what it refers to). */
1532
+ const JsonSchema = Schema.Record(Schema.String, Schema.Unknown);
1533
+ /**
1534
+ * An operator as JSON, by its signature and never its body (a defined
1535
+ * operator says `defined`, not what it means): what a server can publish of
1536
+ * what a body may call, and a client compare with what it runs. Its schemas
1537
+ * are each argument's and the result's stored side, as JSON Schemas.
1538
+ */
1539
+ const OperatorDescription = Schema.Struct({
1540
+ /** By id, and `@version` past the first: what tables, evidence and refusals name. */
1541
+ name: Schema.String,
1542
+ id: Schema.String,
1543
+ version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
1544
+ description: Schema.NullOr(Schema.String),
1545
+ input: Schema.Array(JsonSchema),
1546
+ output: JsonSchema,
1547
+ nulls: Schema.Literals(["strict", "handled"]),
1548
+ collation: Schema.Literals([
1549
+ "none",
1550
+ "operands",
1551
+ "required"
1552
+ ]),
1553
+ laws: Schema.Array(LawDescription),
1554
+ defined: Schema.Boolean
1555
+ });
1556
+ const described = (operator) => ({
1557
+ name: nameOf(operator),
1558
+ id: operator.id,
1559
+ version: operator.version,
1560
+ description: Option.getOrNull(operator.description),
1561
+ input: operator.input.map(jsonSchemaOf),
1562
+ output: jsonSchemaOf(operator.output),
1563
+ nulls: operator.nulls,
1564
+ collation: operator.collation,
1565
+ laws: operator.laws.map(Law.describe),
1566
+ defined: Option.isSome(operator.definedAs)
1567
+ });
1568
+ /** An operator by its id, and its version when that is not the first. */
1569
+ const nameOf = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
1570
+ const fail$3 = (what) => {
1571
+ throw new Error(`[foldkit-entity] Operators: ${what}`);
1572
+ };
1573
+ const table = (implementations, checked, evidence) => {
1574
+ const byOperator = /* @__PURE__ */ new Map();
1575
+ const byName = /* @__PURE__ */ new Map();
1576
+ for (const { operator, run } of implementations) {
1577
+ if (byOperator.has(operator)) fail$3(`${nameOf(operator)} is implemented twice; replace one with Operators.override`);
1578
+ const named = byName.get(nameOf(operator));
1579
+ if (named !== void 0 && named !== operator) fail$3(`two operators are named ${nameOf(operator)}; give one another id or version`);
1580
+ byName.set(nameOf(operator), operator);
1581
+ byOperator.set(operator, run);
1582
+ }
1583
+ return Object.freeze({
1584
+ _tag: "MemoryOperators",
1585
+ has: (operator) => byOperator.has(operator),
1586
+ versions: (id) => implementations.filter(({ operator }) => operator.id === id).map(({ operator }) => operator.version),
1587
+ get: (operator) => Option.fromUndefinedOr(byOperator.get(operator)),
1588
+ named: (name) => Option.fromUndefinedOr(byName.get(name)),
1589
+ checked,
1590
+ implementations: Object.freeze([...implementations]),
1591
+ evidence: Object.freeze([...evidence])
1592
+ });
1593
+ };
1594
+ /** Whether two laws, as JSON, are the same law. */
1595
+ const sameLaw = (left, right) => JSON.stringify(left) === JSON.stringify(right);
1596
+ /** An implementation, its operator's null rule checked against the function chosen for it. */
1597
+ const implementation = (operator, nulls, run) => {
1598
+ if (Option.isSome(operator.definedAs)) fail$3(`${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`);
1599
+ if (operator.nulls !== nulls) fail$3(nulls === "strict" ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls` : `${nameOf(operator)} is strict about null; implement it with Operators.implement`);
1600
+ return Object.freeze({
1601
+ operator,
1602
+ run: (args, context) => run(...args, context)
1603
+ });
1604
+ };
1605
+ const Operators = {
1606
+ /**
1607
+ * An implementation of a strict operator: a pure function of its arguments'
1608
+ * stored values, never given a null (the kernel answers null, or unknown, for
1609
+ * one first), and told the call's collation last.
1610
+ *
1611
+ * ```ts
1612
+ * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))
1613
+ * ```
1614
+ */
1615
+ implement: (operator, run) => implementation(operator.descriptor, "strict", run),
1616
+ /**
1617
+ * An implementation of an operator declared `nulls: 'handled'`: given nulls
1618
+ * as they are, it answers for them; a predicate answers `null` for unknown.
1619
+ */
1620
+ implementHandlingNulls: (operator, run) => implementation(operator.descriptor, "handled", run),
1621
+ /** A table of implementations. One operator implemented twice, or two under one name, is refused. */
1622
+ memory: (...implementations) => table(implementations, false, []),
1623
+ /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */
1624
+ merge: (left, right) => {
1625
+ const both = right.implementations.filter(({ operator }) => left.has(operator));
1626
+ if (both.length > 0) fail$3(`both tables implement ${both.map(({ operator }) => nameOf(operator)).join(", ")}; replace with Operators.override`);
1627
+ return table([...left.implementations, ...right.implementations], left.checked || right.checked, [...left.evidence, ...right.evidence]);
1628
+ },
1629
+ /**
1630
+ * The table with these implementations in place of its own for the same
1631
+ * operators. Evidence of a replaced implementation goes with it: it was
1632
+ * that implementation's.
1633
+ */
1634
+ override: (base, ...implementations) => {
1635
+ const replaced = new Set(implementations.map(({ operator }) => operator));
1636
+ const names = new Set([...replaced].map(nameOf));
1637
+ return table([...base.implementations.filter(({ operator }) => !replaced.has(operator)), ...implementations], base.checked, base.evidence.filter(({ operator, law }) => !names.has(operator) && !Law.witnessesNamed(law).some((name) => names.has(name))));
1638
+ },
1639
+ /**
1640
+ * The table with what is known of its implementations' laws recorded: each
1641
+ * record of an operator it implements and a law that operator declares.
1642
+ * `Conformance.laws` gives `Tested` records, each of the implementation it
1643
+ * ran, and a table takes only those of its own; `Evidence.Proven` says a
1644
+ * proof elsewhere covers one.
1645
+ */
1646
+ withEvidence: (base, evidence) => {
1647
+ const own = new Map(base.implementations.map((each) => [nameOf(each.operator), each]));
1648
+ for (const record of evidence) {
1649
+ const implemented = own.get(record.operator) ?? fail$3(`evidence names ${record.operator}, which this table does not implement`);
1650
+ if (!implemented.operator.laws.map(Law.describe).some((law) => sameLaw(law, record.law))) fail$3(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`);
1651
+ if (record._tag === "Tested" && !Option.exists(implementationTested(record), (tested) => tested === implemented)) fail$3(`evidence of ${record.operator}'s ${record.law.kind} law was not tested on this table's implementation; test it with Conformance.laws(op, table)`);
1652
+ }
1653
+ return table(base.implementations, base.checked, [...base.evidence, ...evidence]);
1654
+ },
1655
+ /**
1656
+ * The memory implementation `Conformance.laws` tested a record on; none for
1657
+ * a record of a runner (`Conformance.lawsBy`) or a proof.
1658
+ */
1659
+ testedOn: (record) => implementationTested(record),
1660
+ /**
1661
+ * Whether `Conformance.lawsBy` made a record, through a runner: what an SQL
1662
+ * table takes. Which runner it was, the database's or another, is the
1663
+ * caller's word; a record built by hand, copied, or tested in memory is not.
1664
+ */
1665
+ testedByRunner,
1666
+ /**
1667
+ * Each operator the table implements, by name, with the laws it declares and
1668
+ * the evidence the table records of them: what a server can publish of how
1669
+ * it runs a body. JSON as it is.
1670
+ */
1671
+ describeTable: (base) => base.implementations.map(({ operator }) => ({
1672
+ ...described(operator),
1673
+ evidence: base.evidence.filter((record) => record.operator === nameOf(operator))
1674
+ })),
1675
+ /**
1676
+ * An operator as JSON (`OperatorDescription`): its name, version and
1677
+ * description, each argument's and its result's stored side as a JSON
1678
+ * Schema (as JSON carries it: a number also admits the strings `"Infinity"`,
1679
+ * `"-Infinity"` and `"NaN"`), its null and collation rules, its laws, and
1680
+ * whether it is defined. Its signature, never its body.
1681
+ */
1682
+ describe: (operator) => described(operator.descriptor),
1683
+ /**
1684
+ * The table, checking every answer against its operator's output schema, so
1685
+ * an implementation that answers the wrong kind fails where it answered. For
1686
+ * tests: it costs a decode per call.
1687
+ */
1688
+ checked: (base) => table(base.implementations, true, base.evidence),
1689
+ /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
1690
+ kernel: table([implementation(Text.startsWith.descriptor, "strict", (...given) => {
1691
+ const [text, prefix, { collation }] = given;
1692
+ return Option.exists(collation, (each) => each._tag === "AsciiFold") ? Collation.foldAscii(text).startsWith(Collation.foldAscii(prefix)) : text.startsWith(prefix);
1693
+ })], false, [])
1694
+ };
1695
+ // src/evaluate.ts
852
1696
  /**
853
1697
  * The reference interpreter: a query body run over rows already in memory.
854
1698
  *
@@ -879,21 +1723,91 @@ var QueryEvaluateError = class extends Error {
879
1723
  this.name = "QueryEvaluateError";
880
1724
  }
881
1725
  };
1726
+ /**
1727
+ * A call of a primitive operator the table does not implement. Its own class,
1728
+ * because a form judging an invariant reads it as a judgement it cannot make
1729
+ * (`Undecided`), not as a failure.
1730
+ */
1731
+ var OperatorMissingError = class extends QueryEvaluateError {
1732
+ operator;
1733
+ /** The operator by its id, and its version past the first. */
1734
+ named;
1735
+ /** `operators`, the table that lacks it, names the versions of it that it does hold. */
1736
+ constructor(operator, operators = noOperators) {
1737
+ super(`this interpreter does not run the operator "${missingName(operator, operators)}"`);
1738
+ this.name = "OperatorMissingError";
1739
+ this.operator = operator;
1740
+ this.named = operatorName(operator);
1741
+ }
1742
+ };
1743
+ /** An operator by its id, and its version when that is not the first. */
1744
+ const operatorName = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
882
1745
  const valueOf = (node, scope) => {
883
1746
  switch (node._tag) {
884
1747
  case "Field": return scope.row[node.key];
885
1748
  case "Next": return scope.next[node.field.key];
886
1749
  case "Literal": return node.value;
887
1750
  case "Input": return scope.input[node.key];
1751
+ case "Call": return called(node, scope);
1752
+ default: return absurd(node);
888
1753
  }
889
1754
  };
890
- const isNull = (value) => value === null || value === void 0;
891
1755
  /**
892
- * Lowercases ASCII letters and leaves every other character as it is, which is
893
- * what SQLite's `lower` does without ICU and so what the compiled SQL folds to.
894
- * `toLowerCase` would fold `É` to `é` here and not there.
1756
+ * What a call comes to, as a value (a predicate's truth as SQL's, unknown as
1757
+ * null). A defined operator's is what it means, as SQL compiles it; a
1758
+ * primitive one's is the table's implementation, or it is refused by name.
1759
+ */
1760
+ const called = (call, scope) => {
1761
+ const expansion = call.expansion;
1762
+ return Option.match(expansion, {
1763
+ onSome: (body) => sideOf(body, scope),
1764
+ onNone: () => Option.match(scope.operators.get(call.operator), {
1765
+ onSome: (run) => ran(call, run, scope),
1766
+ onNone: () => {
1767
+ throw new OperatorMissingError(call.operator, scope.operators);
1768
+ }
1769
+ })
1770
+ });
1771
+ };
1772
+ /** A call of a primitive operator run, its arguments worked out over the scope. */
1773
+ const ran = (call, run, scope) => runWith(call.operator, run, call.args.map((arg) => sideOf(arg, scope)), call.collation, call._tag === "Test", scope.operators.checked);
1774
+ /**
1775
+ * A primitive operator run over values: strict about null and NUL before it
1776
+ * is asked, a throw it makes named as its own, and, in a checked table, its
1777
+ * answer held to its output schema (a predicate's null is its unknown).
895
1778
  */
896
- const foldAscii = (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());
1779
+ const runWith = (operator, run, values, collation, predicate, checked) => {
1780
+ if (values.some(holdsNul)) throw new QueryEvaluateError(`the operator "${operatorName(operator)}" was given text holding a NUL character, which SQL text cannot hold portably`);
1781
+ if (operator.nulls === "strict" && values.some(isNull)) return null;
1782
+ let answer;
1783
+ try {
1784
+ answer = run(values.map((value) => value === void 0 ? null : value), { collation });
1785
+ } catch (error) {
1786
+ if (error instanceof QueryEvaluateError) throw error;
1787
+ throw new QueryEvaluateError(`the operator "${operatorName(operator)}" failed: ${error instanceof Error ? error.message : String(error)}`);
1788
+ }
1789
+ if (checked && !(predicate && answer === null) && !Schema.is(Schema.toEncoded(operator.output))(answer)) throw new QueryEvaluateError(`the operator "${operatorName(operator)}" answered ${JSON.stringify(answer)}, which its output schema does not admit`);
1790
+ return answer;
1791
+ };
1792
+ /**
1793
+ * A primitive operator over stored values, as a call of it is run: what a
1794
+ * computed assignment comes to (`Write.apply`). Refused, as a call is, when
1795
+ * `operators` does not implement it.
1796
+ */
1797
+ const applyOperator = (operator, values, options) => Option.match(options.operators.get(operator), {
1798
+ onNone: () => {
1799
+ throw new OperatorMissingError(operator, options.operators);
1800
+ },
1801
+ onSome: (run) => runWith(operator, run, values, options.collation, SchemaAST.isBoolean(Schema.toEncoded(operator.output).ast), options.operators.checked)
1802
+ });
1803
+ /** A predicate operator's answer as a truth: null is unknown, anything but a boolean refused. */
1804
+ const truthOf = (call, answer) => {
1805
+ if (answer === null || answer === void 0) return "unknown";
1806
+ if (typeof answer !== "boolean") throw new QueryEvaluateError(`the operator "${operatorName(call.operator)}" answered ${JSON.stringify(answer)}, which is not a truth`);
1807
+ return answer;
1808
+ };
1809
+ const isNull = (value) => value === null || value === void 0;
1810
+ const { foldAscii } = Collation;
897
1811
  const NUL = String.fromCharCode(0);
898
1812
  /**
899
1813
  * Whether `value` is text holding a NUL, which Postgres text cannot hold and
@@ -903,23 +1817,49 @@ const holdsNul = (value) => typeof value === "string" && value.includes(NUL);
903
1817
  /** A predicate used as a value is its own truth; anything else is its value. */
904
1818
  const sideOf = (node, scope) => isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope);
905
1819
  /**
1820
+ * What an operand comes to over no row: a call of literals and inputs, run by
1821
+ * `operators` (the kernel's when not given), a predicate as its truth with
1822
+ * unknown as null. How a conformance check asks an implementation one
1823
+ * question; refuses what `evaluate` refuses (an operator the table lacks,
1824
+ * text holding NUL).
1825
+ */
1826
+ const valueOfOperand = (node, options = {}) => sideOf(node, {
1827
+ row: {},
1828
+ input: options.input ?? {},
1829
+ next: {},
1830
+ operators: options.operators ?? Operators.kernel
1831
+ });
1832
+ /**
1833
+ * Refuses a value the query was given (a literal or an input) holding a NUL,
1834
+ * before any null beside it can answer: SQL refuses such a parameter where it
1835
+ * compiles, whatever the row holds. A NUL stored in a row is refused after,
1836
+ * as SQL meets it only beside a value that is not null.
1837
+ */
1838
+ const refuseGivenNul = (message, sides) => {
1839
+ if (sides.some(([side, value]) => !isPredicate(side) && (side._tag === "Literal" || side._tag === "Input") && holdsNul(value))) throw new QueryEvaluateError(message);
1840
+ };
1841
+ /**
906
1842
  * A predicate compared as a value. SQL's unknown is null there too, so an
907
1843
  * unknown compared to anything stays unknown rather than becoming false.
908
1844
  */
909
1845
  const truthValue = (truth) => truth === "unknown" ? null : truth;
910
1846
  const holds = (node, scope) => {
911
1847
  switch (node._tag) {
1848
+ case "Test": return truthOf(node, called(node, scope));
912
1849
  case "Eq": {
913
1850
  const left = sideOf(node.left, scope);
914
1851
  const right = sideOf(node.right, scope);
1852
+ const nul = "an equality was given text holding a NUL character, which SQL text cannot hold portably";
1853
+ refuseGivenNul(nul, [[node.left, left], [node.right, right]]);
915
1854
  if (isNull(left) || isNull(right)) return "unknown";
916
- if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("an equality was given text holding a NUL character, which SQL text cannot hold portably");
1855
+ if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul);
917
1856
  return left === right;
918
1857
  }
919
1858
  case "Null": return isNull(valueOf(node.operand, scope)) !== node.present;
920
1859
  case "Contains": {
921
1860
  const value = valueOf(node.value, scope);
922
1861
  const search = sideOf(node.search, scope);
1862
+ refuseGivenNul("a containment test was given text holding a NUL character, which SQL text cannot hold portably", [[node.search, search], [node.value, value]]);
923
1863
  if (isNull(value) || isNull(search)) return "unknown";
924
1864
  if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
925
1865
  if (holdsNul(value) || holdsNul(search)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
@@ -952,8 +1892,10 @@ const holds = (node, scope) => {
952
1892
  case "Compare": {
953
1893
  const left = valueOf(node.left, scope);
954
1894
  const right = valueOf(node.right, scope);
1895
+ const nul = "a comparison was given text holding a NUL character, which SQL text cannot hold portably";
1896
+ refuseGivenNul(nul, [[node.left, left], [node.right, right]]);
955
1897
  if (isNull(left) || isNull(right)) return "unknown";
956
- if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("a comparison was given text holding a NUL character, which SQL text cannot hold portably");
1898
+ if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul);
957
1899
  const kind = typeof left;
958
1900
  if (kind !== typeof right || kind !== "number" && kind !== "string") throw new QueryEvaluateError("a comparison was given values that do not order together");
959
1901
  const order = compare(left, right, node.collation);
@@ -969,7 +1911,7 @@ const readsAField = /* @__PURE__ */ new WeakMap();
969
1911
  * before it builds anything: `isNull($status)` is known before any row is.
970
1912
  * Refuses what `evaluate` refuses (text holding a NUL).
971
1913
  */
972
- const decided = (node, input) => {
1914
+ const decided = (node, input, operators = Operators.kernel) => {
973
1915
  let reads = readsAField.get(node);
974
1916
  if (reads === void 0) {
975
1917
  const read = dependenciesOf(node);
@@ -979,20 +1921,23 @@ const decided = (node, input) => {
979
1921
  return reads ? Option.none() : Option.some(holds(node, {
980
1922
  row: {},
981
1923
  input,
982
- next: {}
1924
+ next: {},
1925
+ operators
983
1926
  }));
984
1927
  };
985
1928
  /** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
986
- const truthOver = (node, row, input = {}, next = {}) => holds(node, {
1929
+ const truthOver = (node, row, input = {}, next = {}, operators = Operators.kernel) => holds(node, {
987
1930
  row,
988
1931
  input,
989
- next
1932
+ next,
1933
+ operators
990
1934
  });
991
1935
  /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
992
- const matches = (body, row, input) => body.where.every((node) => holds(node, {
1936
+ const matches = (body, row, input, operators) => body.where.every((node) => holds(node, {
993
1937
  row,
994
1938
  input,
995
- next: {}
1939
+ next: {},
1940
+ operators
996
1941
  }) === true);
997
1942
  /** The kinds of value this interpreter orders by; every key of one term must share one. */
998
1943
  const comparable = /* @__PURE__ */ new Set([
@@ -1024,58 +1969,72 @@ const compare = (left, right, collation) => {
1024
1969
  if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
1025
1970
  return left - right;
1026
1971
  };
1972
+ /** Each term's key for one row: a field's value, or what a call comes to over the row. */
1973
+ const keysOf = (row, terms, scope) => terms.map((term) => valueOf(term.expr, {
1974
+ row,
1975
+ input: scope.input,
1976
+ next: {},
1977
+ operators: scope.operators
1978
+ }));
1027
1979
  /**
1028
1980
  * Refuses an ordering this interpreter will not answer for, before sorting, so
1029
1981
  * the refusal names the first offending row in row order rather than whichever
1030
1982
  * pair the engine's sort happened to compare first. Every term is checked over
1031
- * every row: a key whose kind differs from the first present one's. A null key
1032
- * is not refused; the term says where it goes.
1983
+ * every row's keys: a key whose kind differs from the first present one's. A
1984
+ * null key is not refused; the term says where it goes.
1033
1985
  */
1034
- const checkOrder = (rows, terms, query) => {
1035
- for (const term of terms) {
1036
- if (term.expr._tag !== "Field") throw new QueryEvaluateError(`query "${query}" orders by something that is not a field, which this interpreter cannot run yet`);
1037
- if (Option.exists(term.collation, (declared) => declared._tag === "Locale")) throw new QueryEvaluateError(`query "${query}" orders "${term.expr.key}" by a backend's locale collation, which only that backend has`);
1038
- const key = term.expr.key;
1039
- let first;
1040
- for (const row of rows) {
1041
- const value = row[key];
1042
- if (isNull(value)) continue;
1043
- const kind = typeof value;
1044
- first ??= kind;
1045
- if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
1046
- }
1986
+ const checkOrder = (keys, terms, query) => terms.forEach((term, index) => {
1987
+ if (term.expr._tag !== "Field" && term.expr._tag !== "Call") throw new QueryEvaluateError(`query "${query}" orders by something that is neither a field nor a call`);
1988
+ if (Option.exists(term.collation, (declared) => declared._tag === "Locale")) throw new QueryEvaluateError(`query "${query}" orders ${Expr.show(term.expr)} by a backend's locale collation, which only that backend has`);
1989
+ let first;
1990
+ for (const row of keys) {
1991
+ const value = row[index];
1992
+ if (isNull(value)) continue;
1993
+ const kind = typeof value;
1994
+ first ??= kind;
1995
+ if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
1047
1996
  }
1048
- };
1049
- /** Two rows by checked terms: negative when `left` sorts first. */
1997
+ });
1998
+ /** Two rows' keys by checked terms: negative when `left` sorts first. */
1050
1999
  const byTerms = (terms, left, right) => {
1051
- for (const term of terms) {
1052
- const key = term.expr.key;
1053
- const absentLeft = isNull(left[key]);
1054
- const absentRight = isNull(right[key]);
2000
+ for (const [index, term] of terms.entries()) {
2001
+ const absentLeft = isNull(left[index]);
2002
+ const absentRight = isNull(right[index]);
1055
2003
  if (absentLeft || absentRight) {
1056
2004
  if (absentLeft && absentRight) continue;
1057
2005
  return absentLeft === (term.nulls === "first") ? -1 : 1;
1058
2006
  }
1059
- const sign = compare(left[key], right[key], term.collation);
2007
+ const sign = compare(left[index], right[index], term.collation);
1060
2008
  if (sign !== 0) return term.direction === "asc" ? sign : -sign;
1061
2009
  }
1062
2010
  return 0;
1063
2011
  };
1064
- const ordered = (rows, terms, query) => {
1065
- if (terms.length === 0 || rows.length < 2) return [...rows];
1066
- checkOrder(rows, terms, query);
1067
- return [...rows].sort((left, right) => byTerms(terms, left, right));
2012
+ const ordered = (rows, terms, query, scope) => {
2013
+ if (terms.length === 0) return [...rows];
2014
+ const keyed = rows.map((row) => ({
2015
+ row,
2016
+ keys: keysOf(row, terms, scope)
2017
+ }));
2018
+ checkOrder(keyed.map(({ keys }) => keys), terms, query);
2019
+ return keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row);
1068
2020
  };
1069
2021
  /**
1070
2022
  * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),
1071
- * as `evaluate` sorts: negative when it comes first. Refuses what `evaluate`
1072
- * refuses, for these two rows: a term not over a field, a locale collation,
1073
- * or keys of different kinds. For a client placing one row among others it
2023
+ * as `evaluate` sorts: negative when it comes first. A call among them runs
2024
+ * over each row with `input` and `operators` (the kernel's when not given).
2025
+ * Refuses what `evaluate` refuses, for these two rows: a term over neither a
2026
+ * field nor a call, a locale collation, keys of different kinds, or an
2027
+ * operator the table lacks. For a client placing one row among others it
1074
2028
  * holds.
1075
2029
  */
1076
- const compareRows = (terms, left, right, query) => {
1077
- checkOrder([left, right], terms, query);
1078
- return byTerms(terms, left, right);
2030
+ const compareRows = (terms, left, right, query, options = {}) => {
2031
+ const scope = {
2032
+ input: options.input ?? {},
2033
+ operators: options.operators ?? Operators.kernel
2034
+ };
2035
+ const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)];
2036
+ checkOrder(keys, terms, query);
2037
+ return byTerms(terms, keys[0], keys[1]);
1079
2038
  };
1080
2039
  /**
1081
2040
  * The operations this interpreter runs. It is the reference, so this is the
@@ -1099,8 +2058,8 @@ const supported = [
1099
2058
  * than skipping it and answering a different question. Called by `evaluate`;
1100
2059
  * call it directly to check a body once instead of on every run.
1101
2060
  */
1102
- const assertSupported = (body) => {
1103
- const missing = Query.unsupported(body, supported);
2061
+ const assertSupported = (body, operators = Operators.kernel) => {
2062
+ const missing = Query.unsupported(body, supported, operators);
1104
2063
  if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
1105
2064
  };
1106
2065
  /**
@@ -1111,12 +2070,56 @@ const assertSupported = (body) => {
1111
2070
  * placeholders were built with — the same record the query would be called
1112
2071
  * with anywhere else.
1113
2072
  */
1114
- const evaluate = (body, input, rows) => {
1115
- assertSupported(body);
1116
- return ordered(rows.filter((row) => matches(body, row, input)), Query.orderFor(body, input), body.entity.name);
2073
+ const evaluate = (body, input, rows, options = {}) => {
2074
+ const operators = options.operators ?? Operators.kernel;
2075
+ assertSupported(body, operators);
2076
+ return ordered(rows.filter((row) => matches(body, row, input, operators)), Query.orderFor(body, input), body.entity.name, {
2077
+ input,
2078
+ operators
2079
+ });
2080
+ };
2081
+ /**
2082
+ * As `evaluate`, with each row judged alone: a row whose own values are
2083
+ * refused (text holding a NUL, a value an operator fails on) is set aside in
2084
+ * `refused` and the others are still answered. A client judging the rows it
2085
+ * holds wants this, since one bad stored row says nothing about the rest.
2086
+ *
2087
+ * What no single row causes still refuses the run: an operation or operator
2088
+ * the table lacks, an order by a locale collation, an input the body reads
2089
+ * holding a NUL (every row would refuse, and no row is the cause), and order
2090
+ * keys of different kinds across rows.
2091
+ */
2092
+ const evaluateEach = (body, input, rows, options = {}) => {
2093
+ const operators = options.operators ?? Operators.kernel;
2094
+ assertSupported(body, operators);
2095
+ const terms = Query.orderFor(body, input);
2096
+ const scope = {
2097
+ input,
2098
+ operators
2099
+ };
2100
+ const keyed = [];
2101
+ const refused = [];
2102
+ for (const row of rows) try {
2103
+ if (matches(body, row, input, operators)) keyed.push({
2104
+ row,
2105
+ keys: keysOf(row, terms, scope)
2106
+ });
2107
+ } catch (error) {
2108
+ if (!(error instanceof QueryEvaluateError) || givenNul(body, terms, input)) throw error;
2109
+ refused.push(row);
2110
+ }
2111
+ checkOrder(keyed.map(({ keys }) => keys), terms, body.entity.name);
2112
+ return {
2113
+ matched: keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row),
2114
+ refused
2115
+ };
1117
2116
  };
1118
- //#endregion
1119
- //#region src/invariant.ts
2117
+ /** Whether a constant or an input the body reads is text holding a NUL, or a list holding one. */
2118
+ const givenNul = (body, terms, input) => Expr.givesNul(...body.where, ...terms.map((term) => term.expr)) || Query.dependencies(body).inputs.some((key) => {
2119
+ const value = input[key];
2120
+ return Array.isArray(value) ? value.some(holdsNul) : holdsNul(value);
2121
+ });
2122
+ // src/invariant.ts
1120
2123
  /**
1121
2124
  * Invariants: what every stored row of an Entity must hold, and what every
1122
2125
  * change of one must, declared once on the Entity through its metadata and read
@@ -1172,23 +2175,30 @@ const invariant = (id, build, options) => Object.assign((entity) => {
1172
2175
  }, { id });
1173
2176
  const invariantsOf = (entity) => Invariants.get(entity.metadata);
1174
2177
  /** `judge` with the invariants given, as a binding that keeps them holds them. */
1175
- const judgeAgainst = (invariants, change) => {
2178
+ const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
1176
2179
  const missing = /* @__PURE__ */ new Set();
2180
+ const unrun = /* @__PURE__ */ new Set();
1177
2181
  const failures = [];
1178
2182
  const { after, before } = change;
1179
2183
  for (const held of invariants) {
1180
2184
  if (readsBefore(held) && before === void 0) continue;
1181
2185
  const absent = [...held.after.filter((key) => !Object.hasOwn(after, key)), ...held.before.filter((key) => !Object.hasOwn(before ?? {}, key))];
1182
2186
  if (absent.length > 0) absent.forEach((key) => missing.add(key));
1183
- else if (truthOver(held.predicate, before ?? {}, {}, after) !== true) failures.push(held);
2187
+ else try {
2188
+ if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) failures.push(held);
2189
+ } catch (error) {
2190
+ if (!(error instanceof OperatorMissingError)) throw error;
2191
+ unrun.add(error.named);
2192
+ }
1184
2193
  }
1185
2194
  if (failures.length > 0) return {
1186
2195
  _tag: "Invalid",
1187
2196
  failures
1188
2197
  };
1189
- if (missing.size > 0) return {
2198
+ if (missing.size > 0 || unrun.size > 0) return {
1190
2199
  _tag: "Undecided",
1191
- fields: [...missing]
2200
+ fields: [...missing],
2201
+ operators: [...unrun]
1192
2202
  };
1193
2203
  return { _tag: "Valid" };
1194
2204
  };
@@ -1199,7 +2209,7 @@ const judgeAgainst = (invariants, change) => {
1199
2209
  * undecided, never valid. Without `before` (a create), transition invariants
1200
2210
  * are not judged.
1201
2211
  */
1202
- const judge = (entity, change) => judgeAgainst(invariantsOf(entity), change);
2212
+ const judge = (entity, change, operators = Operators.kernel) => judgeAgainst(invariantsOf(entity), change, operators);
1203
2213
  /**
1204
2214
  * The row an input's value describes, judged under its Entity's state
1205
2215
  * invariants: each key mapped to a field, encoded as the store holds it. An
@@ -1207,7 +2217,7 @@ const judge = (entity, change) => judgeAgainst(invariantsOf(entity), change);
1207
2217
  * key left out) is undecided, so a partial input is never called valid on its
1208
2218
  * account. It has no row before, so it judges no transition.
1209
2219
  */
1210
- const judgeInput = (input, value) => {
2220
+ const judgeInput = (input, value, operators = Operators.kernel) => {
1211
2221
  const invariants = invariantsOf(input.entity);
1212
2222
  if (invariants.length === 0) return { _tag: "Valid" };
1213
2223
  const members = input.members;
@@ -1222,14 +2232,14 @@ const judgeInput = (input, value) => {
1222
2232
  row[member.key] = encoded;
1223
2233
  });
1224
2234
  }
1225
- return judgeAgainst(invariants, { after: row });
2235
+ return judgeAgainst(invariants, { after: row }, operators);
1226
2236
  };
1227
2237
  /**
1228
2238
  * The Entity's state invariants as an Effect Schema check over its row type:
1229
2239
  * each failure at its path, with its message. The value is encoded first,
1230
2240
  * field by field, so it is judged as the store would hold it.
1231
2241
  */
1232
- const check = (entity) => Schema.makeFilter((value) => {
2242
+ const check = (entity, options = {}) => Schema.makeFilter((value) => {
1233
2243
  const fields = entity.fields;
1234
2244
  const decoded = value;
1235
2245
  const row = {};
@@ -1237,31 +2247,14 @@ const check = (entity) => Schema.makeFilter((value) => {
1237
2247
  if (!Object.hasOwn(decoded, key)) continue;
1238
2248
  row[key] = Schema.encodeUnknownSync(field.schema)(decoded[key]);
1239
2249
  }
1240
- const judged = judge(entity, { after: row });
2250
+ const judged = judge(entity, { after: row }, options.operators);
1241
2251
  if (judged._tag !== "Invalid") return void 0;
1242
2252
  return judged.failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
1243
2253
  path: [key],
1244
2254
  issue: failure.message
1245
2255
  })));
1246
2256
  });
1247
- //#endregion
1248
- //#region src/shape.ts
1249
- const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
1250
- const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
1251
- /** What a schema's AST holds, read through Effect's own guards. */
1252
- const SchemaShape = {
1253
- /** True for the `null` and `undefined` members that make a schema optional. */
1254
- isNullish,
1255
- /**
1256
- * The members of a schema with `null` and `undefined` set aside, so optional
1257
- * text is still text; a schema that is not a union is its one member.
1258
- */
1259
- present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
1260
- /** True when every value the schema admits is a string. */
1261
- isText
1262
- };
1263
- //#endregion
1264
- //#region src/readFilter.ts
2257
+ // src/readFilter.ts
1265
2258
  /**
1266
2259
  * The members a server filters an Entity's rows by under a rule the client
1267
2260
  * does not run, such as an authorization rule. A client that places rows in
@@ -1280,8 +2273,7 @@ const ReadFilter = {
1280
2273
  /** The members an Entity's metadata names, every attachment's together. */
1281
2274
  members: (metadata) => key.get(metadata)[0] ?? []
1282
2275
  };
1283
- //#endregion
1284
- //#region src/words.ts
2276
+ // src/words.ts
1285
2277
  const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
1286
2278
  const Words = {
1287
2279
  /**
@@ -1299,8 +2291,7 @@ of: (schema) => {
1299
2291
  description: Option.orElse(text(resolved.description), () => text(own["description"]))
1300
2292
  };
1301
2293
  } };
1302
- //#endregion
1303
- //#region src/write.ts
2294
+ // src/write.ts
1304
2295
  /**
1305
2296
  * A write as a value: what an operation changes, declared over the input it
1306
2297
  * takes, so the changes can be known before it runs and its interpreters can
@@ -1316,6 +2307,7 @@ of: (schema) => {
1316
2307
  * It is authority someone declared, never something derived from an Entity: an
1317
2308
  * Entity having a field does not mean anyone may set it.
1318
2309
  */
2310
+ const Computation = Data.taggedEnum();
1319
2311
  const update = (input, options) => settingSomething(declared("Update", input, options));
1320
2312
  const remove = (input, options) => {
1321
2313
  const write = declared("Delete", input, options);
@@ -1381,15 +2373,25 @@ const declared = (kind, input, options) => {
1381
2373
  case "NestedInput": fail$1(input, `"${key}" writes a nested row; a write writes its own row only`);
1382
2374
  }
1383
2375
  }
2376
+ const placeholders = Object.create(null);
2377
+ for (const [key, schema] of Object.entries(input.schema.fields)) placeholders[key] = Expr.input(key, schema);
1384
2378
  const when = Option.map(Option.fromUndefinedOr(options.when), (condition) => {
1385
- const placeholders = Object.create(null);
1386
- for (const [key, schema] of Object.entries(input.schema.fields)) placeholders[key] = Expr.input(key, schema);
1387
2379
  return Query.from(input.entity).pipe(Query.where(condition({ input: placeholders })));
1388
2380
  });
1389
2381
  const increments = Object.entries(options.increment ?? {}).flatMap(([fieldKey, key]) => key === void 0 ? [] : [incrementOf(input, fieldKey, key, {
1390
2382
  expect,
1391
2383
  sets
1392
2384
  })]);
2385
+ const fields = input.entity.fields;
2386
+ const row = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.field(field)]));
2387
+ const assignments = Object.entries(options.compute ?? {}).flatMap(([fieldKey, compute]) => compute === void 0 ? [] : [assignmentOf(input, fieldKey, () => compute({
2388
+ row,
2389
+ input: placeholders
2390
+ }), {
2391
+ expect,
2392
+ sets,
2393
+ increments
2394
+ })]);
1393
2395
  return Object.freeze({
1394
2396
  _tag: kind,
1395
2397
  input,
@@ -1401,14 +2403,102 @@ const declared = (kind, input, options) => {
1401
2403
  when,
1402
2404
  sets: Object.freeze(sets),
1403
2405
  increments: Object.freeze(increments),
2406
+ assignments: Object.freeze(assignments),
1404
2407
  links: Object.freeze(links)
1405
2408
  });
1406
2409
  };
2410
+ /** The kind of one stored form, as far as an assignment must agree with its field. */
2411
+ const storedKind = (ast) => {
2412
+ if (SchemaAST.isNull(ast)) return "null";
2413
+ const literal = SchemaAST.isLiteral(ast) ? typeof ast.literal : void 0;
2414
+ if (SchemaAST.isNumber(ast) || literal === "number") return "number";
2415
+ if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || literal === "string") return "text";
2416
+ if (SchemaAST.isBoolean(ast) || literal === "boolean") return "boolean";
2417
+ return "other";
2418
+ };
2419
+ /** Every kind a stored form may hold: a union's members' kinds. */
2420
+ const storedKinds = (ast) => new Set(SchemaAST.isUnion(ast) ? ast.types.flatMap((member) => [...storedKinds(member)]) : [storedKind(ast)]);
2421
+ /** The stored kinds a scalar may come to, by what it is. */
2422
+ const kindsOf = (expr) => {
2423
+ switch (expr._tag) {
2424
+ case "Field": return storedKinds(Schema.toEncoded(expr.schema).ast);
2425
+ case "Next": return storedKinds(Schema.toEncoded(expr.field.schema).ast);
2426
+ case "Input": return storedKinds(Schema.toEncoded(expr.schema).ast);
2427
+ case "Literal": return /* @__PURE__ */ new Set([expr.value === null ? "null" : typeof expr.value === "string" ? "text" : typeof expr.value]);
2428
+ case "Call": return storedKinds(Schema.toEncoded(expr.operator.output).ast);
2429
+ }
2430
+ };
2431
+ /**
2432
+ * Whether `expr` may come to null: a nullable field or input, a null literal,
2433
+ * an operator answering one, or a strict operator given an argument that may
2434
+ * be null, which it answers with null.
2435
+ */
2436
+ const mayBeNull = (expr) => kindsOf(expr).has("null") || expr._tag === "Call" && expr.operator.nulls === "strict" && expr.args.some((arg) => !isPredicate(arg) && mayBeNull(arg));
2437
+ /** Whether a predicate is anywhere in `expr`, which data carries only as a value. */
2438
+ const holdsPredicate = (expr) => isPredicate(expr) || expr._tag === "Call" && expr.args.some(holdsPredicate);
2439
+ /**
2440
+ * One computed field, checked: a field of the Entity written by nothing else,
2441
+ * computed from this Entity's row before the write and the input alone
2442
+ * (never `Next`, so assignments do not depend on each other), to a value of
2443
+ * the field's stored kind, with no predicate in it.
2444
+ */
2445
+ const assignmentOf = (input, fieldKey, compute, declared) => {
2446
+ const fields = input.entity.fields;
2447
+ const field = Object.hasOwn(fields, fieldKey) ? fields[fieldKey] : void 0;
2448
+ if (field === void 0) return fail$1(input, `computes "${fieldKey}", which is not a field`);
2449
+ if (fieldKey === "id") return fail$1(input, "computes the id");
2450
+ if (declared.expect?.field.key === fieldKey) return fail$1(input, `computes "${fieldKey}", the revision it expects`);
2451
+ if (declared.sets.some((set) => set.field.key === fieldKey) || declared.increments.some((increment) => increment.field.key === fieldKey)) return fail$1(input, `computes "${fieldKey}", which the write also sets`);
2452
+ const operand = compute();
2453
+ const expr = isPredicate(operand) ? operand : Expr.expanded(operand);
2454
+ if (isPredicate(expr) || holdsPredicate(expr)) return fail$1(input, `computes "${fieldKey}" with a predicate, which an assignment carries only as a value`);
2455
+ const reads = dependenciesOf(expr);
2456
+ if (reads.next.length > 0) return fail$1(input, `computes "${fieldKey}" from the row after the write, which an assignment never reads`);
2457
+ const stranger = reads.fields.find((read) => read.owner.name !== input.entity.name);
2458
+ if (stranger !== void 0) return fail$1(input, `computes "${fieldKey}" from ${stranger.owner.name}.${stranger.key}, another Entity's field`);
2459
+ const stored = storedKinds(Schema.toEncoded(field.schema).ast);
2460
+ const comes = [...kindsOf(expr)].filter((kind) => kind !== "null" && !stored.has(kind));
2461
+ if (comes.length > 0) return fail$1(input, `computes "${fieldKey}" as ${comes.join(" or ")}, which it does not store`);
2462
+ if (!stored.has("null") && mayBeNull(expr)) return fail$1(input, `computes "${fieldKey}" as possibly null, which it does not store`);
2463
+ return Object.freeze({
2464
+ field,
2465
+ expr
2466
+ });
2467
+ };
2468
+ /** An assignment's expression, bound to one input, as data. */
2469
+ const computationOf = (write, expr, input) => {
2470
+ switch (expr._tag) {
2471
+ case "Field":
2472
+ case "Next": return Computation.Field({ key: expr._tag === "Field" ? expr.key : expr.field.key });
2473
+ case "Literal": return Computation.Value({ value: expr.value });
2474
+ case "Input": return Computation.Value({ value: Schema.encodeUnknownSync(write.input.schema.fields[expr.key])(input[expr.key]) });
2475
+ case "Call": return Computation.Call({
2476
+ operator: expr.operator.version === 1 ? expr.operator.id : `${expr.operator.id}@${expr.operator.version}`,
2477
+ args: expr.args.map((arg) => computationOf(write, arg, input)),
2478
+ collation: Option.getOrNull(expr.collation)
2479
+ });
2480
+ }
2481
+ };
2482
+ /**
2483
+ * What a computation comes to over `row`, the row before the write: none when
2484
+ * the row lacks a field it reads, or `operators` lacks an operator it calls.
2485
+ */
2486
+ const computed = (computation, row, operators) => Computation.$match(computation, {
2487
+ Field: ({ key }) => Object.hasOwn(row, key) ? Option.some(row[key]) : Option.none(),
2488
+ Value: ({ value }) => Option.some(value),
2489
+ Call: ({ operator, args, collation }) => Option.flatMap(operators.named(operator), (descriptor) => Option.map(Option.all(args.map((arg) => computed(arg, row, operators))), (values) => applyOperator(descriptor, values, {
2490
+ collation: Option.fromNullOr(collation),
2491
+ operators
2492
+ })))
2493
+ });
1407
2494
  /** Whether a value's stored form is a plain number. */
1408
2495
  const storedAsNumber = (schema) => SchemaAST.isNumber(Schema.toEncoded(schema).ast);
2496
+ /** Whether a value's stored form is checked to be an integer. */
2497
+ const storedAsInteger = (schema) => SchemaShape.holdsIntegers(Schema.toEncoded(schema).ast);
1409
2498
  /**
1410
2499
  * One increment, checked: a field of the Entity stored as a number, written
1411
- * by nothing else, moved by an unmapped input key whose value is a number.
2500
+ * by nothing else, moved by an unmapped input key whose value is a number, and
2501
+ * an integer when the field is one.
1412
2502
  */
1413
2503
  const incrementOf = (input, fieldKey, key, declared) => {
1414
2504
  const fields = input.entity.fields;
@@ -1423,13 +2513,16 @@ const incrementOf = (input, fieldKey, key, declared) => {
1423
2513
  if (member._tag !== "Unmapped") return fail$1(input, `"${key}" is an amount, so it must be unmapped, not written as a member`);
1424
2514
  const amount = input.schema.fields[key];
1425
2515
  if (!storedAsNumber(amount)) return fail$1(input, `"${key}" is an amount, but not a number`);
2516
+ const integer = storedAsInteger(amount);
2517
+ if (storedAsInteger(field.schema) && !integer) return fail$1(input, `"${key}" may not be an integer, but "${fieldKey}" is one; give the amount Schema.Int`);
1426
2518
  return Object.freeze({
1427
2519
  key,
1428
- field
2520
+ field,
2521
+ integer
1429
2522
  });
1430
2523
  };
1431
2524
  /** An update or an insert that would write nothing is refused where it is declared. */
1432
- const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 && write.increments.length === 0 ? fail$1(write.input, "it sets no field") : write;
2525
+ const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 && write.increments.length === 0 && write.assignments.length === 0 ? fail$1(write.input, "it sets no field") : write;
1433
2526
  const Write = {
1434
2527
  /**
1435
2528
  * Sets, on the row whose id is the input's `id` key, every field the input
@@ -1448,6 +2541,12 @@ const Write = {
1448
2541
  * `when` is what the row must hold for the update to land, checked where it
1449
2542
  * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
1450
2543
  * does not hold of is refused as unmet.
2544
+ *
2545
+ * `compute` sets a field to what an expression comes to over the row before
2546
+ * the write and the input, run where it commits
2547
+ * (`{ label: ({ row }) => concat(row.title, ' draft') }`). It is refused for
2548
+ * a field another key writes, an expression over the row after the write or
2549
+ * another Entity, or one of a kind the field does not store.
1451
2550
  */
1452
2551
  update,
1453
2552
  /**
@@ -1479,18 +2578,21 @@ const Write = {
1479
2578
  writes: (write) => [
1480
2579
  ...write.sets.map((set) => set.field),
1481
2580
  ...write.increments.map((increment) => increment.field),
2581
+ ...write.assignments.map((assignment) => assignment.field),
1482
2582
  ...write.links.map((link) => link.relation)
1483
2583
  ],
1484
2584
  /**
1485
2585
  * The fields a write reads from the row it writes: those its `when` reads,
1486
- * each it increments, and the revision it expects. What an interpreter
1487
- * must read, and what a startup check judges it could disclose.
2586
+ * each it increments, each its assignments read, and the revision it
2587
+ * expects. What an interpreter must read, and what a startup check judges
2588
+ * it could disclose.
1488
2589
  */
1489
2590
  reads: (write) => {
1490
2591
  const fields = /* @__PURE__ */ new Map();
1491
2592
  const add = (field) => fields.set(field.key, field);
1492
2593
  Option.map(write.when, (body) => Query.dependencies(body).predicate.forEach((field) => add(field)));
1493
2594
  write.increments.forEach((increment) => add(increment.field));
2595
+ write.assignments.forEach((assignment) => dependenciesOf(assignment.expr).fields.forEach((field) => add(field)));
1494
2596
  if (write.expect !== void 0) add(write.expect.field);
1495
2597
  return [...fields.values()];
1496
2598
  },
@@ -1528,17 +2630,65 @@ const Write = {
1528
2630
  increments[field.key] = Schema.encodeUnknownSync(schema)(held);
1529
2631
  });
1530
2632
  }
2633
+ const assignments = {};
2634
+ for (const { field, expr } of write.assignments) assignments[field.key] = computationOf(write, expr, input);
1531
2635
  return {
1532
2636
  entity: write.input.entity.name,
1533
2637
  id: String(encoded(write.id.field, input[write.id.key])),
1534
2638
  values,
1535
2639
  links,
1536
- increments
2640
+ increments,
2641
+ assignments
2642
+ };
2643
+ },
2644
+ /**
2645
+ * The fields of the row before it that a bound write's amounts and
2646
+ * assignments read: what to read to work out the row it leaves.
2647
+ */
2648
+ boundReads: (bound) => {
2649
+ const keys = new Set(Object.keys(bound.increments));
2650
+ const walk = (computation) => Computation.$match(computation, {
2651
+ Field: ({ key }) => void keys.add(key),
2652
+ Value: () => void 0,
2653
+ Call: ({ args }) => args.forEach(walk)
2654
+ });
2655
+ Object.values(bound.assignments).forEach(walk);
2656
+ return [...keys];
2657
+ },
2658
+ /**
2659
+ * The row a bound write leaves over `row`, the row before it: its values
2660
+ * set, each amount added (a null stays null, as in SQL), and each
2661
+ * assignment computed by `operators` over the row before. `unknown` names
2662
+ * each field it could not work out: one `row` lacks, or holds as no number
2663
+ * for an amount, or an assignment calling an operator the table lacks. That
2664
+ * field keeps what `row` holds. The one computation of this row: a guard
2665
+ * judges it, a writer explains a miss with it, a client predicts it.
2666
+ */
2667
+ apply: (row, bound, options) => {
2668
+ const after = {
2669
+ ...row,
2670
+ ...bound.values
2671
+ };
2672
+ const unknown = [];
2673
+ for (const [field, amount] of Object.entries(bound.increments)) {
2674
+ const held = Object.hasOwn(row, field) ? row[field] : void 0;
2675
+ if (held === null) after[field] = null;
2676
+ else if (typeof held === "number") after[field] = held + amount;
2677
+ else unknown.push(field);
2678
+ }
2679
+ for (const [field, computation] of Object.entries(bound.assignments)) Option.match(computed(computation, row, options.operators), {
2680
+ onNone: () => unknown.push(field),
2681
+ onSome: (value) => {
2682
+ after[field] = value;
2683
+ }
2684
+ });
2685
+ return {
2686
+ row: after,
2687
+ unknown
1537
2688
  };
1538
2689
  }
1539
2690
  };
1540
- //#endregion
1541
- //#region src/index.ts
2691
+ // src/index.ts
1542
2692
  /**
1543
2693
  * `foldkit-entity` — domain structure as typed values.
1544
2694
  *
@@ -1906,7 +3056,6 @@ const Relation = {
1906
3056
  })
1907
3057
  };
1908
3058
  const Derived = { make: (schema) => ({ schema }) };
1909
- //#endregion
1910
- export { maxQueryNodes as C, isPredicate as S, truthOver as _, SelectionPageTypeId as a, Query as b, Words as c, QueryEvaluateError as d, assertSupported as f, supported as g, evaluate as h, Relation as i, ReadFilter as l, decided as m, Entity as n, SelectionTypeId as o, compareRows as p, EntityTypeId as r, Write as s, Derived as t, SchemaShape as u, Expr as v, Collation as w, dependenciesOf as x, Order as y };
3059
+ export { Query as A, OperatorDescription as C, stampTested as D, stampRun as E, noOperators as F, Law as I, LawDescription as L, isPredicate as M, maxQueryNodes as N, Expr as O, missingName as P, SchemaShape as R, Evidence as S, Text as T, evaluate as _, SelectionPageTypeId as a, truthOver as b, Write as c, OperatorMissingError as d, QueryEvaluateError as f, decided as g, compareRows as h, Relation as i, dependenciesOf as j, Order as k, Words as l, assertSupported as m, Entity as n, SelectionTypeId as o, applyOperator as p, EntityTypeId as r, Computation as s, Derived as t, ReadFilter as u, evaluateEach as v, Operators as w, valueOfOperand as x, supported as y, Collation as z };
1911
3060
 
1912
- //# sourceMappingURL=src-DwKdHZDu.mjs.map
3061
+ //# sourceMappingURL=src-DBAilaDV.mjs.map