foldkit-entity 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +962 -512
  2. package/dist/collation.d.ts +33 -0
  3. package/dist/collation.d.ts.map +1 -0
  4. package/dist/collation.js +46 -0
  5. package/dist/collation.js.map +1 -0
  6. package/dist/conformance/index.d.ts +66 -0
  7. package/dist/conformance/index.d.ts.map +1 -0
  8. package/dist/conformance/{index.mjs → index.js} +22 -360
  9. package/dist/conformance/index.js.map +1 -0
  10. package/dist/conformance/operator.d.ts +115 -0
  11. package/dist/conformance/operator.d.ts.map +1 -0
  12. package/dist/conformance/operator.js +354 -0
  13. package/dist/conformance/operator.js.map +1 -0
  14. package/dist/conformance/relational.d.ts +240 -0
  15. package/dist/conformance/relational.d.ts.map +1 -0
  16. package/dist/conformance/relational.js +425 -0
  17. package/dist/conformance/relational.js.map +1 -0
  18. package/dist/conformance/tuples.d.ts +8 -0
  19. package/dist/conformance/tuples.d.ts.map +1 -0
  20. package/dist/conformance/tuples.js +43 -0
  21. package/dist/conformance/tuples.js.map +1 -0
  22. package/dist/conformance/variants.d.ts +47 -0
  23. package/dist/conformance/variants.d.ts.map +1 -0
  24. package/dist/conformance/variants.js +126 -0
  25. package/dist/conformance/variants.js.map +1 -0
  26. package/dist/context.d.ts +60 -0
  27. package/dist/context.d.ts.map +1 -0
  28. package/dist/context.js +36 -0
  29. package/dist/context.js.map +1 -0
  30. package/dist/descriptor.d.ts +33 -0
  31. package/dist/descriptor.d.ts.map +1 -0
  32. package/dist/descriptor.js +137 -0
  33. package/dist/descriptor.js.map +1 -0
  34. package/dist/entity.d.ts +231 -0
  35. package/dist/entity.d.ts.map +1 -0
  36. package/dist/entity.js +435 -0
  37. package/dist/entity.js.map +1 -0
  38. package/dist/evaluate.d.ts +204 -0
  39. package/dist/evaluate.d.ts.map +1 -0
  40. package/dist/evaluate.js +765 -0
  41. package/dist/evaluate.js.map +1 -0
  42. package/dist/expr.d.ts +915 -0
  43. package/dist/expr.d.ts.map +1 -0
  44. package/dist/expr.js +1630 -0
  45. package/dist/expr.js.map +1 -0
  46. package/dist/held.d.ts +112 -0
  47. package/dist/held.d.ts.map +1 -0
  48. package/dist/held.js +155 -0
  49. package/dist/held.js.map +1 -0
  50. package/dist/ids.d.ts +8 -0
  51. package/dist/ids.d.ts.map +1 -0
  52. package/dist/ids.js +8 -0
  53. package/dist/ids.js.map +1 -0
  54. package/dist/index.d.ts +380 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.js +110 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/invariant.d.ts +123 -0
  59. package/dist/invariant.d.ts.map +1 -0
  60. package/dist/invariant.js +236 -0
  61. package/dist/invariant.js.map +1 -0
  62. package/dist/jsonSchema.d.ts +3 -0
  63. package/dist/jsonSchema.d.ts.map +1 -0
  64. package/dist/jsonSchema.js +17 -0
  65. package/dist/jsonSchema.js.map +1 -0
  66. package/dist/law.d.ts +264 -0
  67. package/dist/law.d.ts.map +1 -0
  68. package/dist/law.js +111 -0
  69. package/dist/law.js.map +1 -0
  70. package/dist/operators.d.ts +170 -0
  71. package/dist/operators.d.ts.map +1 -0
  72. package/dist/operators.js +207 -0
  73. package/dist/operators.js.map +1 -0
  74. package/dist/readFilter.d.ts +8 -0
  75. package/dist/readFilter.d.ts.map +1 -0
  76. package/dist/readFilter.js +23 -0
  77. package/dist/readFilter.js.map +1 -0
  78. package/dist/record.d.ts +11 -0
  79. package/dist/record.d.ts.map +1 -0
  80. package/dist/record.js +21 -0
  81. package/dist/record.js.map +1 -0
  82. package/dist/sets.d.ts +18 -0
  83. package/dist/sets.d.ts.map +1 -0
  84. package/dist/sets.js +57 -0
  85. package/dist/sets.js.map +1 -0
  86. package/dist/shape.d.ts +23 -0
  87. package/dist/shape.d.ts.map +1 -0
  88. package/dist/shape.js +30 -0
  89. package/dist/shape.js.map +1 -0
  90. package/dist/tested.d.ts +8 -0
  91. package/dist/tested.d.ts.map +1 -0
  92. package/dist/tested.js +25 -0
  93. package/dist/tested.js.map +1 -0
  94. package/dist/text.d.ts +27 -0
  95. package/dist/text.d.ts.map +1 -0
  96. package/dist/text.js +39 -0
  97. package/dist/text.js.map +1 -0
  98. package/dist/variants.d.ts +72 -0
  99. package/dist/variants.d.ts.map +1 -0
  100. package/dist/variants.js +76 -0
  101. package/dist/variants.js.map +1 -0
  102. package/dist/words.d.ts +17 -0
  103. package/dist/words.d.ts.map +1 -0
  104. package/dist/words.js +22 -0
  105. package/dist/words.js.map +1 -0
  106. package/dist/write.d.ts +312 -0
  107. package/dist/write.d.ts.map +1 -0
  108. package/dist/write.js +520 -0
  109. package/dist/write.js.map +1 -0
  110. package/package.json +8 -8
  111. package/dist/conformance/index.d.mts +0 -274
  112. package/dist/conformance/index.d.mts.map +0 -1
  113. package/dist/conformance/index.mjs.map +0 -1
  114. package/dist/index-hu8IYlNc.d.mts +0 -2228
  115. package/dist/index-hu8IYlNc.d.mts.map +0 -1
  116. package/dist/index.d.mts +0 -2
  117. package/dist/index.mjs +0 -1
  118. package/dist/src-DBAilaDV.mjs +0 -3061
  119. package/dist/src-DBAilaDV.mjs.map +0 -1
package/dist/expr.js ADDED
@@ -0,0 +1,1630 @@
1
+ import { Array as Array$1, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
2
+ import { own, put } from "./record.js";
3
+ import { variantsOf } from "./variants.js";
4
+ import { SchemaShape } from "./shape.js";
5
+ import { absurd } from "effect/Function";
6
+ import { Collation } from "./collation.js";
7
+ import { now, viewer } from "./context.js";
8
+ import { Law } from "./law.js";
9
+ // src/expr.ts
10
+ /**
11
+ * `Expr` — a query's scalar computations as typed values.
12
+ *
13
+ * An Entity says what a domain has; an `Expr` says something about one row of
14
+ * it. A field reference, an input placeholder, a literal, and comparisons of
15
+ * those are all immutable data: building one performs no work, reads nothing,
16
+ * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`
17
+ * to SQL, an in-memory evaluator to a predicate over rows.
18
+ *
19
+ * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every
20
+ * operation here is one a real query in this repository needs; the set grows
21
+ * from queries, not from what a database could express.
22
+ */
23
+ /** A table implementing nothing: every primitive operator is unsupported by it. */
24
+ const noOperators = Object.freeze({
25
+ has: () => false,
26
+ versions: () => []
27
+ });
28
+ /**
29
+ * An operator `operators` does not implement, by name, with the versions of it
30
+ * the table does implement: `acme.slug@2 (this table has acme.slug)`.
31
+ */
32
+ const missingName = (operator, operators) => {
33
+ const held = operators.versions(operator.id);
34
+ if (held.includes(operator.version)) return `${operatorName(operator)} (this table has another declaration of it; declare an operator once and import it)`;
35
+ return held.length === 0 ? operatorName(operator) : `${operatorName(operator)} (this table has ${held.map((version) => operatorName({
36
+ ...operator,
37
+ version
38
+ })).join(", ")})`;
39
+ };
40
+ const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
41
+ /**
42
+ * An Entity's field and a `FieldExpr` are the same three members under the same
43
+ * tag — the Entity's carries `metadata` besides — so this reads either and is
44
+ * idempotent on its own output. Nothing needs to tell them apart, which is
45
+ * better than telling them apart by which extra member happens to be present.
46
+ */
47
+ /**
48
+ * Every node is frozen as it is made, so a query built from it stays the value
49
+ * it was when `Query.where` checked it: nothing can swap a field or a literal
50
+ * in afterwards. It also means no node can come to contain itself. A literal's
51
+ * own payload is the caller's; the kernel compares scalars.
52
+ */
53
+ const node = (value) => Object.freeze(value);
54
+ const literal = (value) => node({
55
+ _tag: "Literal",
56
+ value
57
+ });
58
+ const fieldExpr = (field) => node({
59
+ _tag: "Field",
60
+ owner: field.owner,
61
+ key: field.key,
62
+ schema: field.schema,
63
+ collation: Option.orElse(Collation.declared(field.metadata), () => field.key === "id" ? Option.some(Collation.binary) : Option.none())
64
+ });
65
+ /**
66
+ * A `one` relation read as a value: the id of the row it points at, null for
67
+ * none. It is the member the row holds under the relation's key, so it is a
68
+ * field of the owner to every interpreter: a row given to one holds it as that
69
+ * id, and SQL reads the column the relation is stored on.
70
+ */
71
+ const linkExpr = (relation) => node({
72
+ _tag: "Field",
73
+ owner: relation.owner,
74
+ key: relation.key,
75
+ schema: relation.optional ? Schema.NullOr(Schema.String) : Schema.String,
76
+ collation: Option.none()
77
+ });
78
+ const predicateTags = /* @__PURE__ */ new Set([
79
+ "Eq",
80
+ "Null",
81
+ "Contains",
82
+ "In",
83
+ "And",
84
+ "Or",
85
+ "Not",
86
+ "Compare",
87
+ "Test",
88
+ "Exists"
89
+ ]);
90
+ /** Whether a value is a predicate, and so usable where a boolean is wanted. */
91
+ const isPredicate = (value) => predicateTags.has(tagOf(value));
92
+ /**
93
+ * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is
94
+ * itself, and anything else is the constant it is.
95
+ */
96
+ const toOperand = (value) => {
97
+ const tag = tagOf(value);
98
+ if (tag === "Field" && !Object.hasOwn(value, "metadata")) return value;
99
+ if (tag === "Field") return fieldExpr(value);
100
+ if (tag === "Relation") {
101
+ const relation = value;
102
+ if (relation.cardinality !== "one") throw new Error(`[foldkit-entity] ${relation.owner.name}.${relation.key} is a many relation, which holds no one value; ask Expr.exists of the relation that points back`);
103
+ return linkExpr(relation);
104
+ }
105
+ if (tag === "Literal" || tag === "Input" || tag === "Next" || tag === "Call" || tag === "Viewer" || tag === "Now" || tag === "Path" || tag === "ViewerPath" || predicateTags.has(tag)) return value;
106
+ return literal(value);
107
+ };
108
+ /** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
109
+ const toExpr = (value, step) => {
110
+ const operand = toOperand(value);
111
+ if (isPredicate(operand)) throw new Error(`[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`);
112
+ return operand;
113
+ };
114
+ /** How values encoded by `ast` order: as numbers, as text, or not at all. */
115
+ const orderKindOf = (ast) => {
116
+ if (SchemaAST.isNumber(ast)) return "number";
117
+ if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return "text";
118
+ if (SchemaAST.isLiteral(ast)) {
119
+ if (typeof ast.literal === "number") return "number";
120
+ if (typeof ast.literal === "string") return "text";
121
+ return "none";
122
+ }
123
+ if (SchemaAST.isUnion(ast)) {
124
+ const kinds = new Set(ast.types.filter((member) => !SchemaAST.isNull(member)).map(orderKindOf));
125
+ const [only] = kinds;
126
+ return kinds.size === 1 && only !== void 0 ? only : "none";
127
+ }
128
+ return "none";
129
+ };
130
+ /** How a literal orders; a null orders as anything, since comparing it is unknown. */
131
+ const literalKind = (value) => {
132
+ if (value === null) return "null";
133
+ if (typeof value === "number") return "number";
134
+ if (typeof value === "string") return "text";
135
+ return "none";
136
+ };
137
+ /** How a side orders, read from its encoded form. */
138
+ const sideKind = (side) => Match.value(side).pipe(Match.tagsExhaustive({
139
+ Field: (field) => orderKindOf(Schema.toEncoded(field.schema).ast),
140
+ Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),
141
+ Input: (input) => orderKindOf(Schema.toEncoded(input.schema).ast),
142
+ Literal: ({ value }) => literalKind(value),
143
+ Call: ({ operator }) => orderKindOf(Schema.toEncoded(operator.output).ast),
144
+ Viewer: ({ schema }) => orderKindOf(Schema.toEncoded(schema).ast),
145
+ Now: ({ schema }) => orderKindOf(Schema.toEncoded(schema).ast),
146
+ Path: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),
147
+ ViewerPath: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast)
148
+ }));
149
+ /**
150
+ * How a comparison's text compares: the collation given, else the field's
151
+ * declared one. Text orders differently by backend (SQLite's `BINARY`, the
152
+ * Postgres database's locale, JavaScript's UTF-16 units), so it is compared
153
+ * only under `binary` or `asciiFold`, which every interpreter here agrees on,
154
+ * and only against a field, whose collation it is. Values that order
155
+ * intrinsically, numbers, need none.
156
+ */
157
+ const collationFor = (step, left, right, given) => {
158
+ const kinds = new Set([sideKind(left), sideKind(right)].filter((kind) => kind !== "null"));
159
+ 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`);
160
+ if (!kinds.has("text")) return Option.none();
161
+ const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tagsExhaustive({
162
+ Field: (field) => [{
163
+ name: `${field.owner.name}.${field.key}`,
164
+ collation: field.collation
165
+ }],
166
+ Next: ({ field }) => [{
167
+ name: `${field.owner.name}.${field.key}`,
168
+ collation: field.collation
169
+ }],
170
+ Call: (call) => [{
171
+ name: showExpr(call),
172
+ collation: call.collation
173
+ }],
174
+ Path: (path) => [{
175
+ name: showExpr(path),
176
+ collation: path.field.collation
177
+ }],
178
+ ViewerPath: (path) => [{
179
+ name: showExpr(path),
180
+ collation: path.field.collation
181
+ }],
182
+ Literal: () => [],
183
+ Input: () => [],
184
+ Viewer: () => [],
185
+ Now: () => []
186
+ })));
187
+ const [first] = fields;
188
+ 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`);
189
+ const named = fields.map((field) => field.name).join(" and ");
190
+ const collations = Option.match(given, {
191
+ onSome: (collation) => [collation],
192
+ onNone: () => fields.map((field) => Option.getOrElse(field.collation, () => {
193
+ 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`);
194
+ }))
195
+ });
196
+ const [collation] = collations;
197
+ if (collation === void 0 || collations.some((each) => each._tag !== collation._tag)) throw new Error(`[foldkit-entity] Expr.${step}: ${named} declare different collations; pass one to compare them by`);
198
+ return Match.value(collation).pipe(Match.tagsExhaustive({
199
+ Binary: () => Option.some(collation),
200
+ AsciiFold: () => Option.some(collation),
201
+ Locale: ({ locale }) => {
202
+ throw new Error(`[foldkit-entity] Expr.${step}: ${named} compares by the backend's "${locale}" collation, which only that backend has`);
203
+ }
204
+ }));
205
+ };
206
+ /** `Expr.lt` and its three siblings: the operator fixed, the sides typed alike. */
207
+ const comparison = (operator) => (left, right, options = {}) => {
208
+ const leftSide = toExpr(left, operator);
209
+ const rightSide = toExpr(right, operator);
210
+ return node({
211
+ _tag: "Compare",
212
+ operator,
213
+ left: leftSide,
214
+ right: rightSide,
215
+ collation: collationFor(operator, leftSide, rightSide, Option.fromUndefinedOr(options.collation))
216
+ });
217
+ };
218
+ /** A connective's operands, each checked to be a predicate, with one of the same kind flattened in. */
219
+ const connected = (step, kind, given) => {
220
+ const operands = given.flatMap((operand) => {
221
+ if (!isPredicate(operand)) throw new Error(`[foldkit-entity] Expr.${step}: every operand is a predicate; compare a value with Expr.eq first`);
222
+ return Match.value(operand).pipe(Match.tags({
223
+ And: (and) => kind === "And" ? and.operands : [and],
224
+ Or: (or) => kind === "Or" ? or.operands : [or]
225
+ }), Match.orElse(() => [operand]));
226
+ });
227
+ if (operands.length > 1e3) throw new Error(`[foldkit-entity] Expr.${step}: more than ${maxQueryNodes} operands, the most a query's predicates may hold`);
228
+ if (!Array$1.isReadonlyArrayNonEmpty(operands)) throw new Error(`[foldkit-entity] Expr.${step}: no operands, which would match ${step === "and" ? "every row" : "no row"}; check a list is non-empty before spreading it`);
229
+ return operands;
230
+ };
231
+ const connective = (step, kind) => (...given) => {
232
+ const operands = connected(step, kind, given);
233
+ return operands.length === 1 ? operands[0] : node({
234
+ _tag: kind,
235
+ operands
236
+ });
237
+ };
238
+ const collationTags = /* @__PURE__ */ new Set([
239
+ "Binary",
240
+ "AsciiFold",
241
+ "Locale"
242
+ ]);
243
+ /** A call's last value, when it is one past the arguments: its options, checked. */
244
+ const callOptionsOf = (id, value) => {
245
+ const collation = typeof value === "object" && value !== null && Object.hasOwn(value, "collation") ? value.collation : void 0;
246
+ if (!collationTags.has(tagOf(collation))) throw new Error(`[foldkit-entity] ${id}: a value past its arguments is \`{ collation }\`, a Collation`);
247
+ return collation;
248
+ };
249
+ /** A collation a call was given: one its operator compares by, and portable where required. */
250
+ const givenCollation = (id, descriptor, collation) => {
251
+ if (Option.isSome(descriptor.definedAs) || descriptor.collation === "none") throw new Error(`[foldkit-entity] ${id}: takes no collation; it compares no text of its own`);
252
+ if (collation._tag === "Locale") throw new Error(`[foldkit-entity] ${id}: compares by the backend's "${collation.locale}" collation, which only that backend has`);
253
+ return Option.some(collation);
254
+ };
255
+ /** Namespaced, lower camel case: `cms.published`, `text.startsWith`. */
256
+ const operatorId = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
257
+ /**
258
+ * Why `law` cannot be declared of an operator of this shape, if it cannot: an
259
+ * equation over two arguments of a unary operator, a witness that does not
260
+ * decode as the argument it stands in, or a collation law of an operator
261
+ * whose text keeps none.
262
+ */
263
+ const lawProblem = (law, input, output, collation) => {
264
+ const name = Law.describe(law).kind;
265
+ 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}`);
266
+ 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`);
267
+ 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")));
268
+ return Law.$match(law, {
269
+ Associative: binary,
270
+ Commutative: binary,
271
+ Idempotent: binary,
272
+ Identity: ({ value, side }) => sides(value, side),
273
+ Absorbing: ({ value, side }) => sides(value, side),
274
+ Inverse: ({ other, identity }) => Option.orElse(binary(), () => other.descriptor.input.length === 1 ? decodes(identity, output, "identity") : Option.some(`${name}'s other operator takes one argument`)),
275
+ Distributes: ({ over }) => Option.orElse(binary(), () => over.descriptor.input.length === 2 ? Option.none() : Option.some(`${name} is over an operator of two arguments`)),
276
+ Monotonic: ({ position }) => Number.isSafeInteger(position) && position >= 0 && position < input.length ? Option.none() : Option.some(`${name}'s position ${position} is not an argument's`),
277
+ PreservesCollation: () => collation === "operands" ? Option.none() : Option.some(`${name} is a law of an operator declared \`collation: 'operands'\``)
278
+ });
279
+ };
280
+ /** Whether a schema's stored form is a boolean, which makes its operator a predicate. */
281
+ const storedAsBoolean = (schema) => SchemaAST.isBoolean(Schema.toEncoded(schema).ast);
282
+ /** What a schema stores, null aside: one kind an argument is checked by, or `other`. */
283
+ const storedKindOf = (schema) => {
284
+ const present = SchemaShape.present(Schema.toEncoded(schema).ast);
285
+ if (present.length === 0) return "other";
286
+ if (present.every(SchemaAST.isNumber)) return "number";
287
+ if (present.every(SchemaShape.isText)) return "text";
288
+ if (present.every(SchemaAST.isBoolean)) return "boolean";
289
+ return "other";
290
+ };
291
+ /** The schema a scalar's values are stored by. */
292
+ const scalarSchema = (scalar) => Match.value(scalar).pipe(Match.tagsExhaustive({
293
+ Field: (field) => field.schema,
294
+ Next: ({ field }) => field.schema,
295
+ Input: (input) => input.schema,
296
+ Literal: () => Schema.Unknown,
297
+ Call: ({ operator }) => operator.output,
298
+ Viewer: ({ schema }) => schema,
299
+ Now: ({ schema }) => schema,
300
+ Path: ({ field }) => field.schema,
301
+ ViewerPath: ({ field }) => field.schema
302
+ }));
303
+ /** Every field, field after a write, and input an expression reads, as keys to compare. */
304
+ const readKeys = (...nodes) => {
305
+ const read = dependenciesOf(...nodes);
306
+ const named = (prefix, fields) => fields.map((field) => `${prefix}${field.entity}.${field.key}`);
307
+ return /* @__PURE__ */ new Set([
308
+ ...named("", read.fields),
309
+ ...named("next ", read.next),
310
+ ...read.inputs.map((key) => `$${key}`)
311
+ ]);
312
+ };
313
+ /** One argument, checked against the schema it is passed for, as a node. */
314
+ const argumentFor = (id, position, schema, value) => {
315
+ const arg = toOperand(value);
316
+ const fail = (what) => {
317
+ throw new Error(`[foldkit-entity] ${id}: argument ${position + 1} ${what}`);
318
+ };
319
+ if (isPredicate(arg)) {
320
+ const stored = Schema.is(Schema.toEncoded(schema));
321
+ if (!stored(true) || !stored(false)) fail("is a predicate, but the operator does not take a boolean");
322
+ return arg;
323
+ }
324
+ if (arg._tag === "Literal") {
325
+ if (!Schema.is(Schema.toEncoded(schema))(arg.value)) fail(`is ${JSON.stringify(arg.value)}, which the operator's input schema does not admit`);
326
+ return arg;
327
+ }
328
+ const wanted = storedKindOf(schema);
329
+ const given = storedKindOf(scalarSchema(arg));
330
+ if (wanted !== "other" && given !== "other" && given !== wanted) fail(`is stored as ${given}, but the operator takes ${wanted}`);
331
+ return arg;
332
+ };
333
+ /** A scalar's collation: a field's declared one, or a call's. */
334
+ const collationOf = (scalar) => Match.value(scalar).pipe(Match.tagsExhaustive({
335
+ Field: (field) => field.collation,
336
+ Next: ({ field }) => field.collation,
337
+ Call: (call) => call.collation,
338
+ Literal: () => Option.none(),
339
+ Input: () => Option.none(),
340
+ Viewer: () => Option.none(),
341
+ Now: () => Option.none(),
342
+ Path: ({ field }) => field.collation,
343
+ ViewerPath: ({ field }) => field.collation
344
+ }));
345
+ /**
346
+ * The collation a primitive call compares text under: the one its collated
347
+ * text arguments share. A literal or an input carries none and does not vote.
348
+ * `required` refuses a call with none, or with a backend's locale.
349
+ */
350
+ const callCollation = (id, rule, args) => {
351
+ if (rule === "none") return Option.none();
352
+ const fail = (what) => {
353
+ throw new Error(`[foldkit-entity] ${id}: ${what}`);
354
+ };
355
+ const voters = args.flatMap((arg) => isPredicate(arg) || arg._tag === "Literal" || arg._tag === "Input" || sideKind(arg) !== "text" ? [] : [{
356
+ arg,
357
+ collation: collationOf(arg)
358
+ }]);
359
+ const collations = voters.flatMap(({ arg, collation }) => Option.match(collation, {
360
+ onSome: (each) => [each],
361
+ 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`) : []
362
+ }));
363
+ const [shared] = collations;
364
+ if (shared === void 0) return rule === "required" ? fail("compares text with no field or call holding a collation") : Option.none();
365
+ if (collations.some((each) => each._tag !== shared._tag)) fail(`${voters.map((voter) => showExpr(voter.arg)).join(" and ")} declare different collations`);
366
+ if (shared._tag === "Locale") fail(`compares by the backend's "${shared.locale}" collation, which a call cannot carry`);
367
+ return Option.some(shared);
368
+ };
369
+ /** Builds an operator: checks what it is given once, then each call. */
370
+ const makeOperator = (id, options) => {
371
+ const fail = (what) => {
372
+ throw new Error(`[foldkit-entity] Expr.operator("${id}"): ${what}`);
373
+ };
374
+ if (!operatorId.test(id)) fail("an id is namespaced lower camel case, as `cms.published`");
375
+ if (id.startsWith("foldkit.")) fail("ids under `foldkit.` are reserved");
376
+ const version = options.version ?? 1;
377
+ if (!Number.isSafeInteger(version) || version < 1) fail("a version is a positive integer");
378
+ if (!Array.isArray(options.input) || !options.input.every(Schema.isSchema)) fail("`input` is one schema per argument");
379
+ if (!Schema.isSchema(options.output)) fail("`output` is a schema");
380
+ const definedAs = Option.fromUndefinedOr(options.definedAs);
381
+ if (Option.isSome(definedAs) && typeof definedAs.value !== "function") fail("`definedAs` builds what a call means");
382
+ 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");
383
+ const nulls = options.nulls ?? "strict";
384
+ const collation = options.collation ?? "none";
385
+ if (nulls !== "strict" && nulls !== "handled") fail("`nulls` is 'strict' or 'handled'");
386
+ if (collation !== "none" && collation !== "operands" && collation !== "required") fail("`collation` is 'none', 'operands' or 'required'");
387
+ const input = Object.freeze([...options.input]);
388
+ const predicate = storedAsBoolean(options.output);
389
+ if (collation === "operands" && orderKindOf(Schema.toEncoded(options.output).ast) !== "text") fail("`collation: 'operands'` describes a text result, and this one is not text");
390
+ const laws = Object.freeze([...options.laws ?? []]);
391
+ for (const law of laws) Option.match(lawProblem(law, input, options.output, collation), {
392
+ onNone: () => void 0,
393
+ onSome: fail
394
+ });
395
+ const descriptor = Object.freeze({
396
+ _tag: "Operator",
397
+ id,
398
+ version,
399
+ description: Option.fromUndefinedOr(options.description),
400
+ input,
401
+ output: options.output,
402
+ definedAs,
403
+ nulls,
404
+ collation,
405
+ laws
406
+ });
407
+ /** A defined call's expansion, checked: of its output's kind, reading only its arguments. */
408
+ const expand = (body, args) => {
409
+ const expansion = toOperand(body(...args));
410
+ 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"}`);
411
+ const allowed = readKeys(...args);
412
+ const hidden = [...readKeys(expansion)].filter((key) => !allowed.has(key));
413
+ if (hidden.length > 0) throw new Error(`[foldkit-entity] ${id}: \`definedAs\` reads ${hidden.join(", ")}, which no argument holds; pass it as one`);
414
+ return expansion;
415
+ };
416
+ const call = (...written) => {
417
+ const explicit = written.length === input.length + 1 ? Option.some(callOptionsOf(id, written[written.length - 1])) : Option.none();
418
+ const given = Option.isSome(explicit) ? written.slice(0, -1) : written;
419
+ if (given.length !== input.length) throw new Error(`[foldkit-entity] ${id}: takes ${input.length} argument${input.length === 1 ? "" : "s"}, given ${given.length}`);
420
+ const args = Object.freeze(given.map((value, position) => argumentFor(id, position, input[position], value)));
421
+ const expansion = Option.map(descriptor.definedAs, (body) => expand(body, args));
422
+ const carried = Option.match(explicit, {
423
+ onSome: (each) => givenCollation(id, descriptor, each),
424
+ onNone: () => Option.match(expansion, {
425
+ onSome: (body) => isPredicate(body) ? Option.none() : collationOf(body),
426
+ onNone: () => callCollation(id, collation, args)
427
+ })
428
+ });
429
+ return predicate ? node({
430
+ _tag: "Test",
431
+ operator: descriptor,
432
+ args,
433
+ expansion,
434
+ collation: carried
435
+ }) : node({
436
+ _tag: "Call",
437
+ operator: descriptor,
438
+ args,
439
+ expansion,
440
+ collation: carried
441
+ });
442
+ };
443
+ return Object.freeze(Object.assign(call, { descriptor }));
444
+ };
445
+ /** Each defined call replaced by its expansion, deeply; built once per node. */
446
+ const expandedCache = /* @__PURE__ */ new WeakMap();
447
+ const expandedScalar = (scalar) => {
448
+ const known = expandedCache.get(scalar);
449
+ if (known !== void 0) return known;
450
+ const result = scalar._tag === "Call" ? Option.match(scalar.expansion, {
451
+ onSome: expandedScalar,
452
+ onNone: () => node({
453
+ ...scalar,
454
+ args: scalar.args.map(expandedSide)
455
+ })
456
+ }) : scalar;
457
+ expandedCache.set(scalar, result);
458
+ return result;
459
+ };
460
+ const expandedSide = (side) => isPredicate(side) ? expandedPredicate(side) : expandedScalar(side);
461
+ const expandedPredicate = (predicate) => {
462
+ const known = expandedCache.get(predicate);
463
+ if (known !== void 0) return known;
464
+ const result = Match.value(predicate).pipe(Match.tagsExhaustive({
465
+ Eq: (eq) => node({
466
+ ...eq,
467
+ left: expandedSide(eq.left),
468
+ right: expandedSide(eq.right)
469
+ }),
470
+ Null: (nul) => node({
471
+ ...nul,
472
+ operand: expandedScalar(nul.operand)
473
+ }),
474
+ Contains: (contains) => node({
475
+ ...contains,
476
+ value: expandedScalar(contains.value),
477
+ search: expandedSide(contains.search)
478
+ }),
479
+ In: (inPredicate) => node({
480
+ ...inPredicate,
481
+ value: expandedScalar(inPredicate.value),
482
+ among: expandedScalar(inPredicate.among)
483
+ }),
484
+ And: (and) => node({
485
+ ...and,
486
+ operands: Array$1.map(and.operands, expandedPredicate)
487
+ }),
488
+ Or: (or) => node({
489
+ ...or,
490
+ operands: Array$1.map(or.operands, expandedPredicate)
491
+ }),
492
+ Not: (not) => node({
493
+ ...not,
494
+ operand: expandedPredicate(not.operand)
495
+ }),
496
+ Compare: (compare) => node({
497
+ ...compare,
498
+ left: expandedScalar(compare.left),
499
+ right: expandedScalar(compare.right)
500
+ }),
501
+ Test: (test) => Option.match(test.expansion, {
502
+ onSome: expandedPredicate,
503
+ onNone: () => node({
504
+ ...test,
505
+ args: test.args.map(expandedSide)
506
+ })
507
+ }),
508
+ Exists: (exists) => node({
509
+ ...exists,
510
+ where: Option.map(exists.where, expandedPredicate)
511
+ })
512
+ }));
513
+ expandedCache.set(predicate, result);
514
+ return result;
515
+ };
516
+ /**
517
+ * The most relations one path follows. Each is a subquery in SQL and a lookup
518
+ * in memory; the deepest rule a real app here writes follows two.
519
+ */
520
+ const maxPathLength = 4;
521
+ /** A value checked to be a `one` relation, or refused with what to write instead. */
522
+ const oneRelation = (step, value) => {
523
+ if (tagOf(value) !== "Relation") throw new Error(`[foldkit-entity] Expr.${step}: the first argument is a relation (Post.relations.author)`);
524
+ const relation = value;
525
+ if (relation.cardinality !== "one") throw new Error(`[foldkit-entity] Expr.${step}: ${relation.owner.name}.${relation.key} is a many relation; name the one relation that points back${step === "path" ? ", with Expr.exists" : ""}`);
526
+ return relation;
527
+ };
528
+ /** `Expr.path` from the viewer: a field of their row, or what a path from it reads. */
529
+ const viewerPathOf = (from, end) => {
530
+ const start = from.target();
531
+ const onStart = (owner, what) => {
532
+ if (owner.token !== start.identity.token) throw new Error(`[foldkit-entity] Expr.path: the viewer is a ${start.name}, but ${what} is read on a ${owner.name}`);
533
+ };
534
+ return Match.value(toOperand(end)).pipe(Match.tag("Field", (field) => {
535
+ onStart(field.owner, `${field.owner.name}.${field.key}`);
536
+ return node({
537
+ _tag: "ViewerPath",
538
+ viewer: from,
539
+ via: [],
540
+ field
541
+ });
542
+ }), Match.tag("Path", (path) => {
543
+ onStart(path.via[0].owner, showExpr(path));
544
+ return node({
545
+ _tag: "ViewerPath",
546
+ viewer: from,
547
+ via: path.via,
548
+ field: path.field
549
+ });
550
+ }), Match.orElse((other) => {
551
+ throw new Error(`[foldkit-entity] Expr.path: a path from the viewer ends at a field or a path, not ${showExpr(other)}`);
552
+ }));
553
+ };
554
+ /** `Expr.path`: `relation` followed first, then whatever `end` reads, checked to be on its target. */
555
+ const pathOf = (relation, end) => {
556
+ if (tagOf(relation) === "Viewer") return viewerPathOf(relation, end);
557
+ const first = oneRelation("path", relation);
558
+ const target = first.target().identity;
559
+ const onTarget = (owner, what) => {
560
+ if (owner.token !== target.token) throw new Error(`[foldkit-entity] Expr.path: ${first.owner.name}.${first.key} reaches a ${target.name}, but ${what} is read on a ${owner.name}`);
561
+ };
562
+ const capped = (path) => {
563
+ if (path.via.length > 4) throw new Error(`[foldkit-entity] Expr.path: ${showExpr(path)} follows more than 4 relations`);
564
+ return node(path);
565
+ };
566
+ return Match.value(toOperand(end)).pipe(Match.tag("Field", (field) => {
567
+ onTarget(field.owner, `${field.owner.name}.${field.key}`);
568
+ return capped({
569
+ _tag: "Path",
570
+ via: [first],
571
+ field
572
+ });
573
+ }), Match.tag("Path", (path) => {
574
+ onTarget(path.via[0].owner, showExpr(path));
575
+ return capped({
576
+ ...path,
577
+ via: [first, ...path.via]
578
+ });
579
+ }), Match.tag("Exists", (exists) => {
580
+ onTarget(existsStart(exists).owner, showExpr(exists));
581
+ return capped({
582
+ ...exists,
583
+ via: [first, ...exists.via]
584
+ });
585
+ }), Match.orElse((other) => {
586
+ throw new Error(`[foldkit-entity] Expr.path: a path ends at a field, a path or an exists, not ${showExpr(other)}`);
587
+ }));
588
+ };
589
+ /** `Expr.exists`: the filter checked to read only the pointing row and the input. */
590
+ const existsOf = (relation, where) => {
591
+ const pointing = oneRelation("exists", relation);
592
+ const filter = Option.fromUndefinedOr(where);
593
+ Option.map(filter, (given) => {
594
+ if (!isPredicate(given)) throw new Error("[foldkit-entity] Expr.exists: the filter is a predicate");
595
+ const read = dependenciesOf(given);
596
+ const foreign = read.fields.find((field) => field.owner.token !== pointing.owner.token);
597
+ if (foreign !== void 0 || read.next.length > 0 || read.reaches.length > 0) throw new Error(`[foldkit-entity] Expr.exists: the filter reads ${foreign === void 0 ? "past its row" : `${foreign.entity}.${foreign.key}`}; it reads the pointing ${pointing.owner.name}'s own fields and the input`);
598
+ });
599
+ return node({
600
+ _tag: "Exists",
601
+ via: [],
602
+ relation: pointing,
603
+ where: filter
604
+ });
605
+ };
606
+ const isOf = (subject, tag, build) => {
607
+ const relation = tagOf(subject) === "Relation" ? subject : void 0;
608
+ if (relation !== void 0 && relation.cardinality !== "one") throw new Error(`[foldkit-entity] Expr.is: ${relation.owner.name}.${relation.key} is a many relation, which reaches no one row`);
609
+ const entity = relation === void 0 ? subject : relation.target();
610
+ const variants = Option.getOrThrowWith(typeof entity === "object" && entity !== null && "identity" in entity ? variantsOf(entity.identity) : Option.none(), () => /* @__PURE__ */ new Error("[foldkit-entity] Expr.is: the first argument is an Entity declared with Entity.defineVariants, or a one relation to one"));
611
+ if (!variants.tags.includes(tag)) throw new Error(`[foldkit-entity] Expr.is: ${entity.name} has no case "${tag}"; its cases are ${variants.tags.join(", ")}`);
612
+ const stored = entity.fields;
613
+ const read = (field) => relation === void 0 ? field : pathOf(relation, field);
614
+ const is = Expr.eq(read(stored._tag), tag);
615
+ if (build === void 0) return is;
616
+ const caseFields = {};
617
+ for (const [key, schema] of Object.entries(variants.cases[tag])) put(caseFields, key, read(Object.freeze({
618
+ ...stored[key],
619
+ schema
620
+ })));
621
+ const asked = build(Object.freeze(caseFields));
622
+ if (!isPredicate(asked)) throw new Error(`[foldkit-entity] Expr.is: what is asked of a ${tag} is a predicate`);
623
+ return Expr.and(is, asked);
624
+ };
625
+ const fieldOf = ((field) => fieldExpr(field));
626
+ const nextOf = ((member) => node({
627
+ _tag: "Next",
628
+ field: toOperand(member)
629
+ }));
630
+ const Expr = {
631
+ /**
632
+ * An operator, defined by what a call of it means: `definedAs` builds that
633
+ * expression from the call's arguments, once per call, and every interpreter
634
+ * runs it, so the operator needs no implementation anywhere. What it adds is
635
+ * a name: a query, a guard and an invariant that mean the same thing say so,
636
+ * and print it.
637
+ *
638
+ * ```ts
639
+ * const published = Expr.operator('cms.published', {
640
+ * input: [Schema.Unknown],
641
+ * output: Schema.Boolean,
642
+ * definedAs: publishedAt => Expr.isNotNull(publishedAt),
643
+ * })
644
+ * Query.where(published(Post.fields.publishedAt))
645
+ * ```
646
+ *
647
+ * Arguments are checked by their stored form: a field, scalar or plain value
648
+ * of the input's stored type, or a predicate where it takes a boolean. A
649
+ * boolean output makes a call a predicate. `definedAs` may read only what its
650
+ * arguments hold: a field or input it closes over instead is refused when
651
+ * called, since nothing asking what the call reads would see it. The id is
652
+ * namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)
653
+ * changes when what it means does.
654
+ *
655
+ * **Without `definedAs` it is primitive**: each interpreter implements it
656
+ * (`Operators.implement` in memory), and one without an implementation
657
+ * refuses the body by the operator's id. `nulls` (default `strict`: a null
658
+ * argument gives null, the implementation never sees one) and `collation`
659
+ * (`operands`: a text result carries its text arguments' shared collation;
660
+ * `required`: it compares text itself and needs one) are a primitive
661
+ * operator's; a defined one means its body for both.
662
+ */
663
+ operator: (id, options) => makeOperator(id, options),
664
+ /**
665
+ * The predicate or scalar (an order term's, say) with every call of a
666
+ * defined operator replaced by what it means, deeply. An interpreter that
667
+ * compiles a body expands it first, and compiles exactly what was written
668
+ * out. A call with no definition stays, for the interpreter to run or refuse
669
+ * by name.
670
+ */
671
+ /**
672
+ * Whether a constant written in these expressions is one no two backends
673
+ * agree on, text holding a NUL or NaN, or a list holding one: SQL refuses
674
+ * such a parameter wherever it compiles, so an interpreter refuses the run,
675
+ * not one row.
676
+ */
677
+ givesUnportable: (...nodes) => {
678
+ const seen = /* @__PURE__ */ new Set();
679
+ const nul = (value) => typeof value === "string" && value.includes(String.fromCharCode(0)) || typeof value === "number" && Number.isNaN(value);
680
+ const walk = (node) => {
681
+ if (seen.has(node)) return false;
682
+ seen.add(node);
683
+ if (node._tag === "Literal") return Array.isArray(node.value) ? node.value.some(nul) : nul(node.value);
684
+ return childrenOf(node).some(walk);
685
+ };
686
+ return nodes.some(walk);
687
+ },
688
+ expanded: (node) => isPredicate(node) ? expandedPredicate(node) : expandedScalar(node),
689
+ /**
690
+ * What these expressions need that an interpreter lacks, as `Query.unsupported`
691
+ * says it for a query: each kernel operation `supported` does not list, then
692
+ * each primitive operator `operators` does not implement, by name (`id`, or
693
+ * `id@version` past the first). For anything holding expressions that is not a
694
+ * query: a guard's rule, an invariant, a write's `when`.
695
+ */
696
+ unsupported: (nodes, interpreter) => unsupportedIn(nodes, interpreter.operations, interpreter.operators),
697
+ /** A constant. Comparisons coerce a plain value, so this is rarely written. */
698
+ literal,
699
+ /**
700
+ * A value the query is given when it runs. A definition builds these from its
701
+ * `Input` schema; written by hand only when constructing a body directly.
702
+ */
703
+ input: (key, schema) => node({
704
+ _tag: "Input",
705
+ key,
706
+ schema
707
+ }),
708
+ /**
709
+ * A field, or a `one` relation as the id it points at, as the row a write
710
+ * would leave holds it: what `Entity.invariant`'s builder hands out as `after`.
711
+ */
712
+ next: nextOf,
713
+ /**
714
+ * One field of one Entity, as a scalar. An expression is one already: an
715
+ * invariant's `before.x` and `after.x` compare as they are, so wrapping one
716
+ * is refused with that sentence.
717
+ */
718
+ field: fieldOf,
719
+ /**
720
+ * What the row reached through a `one` relation holds: a field of it, a
721
+ * further path from it, or an exists asked of it. The first relation is the
722
+ * judged row's own.
723
+ *
724
+ * ```ts
725
+ * Expr.eq(Expr.path(Post.relations.author, User.fields.handle), input.handle)
726
+ * Expr.path(Note.relations.project, Expr.path(Project.relations.org, Org.fields.plan))
727
+ * ```
728
+ *
729
+ * A null link, or a row the reader may not see, reaches no row: the field
730
+ * reads null, and an exists at the end is unknown, as SQL's scalar subquery
731
+ * is. At most `maxPathLength` relations.
732
+ */
733
+ path: pathOf,
734
+ /**
735
+ * Some row points at this one through `relation`, a `one` relation of
736
+ * another Entity, and holds `where`, a predicate over that row's own fields
737
+ * and the input:
738
+ *
739
+ * ```ts
740
+ * // Posts whose author the reader follows.
741
+ * Expr.path(Post.relations.author,
742
+ * Expr.exists(Follow.relations.followee, Expr.eq(Follow.fields.followerId, input.me)))
743
+ * ```
744
+ *
745
+ * Only rows the reader may see are sought. Never unknown in SQL; in memory,
746
+ * unknown when no held row holds and the holder may lack one that would.
747
+ */
748
+ exists: existsOf,
749
+ /**
750
+ * The row is of case `tag` of an Entity declared with
751
+ * `Entity.defineVariants`, and holds what `build` asks of that case's
752
+ * fields, each typed as the case holds it:
753
+ *
754
+ * ```ts
755
+ * Expr.is(Domain, 'Unconfirmed')
756
+ * Expr.is(Domain, 'Available', ({ price }) => Expr.lt(price, 20))
757
+ * // Through a one relation, the row it reaches.
758
+ * Expr.is(Order.relations.domain, 'Available', ({ price }) => Expr.lt(price, 20))
759
+ * ```
760
+ *
761
+ * It is `_tag = tag` and the predicate, so a row of another case is false,
762
+ * never unknown, and `Expr.not` of it holds there. Through a relation, a null
763
+ * link reaches no row and the test is unknown, as a path's field reads null.
764
+ * Use the fields inside `build`: outside it a case's field is the stored
765
+ * column, null on rows of other cases.
766
+ */
767
+ is: isOf,
768
+ /**
769
+ * Whoever asks, as a row of `entity`: `Expr.eq(Like.fields.userId,
770
+ * Expr.viewer(User))`. Shaped as a `one` relation to `entity`. Its value is
771
+ * the row's id, and null for a visitor or a viewer of another Entity, so a
772
+ * comparison with it holds of no row. A server reads it from
773
+ * `RemoteServer.make`'s `viewer`, a client from `Remote.make`'s.
774
+ */
775
+ viewer,
776
+ /**
777
+ * The time of the write, in milliseconds since the epoch, as a number field
778
+ * stores it. A server reads its clock. A client judging a list has no
779
+ * reading of the time the server judged it at, so such a list is the
780
+ * server's to say.
781
+ */
782
+ now,
783
+ /**
784
+ * Two scalars are the same value: a field (or an expression) on the left,
785
+ * and the value on the right, typed from it. Fields and plain values are
786
+ * coerced, so the common form reads as it means:
787
+ *
788
+ * ```ts
789
+ * Expr.eq(Post.fields.slug, input.slug)
790
+ * Expr.eq(Post.fields.status, 'active')
791
+ * ```
792
+ */
793
+ eq: (left, right) => node({
794
+ _tag: "Eq",
795
+ left: toOperand(left),
796
+ right: toOperand(right)
797
+ }),
798
+ /**
799
+ * Whether a field holds no value. Its opposite is `isNotNull`; both are the
800
+ * one node, since a query asks which of the two it means, and `is not null`
801
+ * has no unknown for a `not` to keep.
802
+ */
803
+ isNull: (operand) => node({
804
+ _tag: "Null",
805
+ operand: toExpr(operand, "isNull"),
806
+ present: false
807
+ }),
808
+ /** Whether a field holds a value. */
809
+ isNotNull: (operand) => node({
810
+ _tag: "Null",
811
+ operand: toExpr(operand, "isNotNull"),
812
+ present: true
813
+ }),
814
+ /**
815
+ * Whether a text value contains `search`, anywhere in it. Containing the
816
+ * empty string is everything, so a search box with nothing typed in it is the
817
+ * same query as one with something — no branch, and no second query.
818
+ *
819
+ * **Case-insensitive**, which is what a search means, and which has to be
820
+ * said rather than left to the interpreter: SQLite's `like` ignores case and
821
+ * Postgres's does not, so a body that left it open would mean two things.
822
+ * Folding is ASCII-only, because that is what `lower` does in SQLite without
823
+ * ICU.
824
+ *
825
+ * **Over a column that can be null this is not the same as no filter.** A
826
+ * null contains nothing, not even the empty string, so its rows drop out. A
827
+ * nullable column that should match everything on an empty search says so:
828
+ * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.
829
+ */
830
+ contains: (value, search) => {
831
+ const operand = toOperand(search);
832
+ 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`);
833
+ return node({
834
+ _tag: "Contains",
835
+ value: toExpr(value, "contains"),
836
+ search: operand
837
+ });
838
+ },
839
+ /**
840
+ * Whether a value is one of `among`: a list written out, or an input whose
841
+ * value is one. Each element is compared as `eq` compares.
842
+ *
843
+ * ```ts
844
+ * Expr.in(Todo.fields.projectId, input.projectIds)
845
+ * Expr.in(Todo.fields.status, ['open', 'blocked'])
846
+ * ```
847
+ *
848
+ * As SQL's `in`: a null value is unknown, as is no match against a list
849
+ * holding a null, and an empty list matches no row. A list written out is
850
+ * copied, so changing the array afterwards does not change the query.
851
+ */
852
+ in: (value, among) => node({
853
+ _tag: "In",
854
+ value: toExpr(value, "in"),
855
+ among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, "in")
856
+ }),
857
+ /**
858
+ * `left` orders before `right`. Numbers compare as numbers; text compares
859
+ * under a collation, the one given or the field's declared one, which must be
860
+ * `binary` or `asciiFold` (so every backend agrees), and text needs a field on
861
+ * one side. A date compares by its encoded form: as text when it is stored as
862
+ * an ISO string, so its field declares `Collation.binary`. A null on either
863
+ * side is unknown, so the row is matched by neither this nor its `not`.
864
+ *
865
+ * ```ts
866
+ * Expr.lt(fields.cents, 1000)
867
+ * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))
868
+ * ```
869
+ */
870
+ lt: comparison("lt"),
871
+ /** `left` orders before `right`, or with it; see `Expr.lt`. */
872
+ lte: comparison("lte"),
873
+ /** `left` orders after `right`; see `Expr.lt`. */
874
+ gt: comparison("gt"),
875
+ /** `left` orders after `right`, or with it; see `Expr.lt`. */
876
+ gte: comparison("gte"),
877
+ /**
878
+ * Every operand holds, as one predicate to place inside another: `where`'s
879
+ * list is already a conjunction, so this is for `or(and(a, b), c)`.
880
+ * Unknown as SQL's `and` is: false wins over unknown, which wins over true.
881
+ * Needs an operand; a list built at run time is checked non-empty first
882
+ * (`Array.isReadonlyArrayNonEmpty`), since an empty `and` would match every row.
883
+ */
884
+ and: connective("and", "And"),
885
+ /**
886
+ * At least one operand holds:
887
+ *
888
+ * ```ts
889
+ * Expr.or(Expr.contains(fields.description, input.search), Expr.contains(fields.upc, input.search))
890
+ * ```
891
+ *
892
+ * Unknown as SQL's `or` is: true wins over unknown, which wins over false.
893
+ * Needs an operand, since an empty `or` would match no row.
894
+ */
895
+ or: connective("or", "Or"),
896
+ /**
897
+ * The operand does not hold. **A null is matched by neither side**:
898
+ * `not(eq(status, 'draft'))` leaves out a row whose `status` is null, since
899
+ * `null = 'draft'` is unknown and so is its `not`, as in SQL. "Everything
900
+ * but drafts" over a nullable column is
901
+ * `Expr.or(Expr.isNull(status), Expr.not(Expr.eq(status, 'draft')))`.
902
+ */
903
+ not: (operand) => {
904
+ if (!isPredicate(operand)) throw new Error("[foldkit-entity] Expr.not: the operand is a predicate; compare a value with Expr.eq first");
905
+ return node({
906
+ _tag: "Not",
907
+ operand
908
+ });
909
+ },
910
+ /**
911
+ * A filter that applies only when its input is given: `or(isNull($x), …)`,
912
+ * with the predicate built from the input as never null.
913
+ *
914
+ * ```ts
915
+ * // Every product, or those of the chosen status.
916
+ * Expr.whenGiven(input.status, status => Expr.eq(fields.status, status))
917
+ * ```
918
+ *
919
+ * An interpreter that runs per request, as the Drizzle compiler does, decides
920
+ * `isNull($x)` before writing SQL, so this compiles to `true`, which filters
921
+ * nothing, or to the predicate alone.
922
+ */
923
+ whenGiven: (input, build) => Expr.or(Expr.isNull(input), build(input)),
924
+ /** An expression as readable text; see `showExpr` for what it is and is not. */
925
+ show: (node) => showExpr(node),
926
+ /**
927
+ * The predicate with each field after a write (`Next`) that `values` names,
928
+ * by key, read as that value: how an invariant is judged where the
929
+ * write's new values are known. A field it does not name stays `Next`, for
930
+ * the interpreter to read as the row after holds it.
931
+ */
932
+ 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)))
933
+ };
934
+ const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) : substitutedScalar(side, rewrite);
935
+ /**
936
+ * A scalar rewritten: a call's arguments and expansion each, so a field read
937
+ * under it is rewritten as one read directly is; anything else by `rewrite`.
938
+ */
939
+ const substitutedScalar = (scalar, rewrite) => scalar._tag === "Call" ? node({
940
+ ...scalar,
941
+ args: Object.freeze(scalar.args.map((arg) => substitutedSide(arg, rewrite))),
942
+ expansion: Option.map(scalar.expansion, (expansion) => substitutedScalar(expansion, rewrite))
943
+ }) : rewrite(scalar);
944
+ const substituted = (predicate, rewrite) => {
945
+ switch (predicate._tag) {
946
+ case "Eq": return node({
947
+ ...predicate,
948
+ left: substitutedSide(predicate.left, rewrite),
949
+ right: substitutedSide(predicate.right, rewrite)
950
+ });
951
+ case "Null": return node({
952
+ ...predicate,
953
+ operand: substitutedScalar(predicate.operand, rewrite)
954
+ });
955
+ case "Contains": return node({
956
+ ...predicate,
957
+ value: substitutedScalar(predicate.value, rewrite),
958
+ search: substitutedSide(predicate.search, rewrite)
959
+ });
960
+ case "In": return node({
961
+ ...predicate,
962
+ value: substitutedScalar(predicate.value, rewrite),
963
+ among: substitutedScalar(predicate.among, rewrite)
964
+ });
965
+ case "And":
966
+ case "Or": return node({
967
+ ...predicate,
968
+ operands: Array$1.map(predicate.operands, (operand) => substituted(operand, rewrite))
969
+ });
970
+ case "Not": return node({
971
+ ...predicate,
972
+ operand: substituted(predicate.operand, rewrite)
973
+ });
974
+ case "Compare": return node({
975
+ ...predicate,
976
+ left: substitutedScalar(predicate.left, rewrite),
977
+ right: substitutedScalar(predicate.right, rewrite)
978
+ });
979
+ case "Test": return node({
980
+ ...predicate,
981
+ args: Object.freeze(predicate.args.map((arg) => substitutedSide(arg, rewrite))),
982
+ expansion: Option.map(predicate.expansion, (expansion) => substituted(expansion, rewrite))
983
+ });
984
+ case "Exists": return predicate;
985
+ }
986
+ };
987
+ /** A term, its nulls placed by `options` or by the direction's default. */
988
+ const term = (direction, expr, options = {}) => {
989
+ const carried = Match.value(expr).pipe(Match.tagsExhaustive({
990
+ Field: (field) => field.collation,
991
+ Call: (call) => call.collation,
992
+ Path: (path) => {
993
+ throw new Error(`[foldkit-entity] Order: ${showExpr(path)} is a path; a list orders by its own row's fields`);
994
+ },
995
+ ViewerPath: (path) => {
996
+ throw new Error(`[foldkit-entity] Order: ${showExpr(path)} is a path from the viewer; a list orders by its own row's fields`);
997
+ },
998
+ Literal: () => Option.none(),
999
+ Input: () => Option.none(),
1000
+ Next: () => Option.none(),
1001
+ Viewer: () => Option.none(),
1002
+ Now: () => Option.none()
1003
+ }));
1004
+ const number = sideKind(expr) === "number";
1005
+ 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`);
1006
+ const collation = number ? Option.none() : Option.orElse(Option.fromUndefinedOr(options.collation), () => carried);
1007
+ if (expr._tag === "Call") orderableCall(expr, collation);
1008
+ return node({
1009
+ _tag: "Term",
1010
+ direction,
1011
+ expr,
1012
+ nulls: options.nulls ?? (direction === "asc" ? "last" : "first"),
1013
+ collation
1014
+ });
1015
+ };
1016
+ /**
1017
+ * Refuses a call no interpreter could order alike (expr-operations-DESIGN §8):
1018
+ * its result must be a number, or text under a collation every interpreter
1019
+ * shares. A field's text may be left to the backend; a call's has no backend
1020
+ * column to fall back on.
1021
+ */
1022
+ const orderableCall = (call, collation) => {
1023
+ const fail = (why) => {
1024
+ throw new Error(`[foldkit-entity] Order: ${showExpr(call)} ${why}`);
1025
+ };
1026
+ const kind = sideKind(call);
1027
+ if (kind === "number") return;
1028
+ if (kind !== "text") fail("is neither a number nor text, so it orders nowhere alike");
1029
+ Option.match(collation, {
1030
+ onNone: () => fail("is text with no collation, so backends would order it differently; give the term or its text Collation.binary or Collation.asciiFold"),
1031
+ onSome: (each) => {
1032
+ if (each._tag === "Locale") fail(`is ordered by the backend's "${each.locale}" collation, which a call cannot carry`);
1033
+ }
1034
+ });
1035
+ };
1036
+ /**
1037
+ * What an order term orders by, refusing a link: a client holds a link as a
1038
+ * ref, not the id it orders by, so it could not place a row there.
1039
+ */
1040
+ const orderOperand = (expr, step) => {
1041
+ if (tagOf(expr) === "Relation") throw new Error(`[foldkit-entity] Order.${step}: a list orders by its own fields, not by where a relation points`);
1042
+ return toExpr(expr, step);
1043
+ };
1044
+ const Order = {
1045
+ /** Smallest first; rows without a value last, unless `nulls` says first. */
1046
+ asc: (expr, options) => term("asc", orderOperand(expr, "asc"), options),
1047
+ /** Largest first; rows without a value first, unless `nulls` says last. */
1048
+ desc: (expr, options) => term("desc", orderOperand(expr, "desc"), options),
1049
+ /**
1050
+ * The order the input names, among `choices`: every name the sort can hold
1051
+ * maps to a field or a call that orders, so a name left out is a type error
1052
+ * here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after
1053
+ * it decide.
1054
+ *
1055
+ * ```ts
1056
+ * Query.orderBy(Order.chosen(input.sort, { title: Post.fields.title }))
1057
+ * ```
1058
+ */
1059
+ chosen: (sort, choices) => {
1060
+ const fields = Object.create(null);
1061
+ for (const [name, choice] of Object.entries(choices)) {
1062
+ const expr = orderOperand(choice, "chosen");
1063
+ if (expr._tag !== "Field" && expr._tag !== "Call") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is neither a field nor a call`);
1064
+ if (expr._tag === "Call") orderableCall(expr, expr.collation);
1065
+ fields[name] = expr;
1066
+ }
1067
+ return node({
1068
+ _tag: "Chosen",
1069
+ sort,
1070
+ choices: Object.freeze(fields)
1071
+ });
1072
+ }
1073
+ };
1074
+ const placeable = Object.freeze({ _tag: "Placeable" });
1075
+ const notPlaceable = (reason) => Object.freeze({
1076
+ _tag: "NotPlaceable",
1077
+ reason
1078
+ });
1079
+ /**
1080
+ * Whether values encoded by `ast` order the same everywhere: numbers and
1081
+ * booleans, never text. A null among them does too: where it goes is said on
1082
+ * every order term.
1083
+ */
1084
+ 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));
1085
+ /** Why a term cannot be placed by a client running `operators`, if it cannot. */
1086
+ const unplaceable = (orderTerm, operators) => Match.value(orderTerm.expr).pipe(Match.tag("Call", (call) => {
1087
+ const missing = missingFrom(dependenciesOf(call).operators, operators);
1088
+ return missing.length === 0 ? Option.none() : Option.some(`it orders by ${showExpr(call)}, and this client does not run ${missing.join(", ")}`);
1089
+ }), Match.tag("Field", (field) => Option.match(orderTerm.collation, {
1090
+ onNone: () => ordersIntrinsically(Schema.toEncoded(field.schema).ast) ? Option.none() : Option.some(`it orders by ${field.owner.name}.${field.key}, text with no declared collation`),
1091
+ onSome: (collation) => Match.value(collation).pipe(Match.tagsExhaustive({
1092
+ Binary: () => Option.none(),
1093
+ AsciiFold: () => Option.none(),
1094
+ Locale: ({ locale }) => Option.some(`it orders ${field.owner.name}.${field.key} by the backend's "${locale}" collation`)
1095
+ }))
1096
+ })), Match.tags({
1097
+ Literal: neither,
1098
+ Input: neither,
1099
+ Next: neither,
1100
+ Viewer: neither,
1101
+ Now: neither,
1102
+ Path: neither,
1103
+ ViewerPath: neither
1104
+ }), Match.exhaustive);
1105
+ const neither = () => Option.some("it orders by something that is neither a field nor a call");
1106
+ /** Each Entity's id tie-break, made once, so a resolved order reuses one term. */
1107
+ const idTerms = /* @__PURE__ */ new WeakMap();
1108
+ const idTermOf = (entity) => {
1109
+ const known = idTerms.get(entity);
1110
+ if (known !== void 0) return known;
1111
+ const id = entity.fields.id;
1112
+ if (id === void 0) throw new Error(`[foldkit-entity] ${entity.name} has no id field to break an order's ties by`);
1113
+ const tieBreak = term("asc", fieldExpr(id));
1114
+ idTerms.set(entity, tieBreak);
1115
+ return tieBreak;
1116
+ };
1117
+ /** The fixed term a chosen order is for one input, or none for a `null` sort. */
1118
+ const chosenTerms = (chosen, input) => {
1119
+ const sort = own(input, chosen.sort.key);
1120
+ if (sort === null || sort === void 0) return [];
1121
+ const picked = typeof sort === "object" && "by" in sort && typeof sort.by === "string" ? sort.by : void 0;
1122
+ const direction = typeof sort === "object" && "direction" in sort ? sort.direction : void 0;
1123
+ if (picked === void 0 || !Object.hasOwn(chosen.choices, picked) || direction !== "asc" && direction !== "desc") throw new Error(`[foldkit-entity] Order.chosen: $${chosen.sort.key} names no order it offers (${Object.keys(chosen.choices).join(", ")})`);
1124
+ return [term(direction, chosen.choices[picked])];
1125
+ };
1126
+ /**
1127
+ * Visits each node once. A node can be shared by several paths (`eq(n, n)`),
1128
+ * and a walk that followed every path would take time exponential in the depth.
1129
+ */
1130
+ const walk = (expr, found) => {
1131
+ if (found.seen.has(expr)) return;
1132
+ found.seen.add(expr);
1133
+ switch (expr._tag) {
1134
+ case "Literal": return;
1135
+ case "Field": {
1136
+ const byKey = found.fields.get(expr.owner.token) ?? /* @__PURE__ */ new Map();
1137
+ found.fields.set(expr.owner.token, byKey);
1138
+ if (!byKey.has(expr.key)) {
1139
+ const field = {
1140
+ entity: expr.owner.name,
1141
+ key: expr.key,
1142
+ owner: expr.owner
1143
+ };
1144
+ byKey.set(expr.key, field);
1145
+ found.order.push(field);
1146
+ }
1147
+ return;
1148
+ }
1149
+ case "Input":
1150
+ found.inputs.add(expr.key);
1151
+ return;
1152
+ case "Viewer":
1153
+ found.operations.add("viewer");
1154
+ return;
1155
+ case "Now":
1156
+ found.operations.add("now");
1157
+ return;
1158
+ case "Next": {
1159
+ found.operations.add("next");
1160
+ const { field } = expr;
1161
+ const byKey = found.next.get(field.owner.token) ?? /* @__PURE__ */ new Map();
1162
+ found.next.set(field.owner.token, byKey);
1163
+ if (!byKey.has(field.key)) {
1164
+ const read = {
1165
+ entity: field.owner.name,
1166
+ key: field.key,
1167
+ owner: field.owner
1168
+ };
1169
+ byKey.set(field.key, read);
1170
+ found.nextOrder.push(read);
1171
+ }
1172
+ return;
1173
+ }
1174
+ case "Eq":
1175
+ found.operations.add("eq");
1176
+ walk(expr.left, found);
1177
+ walk(expr.right, found);
1178
+ return;
1179
+ case "Null":
1180
+ found.operations.add(expr.present ? "isNotNull" : "isNull");
1181
+ walk(expr.operand, found);
1182
+ return;
1183
+ case "Contains":
1184
+ found.operations.add("contains");
1185
+ walk(expr.value, found);
1186
+ walk(expr.search, found);
1187
+ return;
1188
+ case "In":
1189
+ found.operations.add("in");
1190
+ walk(expr.value, found);
1191
+ walk(expr.among, found);
1192
+ return;
1193
+ case "And":
1194
+ found.operations.add("and");
1195
+ for (const operand of expr.operands) walk(operand, found);
1196
+ return;
1197
+ case "Or":
1198
+ found.operations.add("or");
1199
+ for (const operand of expr.operands) walk(operand, found);
1200
+ return;
1201
+ case "Not":
1202
+ found.operations.add("not");
1203
+ walk(expr.operand, found);
1204
+ return;
1205
+ case "Compare":
1206
+ found.operations.add("compare");
1207
+ walk(expr.left, found);
1208
+ walk(expr.right, found);
1209
+ return;
1210
+ case "Term":
1211
+ walk(expr.expr, found);
1212
+ return;
1213
+ case "Chosen":
1214
+ walk(expr.sort, found);
1215
+ for (const choice of Object.values(expr.choices)) walk(choice, found);
1216
+ return;
1217
+ case "Path":
1218
+ found.operations.add("path");
1219
+ found.reaches.push(expr);
1220
+ return;
1221
+ case "ViewerPath":
1222
+ found.operations.add("viewer");
1223
+ found.operations.add("path");
1224
+ found.reaches.push(expr);
1225
+ return;
1226
+ case "Exists":
1227
+ found.operations.add("exists");
1228
+ found.reaches.push(expr);
1229
+ Option.map(expr.where, (where) => {
1230
+ const inner = dependenciesOf(where);
1231
+ inner.inputs.forEach((key) => found.inputs.add(key));
1232
+ inner.operations.forEach((operation) => found.operations.add(operation));
1233
+ inner.operators.forEach((operator) => found.operators.add(operator));
1234
+ });
1235
+ return;
1236
+ case "Call":
1237
+ case "Test":
1238
+ found.operators.add(expr.operator);
1239
+ Option.match(expansionOf(expr), {
1240
+ onSome: (expansion) => walk(expansion, found),
1241
+ onNone: () => expr.args.forEach((arg) => walk(arg, found))
1242
+ });
1243
+ return;
1244
+ default: return absurd(expr);
1245
+ }
1246
+ };
1247
+ /**
1248
+ * What an expression reads and uses, for the planner and for an interpreter
1249
+ * deciding whether it can run this query at all. Distinct entries only, in the
1250
+ * order first seen, so the answer is stable enough to assert on.
1251
+ */
1252
+ const dependenciesOf = (...nodes) => {
1253
+ const found = {
1254
+ seen: /* @__PURE__ */ new Set(),
1255
+ fields: /* @__PURE__ */ new Map(),
1256
+ order: [],
1257
+ inputs: /* @__PURE__ */ new Set(),
1258
+ next: /* @__PURE__ */ new Map(),
1259
+ nextOrder: [],
1260
+ operations: /* @__PURE__ */ new Set(),
1261
+ operators: /* @__PURE__ */ new Set(),
1262
+ reaches: []
1263
+ };
1264
+ for (const term of nodes) walk(term, found);
1265
+ return {
1266
+ fields: found.order,
1267
+ next: found.nextOrder,
1268
+ inputs: [...found.inputs],
1269
+ operations: [...found.operations],
1270
+ operators: [...found.operators],
1271
+ reaches: found.reaches
1272
+ };
1273
+ };
1274
+ /**
1275
+ * Every member of the judged row an expression reads, each node visited once:
1276
+ * a field, or the relation a path or an exists starts from.
1277
+ */
1278
+ const fieldsIn = function* (expr, seen) {
1279
+ if (seen.has(expr)) return;
1280
+ seen.add(expr);
1281
+ switch (expr._tag) {
1282
+ case "Field":
1283
+ yield expr;
1284
+ return;
1285
+ case "Next":
1286
+ yield expr.field;
1287
+ return;
1288
+ case "Literal":
1289
+ case "Input":
1290
+ case "Viewer":
1291
+ case "Now": return;
1292
+ case "Eq":
1293
+ yield* fieldsIn(expr.left, seen);
1294
+ yield* fieldsIn(expr.right, seen);
1295
+ return;
1296
+ case "Null":
1297
+ yield* fieldsIn(expr.operand, seen);
1298
+ return;
1299
+ case "Contains":
1300
+ yield* fieldsIn(expr.value, seen);
1301
+ yield* fieldsIn(expr.search, seen);
1302
+ return;
1303
+ case "In":
1304
+ yield* fieldsIn(expr.value, seen);
1305
+ yield* fieldsIn(expr.among, seen);
1306
+ return;
1307
+ case "And":
1308
+ case "Or":
1309
+ for (const operand of expr.operands) yield* fieldsIn(operand, seen);
1310
+ return;
1311
+ case "Not":
1312
+ yield* fieldsIn(expr.operand, seen);
1313
+ return;
1314
+ case "Compare":
1315
+ yield* fieldsIn(expr.left, seen);
1316
+ yield* fieldsIn(expr.right, seen);
1317
+ return;
1318
+ case "Term":
1319
+ yield* fieldsIn(expr.expr, seen);
1320
+ return;
1321
+ case "Chosen":
1322
+ for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen);
1323
+ return;
1324
+ case "Path":
1325
+ yield expr.via[0];
1326
+ return;
1327
+ case "ViewerPath": return;
1328
+ case "Exists":
1329
+ yield existsStart(expr);
1330
+ return;
1331
+ case "Call":
1332
+ case "Test":
1333
+ for (const arg of expr.args) yield* fieldsIn(arg, seen);
1334
+ return;
1335
+ default: return absurd(expr);
1336
+ }
1337
+ };
1338
+ /**
1339
+ * A query reads one Entity, so a predicate or ordering term naming a different
1340
+ * one cannot be answered — an interpreter would be asked for a column of a
1341
+ * table it was never told to read. Compared by identity, not by name, because
1342
+ * two Entities defined with the same name are two Entities.
1343
+ */
1344
+ const checkOwnership = (step, what, entity, nodes) => {
1345
+ const seen = /* @__PURE__ */ new Set();
1346
+ for (const term of nodes) for (const field of fieldsIn(term, seen)) if (field.owner.token !== entity.identity.token) throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`);
1347
+ };
1348
+ /**
1349
+ * The most nodes a query's predicates may hold once every shared node is
1350
+ * counted on each path that reaches it. Interpreters read a predicate as a
1351
+ * tree: `evaluate` once per row, and the SQL compiler into text that repeats a
1352
+ * shared operand wherever it appears. So `eq(n, n)` nested thirty deep is
1353
+ * thirty-one objects and a billion nodes of work. Real queries are tens.
1354
+ */
1355
+ const maxQueryNodes = 1e3;
1356
+ const childrenOf = (expr) => {
1357
+ switch (expr._tag) {
1358
+ case "Literal":
1359
+ case "Field":
1360
+ case "Input":
1361
+ case "Next":
1362
+ case "Viewer":
1363
+ case "Now":
1364
+ case "Path":
1365
+ case "ViewerPath": return [];
1366
+ case "Exists": return Option.toArray(expr.where);
1367
+ case "Eq": return [expr.left, expr.right];
1368
+ case "Null": return [expr.operand];
1369
+ case "Contains": return [expr.value, expr.search];
1370
+ case "In": return [expr.value, expr.among];
1371
+ case "And":
1372
+ case "Or": return expr.operands;
1373
+ case "Not": return [expr.operand];
1374
+ case "Compare": return [expr.left, expr.right];
1375
+ case "Call":
1376
+ case "Test": return Option.match(expansionOf(expr), {
1377
+ onSome: (expansion) => [expansion],
1378
+ onNone: () => expr.args
1379
+ });
1380
+ }
1381
+ };
1382
+ /** A node's size as a tree, each distinct node sized once. */
1383
+ const expandedSize = (expr, sizes) => {
1384
+ const known = sizes.get(expr);
1385
+ if (known !== void 0) return known;
1386
+ const size = Math.min(1001, childrenOf(expr).reduce((sum, child) => sum + expandedSize(child, sizes), 1));
1387
+ sizes.set(expr, size);
1388
+ return size;
1389
+ };
1390
+ const QueryProto = {
1391
+ _tag: "Query",
1392
+ pipe() {
1393
+ return Pipeable.pipeArguments(this, arguments);
1394
+ }
1395
+ };
1396
+ const query = (entity, where, orderBy) => Object.freeze(Object.assign(Object.create(QueryProto), {
1397
+ entity,
1398
+ where: Object.freeze(where),
1399
+ orderBy: Object.freeze(orderBy)
1400
+ }));
1401
+ /**
1402
+ * Refuses a query whose predicates and order terms (every chosen alternative
1403
+ * among them) expand past `maxQueryNodes`, counting a shared node on every
1404
+ * path that reaches it: what an interpreter walks, and SQL writes out.
1405
+ */
1406
+ const checkSize = (step, where, orderBy) => {
1407
+ const sizes = /* @__PURE__ */ new Map();
1408
+ const terms = orderBy.flatMap((ordering) => Match.valueTags(ordering, {
1409
+ Term: ({ expr }) => [expr],
1410
+ Chosen: ({ choices }) => Object.values(choices)
1411
+ }));
1412
+ 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`);
1413
+ };
1414
+ const Query = {
1415
+ /** Every row of an Entity: the query each transformation narrows. */
1416
+ from: (entity) => query(entity, [], []),
1417
+ /**
1418
+ * Narrows to the rows the predicate holds for. Two `where`s conjoin — the
1419
+ * second never replaces the first — so a fragment can be written once and
1420
+ * piped into any query over the same Entity:
1421
+ *
1422
+ * ```ts
1423
+ * const published = Query.where(Expr.eq(Post.fields.published, true))
1424
+ * Query.from(Post).pipe(published, Query.where(byTitle))
1425
+ * ```
1426
+ */
1427
+ where: (...predicates) => (self) => {
1428
+ if (predicates.length === 0) return self;
1429
+ checkOwnership("where", "a predicate", self.entity, predicates);
1430
+ const where = [...self.where, ...predicates];
1431
+ checkSize("where", where, self.orderBy);
1432
+ return query(self.entity, where, self.orderBy);
1433
+ },
1434
+ /**
1435
+ * Reads the rows in this order. Two `orderBy`s append, so an earlier term
1436
+ * stays the more significant one and a later call adds a tie-breaker rather
1437
+ * than silently winning.
1438
+ */
1439
+ orderBy: (...terms) => (self) => {
1440
+ if (terms.length === 0) return self;
1441
+ checkOwnership("orderBy", "a term", self.entity, terms);
1442
+ const orderBy = [...self.orderBy, ...terms];
1443
+ checkSize("orderBy", self.where, orderBy);
1444
+ return query(self.entity, self.where, orderBy);
1445
+ },
1446
+ /**
1447
+ * The fixed terms this query orders by for one input: each chosen order
1448
+ * resolved to the field its input names, or to nothing for a `null` sort,
1449
+ * and the Entity's id last, ascending, unless the terms already read it. So
1450
+ * the order is total, and every interpreter breaks ties the same way: one
1451
+ * that broke them its own way would place rows a step apart from another.
1452
+ */
1453
+ orderFor: (self, input) => {
1454
+ const terms = self.orderBy.flatMap((entry) => Match.value(entry).pipe(Match.tagsExhaustive({
1455
+ Term: (term) => [term],
1456
+ Chosen: (chosen) => chosenTerms(chosen, input)
1457
+ })));
1458
+ const id = idTermOf(self.entity);
1459
+ return terms.some((term) => term.expr._tag === "Field" && term.expr.key === "id") ? terms : [...terms, id];
1460
+ },
1461
+ /**
1462
+ * Whether a client can order this query's rows exactly as the server does,
1463
+ * for one input: every term over a number or a boolean (a row may lack it), or over text with a
1464
+ * portable collation (`binary`, `asciiFold`), or a call whose primitive
1465
+ * operators the client's table (`operators`; none when not given) runs. A
1466
+ * body that names no order leaves it to the server, and is never placeable.
1467
+ */
1468
+ placement: (self, input, options = {}) => {
1469
+ if (self.orderBy.length === 0) return notPlaceable("its order is the server's: the body names none");
1470
+ const operators = options.operators ?? noOperators;
1471
+ for (const orderTerm of Query.orderFor(self, input)) {
1472
+ const reason = unplaceable(orderTerm, operators);
1473
+ if (Option.isSome(reason)) return notPlaceable(reason.value);
1474
+ }
1475
+ return placeable;
1476
+ },
1477
+ /**
1478
+ * Each operator the body calls, by name (`id`, or `id@version` past the
1479
+ * first), in the order it first calls them: a defined one, and each
1480
+ * primitive one its expansion calls.
1481
+ */
1482
+ operators: (self) => Query.dependencies(self).operators.map(operatorName),
1483
+ /**
1484
+ * What the whole query reads: the fields and inputs of every predicate and
1485
+ * every ordering term, and the operations it uses, with the fields also
1486
+ * split by role.
1487
+ */
1488
+ dependencies: (self) => ({
1489
+ ...dependenciesOf(...self.where, ...self.orderBy),
1490
+ predicate: dependenciesOf(...self.where).fields,
1491
+ order: dependenciesOf(...self.orderBy).fields
1492
+ }),
1493
+ /**
1494
+ * The operations this query needs that `supported` does not list, in the
1495
+ * order the query uses them, then each primitive operator `operators` does
1496
+ * not implement, by name. Without `operators`, every primitive operator is
1497
+ * named: a list of operations implements none. Empty means an interpreter
1498
+ * declaring both can answer it.
1499
+ *
1500
+ * An interpreter declares what it runs and refuses the rest, rather than
1501
+ * ignoring an operation it does not implement — which would answer a
1502
+ * different question and say nothing. The refusal is the interpreter's to
1503
+ * raise: this only says what is missing, because what to do about it differs
1504
+ * between one that compiles at registration and one that runs a body
1505
+ * directly.
1506
+ *
1507
+ * ```ts
1508
+ * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])
1509
+ * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
1510
+ * ```
1511
+ */
1512
+ unsupported: (self, supported, operators = noOperators) => unsupportedIn([...self.where, ...self.orderBy], supported, operators),
1513
+ /**
1514
+ * The whole query as readable text, one clause per line:
1515
+ *
1516
+ * ```text
1517
+ * FROM Post
1518
+ * WHERE Post.slug = $slug
1519
+ * AND Post.published = true
1520
+ * ORDER BY Post.updatedAt DESC
1521
+ * ```
1522
+ *
1523
+ * For an explanation or a diagnostic, never for an interpreter — see
1524
+ * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather
1525
+ * than printing an empty one, so what is shown is what was written.
1526
+ */
1527
+ show: (self) => [
1528
+ `FROM ${self.entity.name}`,
1529
+ ...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Match.value(predicate).pipe(Match.tag("Or", (or) => self.where.length > 1 ? `(${Expr.show(or)})` : Expr.show(or)), Match.orElse((each) => Expr.show(each)))}`),
1530
+ ...self.orderBy.length === 0 ? [] : [`ORDER BY ${self.orderBy.map((entry) => Match.value(entry).pipe(Match.tagsExhaustive({
1531
+ Term: (term) => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`,
1532
+ Chosen: (chosen) => `$${chosen.sort.key} among (${Object.entries(chosen.choices).map(([name, field]) => `${name}: ${Expr.show(field)}`).join(", ")})`
1533
+ }))).join(", ")}`]
1534
+ ].join("\n")
1535
+ };
1536
+ /**
1537
+ * An expression as readable text, in the IR's own terms.
1538
+ *
1539
+ * This is for a human — an explanation, a diagnostic, a test that wants to
1540
+ * assert on a whole predicate at once — and deliberately **not** for an
1541
+ * interpreter. It is close enough to SQL to read at a glance and unlike it
1542
+ * everywhere that matters: an input is `$slug` rather than a bound parameter,
1543
+ * `contains` is named rather than rendered as somebody's `like`, and no
1544
+ * dialect's escaping or collation is implied. What actually ran is whatever
1545
+ * that backend compiled, which is not this.
1546
+ *
1547
+ * A predicate standing where a value is wanted is parenthesised, because
1548
+ * `x is not null = $archived` reads as three operands and is two. A predicate
1549
+ * that *is* the whole expression is not: nothing encloses it.
1550
+ */
1551
+ const showExpr = (node) => {
1552
+ switch (node._tag) {
1553
+ case "Literal": return JSON.stringify(node.value) ?? String(node.value);
1554
+ case "Field": return `${node.owner.name}.${node.key}`;
1555
+ case "Input": return `$${node.key}`;
1556
+ case "Next": return `next ${node.field.owner.name}.${node.field.key}`;
1557
+ case "Viewer": return `viewer ${node.entity.name}`;
1558
+ case "Now": return "now";
1559
+ case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
1560
+ case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
1561
+ case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
1562
+ case "In": return `${showOperand(node.value)} in ${showOperand(node.among)}`;
1563
+ case "And": return node.operands.map(showConnected).join(" and ");
1564
+ case "Or": return node.operands.map(showConnected).join(" or ");
1565
+ case "Not": return `not (${showExpr(node.operand)})`;
1566
+ case "Compare": return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`;
1567
+ case "Call":
1568
+ case "Test": return `${operatorName(node.operator)}(${node.args.map(showOperand).join(", ")})`;
1569
+ case "Path": return [
1570
+ `${node.via[0].owner.name}`,
1571
+ ...node.via.map((step) => step.key),
1572
+ node.field.key
1573
+ ].join(".");
1574
+ case "ViewerPath": return `viewer ${[
1575
+ node.viewer.entity.name,
1576
+ ...node.via.map((step) => step.key),
1577
+ node.field.key
1578
+ ].join(".")}`;
1579
+ case "Exists": {
1580
+ const sought = `exists ${node.relation.owner.name}.${node.relation.key}${Option.match(node.where, {
1581
+ onNone: () => "",
1582
+ onSome: (where) => ` where ${showExpr(where)}`
1583
+ })}`;
1584
+ const [first] = node.via;
1585
+ return first === void 0 ? sought : `${[first.owner.name, ...node.via.map((step) => step.key)].join(".")}: ${sought}`;
1586
+ }
1587
+ }
1588
+ };
1589
+ /**
1590
+ * Where an exists starts on the judged row: the relation its path follows
1591
+ * first, or, asked of the row itself, its id, which the pointing rows hold.
1592
+ */
1593
+ const existsStart = (exists) => exists.via[0] ?? {
1594
+ owner: exists.relation.target().identity,
1595
+ key: "id"
1596
+ };
1597
+ /** A call's expansion, scalar or predicate alike. */
1598
+ const expansionOf = (call) => call.expansion;
1599
+ /**
1600
+ * What `nodes` need that an interpreter lacks: each kernel operation it does
1601
+ * not list, then each primitive operator its table does not implement, by
1602
+ * name. A defined operator needs nothing: what it means is walked instead.
1603
+ */
1604
+ const unsupportedIn = (nodes, supported, operators) => {
1605
+ const read = dependenciesOf(...nodes);
1606
+ const runs = new Set(supported);
1607
+ return [...read.operations.filter((operation) => !runs.has(operation)), ...missingFrom(read.operators, operators)];
1608
+ };
1609
+ /**
1610
+ * The primitive operators among `read` that `operators` does not implement, by
1611
+ * name. A defined one needs nothing: what it means was walked into `read`.
1612
+ */
1613
+ const missingFrom = (read, operators) => read.filter((operator) => Option.isNone(operator.definedAs) && !operators.has(operator)).map((operator) => missingName(operator, operators));
1614
+ /** An operator by its id, and its version when that is not the first. */
1615
+ const operatorName = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
1616
+ const symbols = {
1617
+ lt: "<",
1618
+ lte: "<=",
1619
+ gt: ">",
1620
+ gte: ">="
1621
+ };
1622
+ /** An operand of `and` or `or`: another connective is parenthesised, so its grouping shows. */
1623
+ const showConnected = (node) => Match.value(node).pipe(Match.tags({
1624
+ And: () => `(${showExpr(node)})`,
1625
+ Or: () => `(${showExpr(node)})`
1626
+ }), Match.orElse(() => showExpr(node)));
1627
+ const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
1628
+ export { Expr, Order, Query, dependenciesOf, isPredicate, maxPathLength, maxQueryNodes, missingName, noOperators };
1629
+
1630
+ //# sourceMappingURL=expr.js.map