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
@@ -0,0 +1,765 @@
1
+ import { Match, Option, Schema, SchemaAST } from "effect";
2
+ import { own } from "./record.js";
3
+ import { absurd } from "effect/Function";
4
+ import { Collation } from "./collation.js";
5
+ import { Expr, Query, dependenciesOf, isPredicate, missingName, noOperators } from "./expr.js";
6
+ import { Held } from "./held.js";
7
+ import { Operators } from "./operators.js";
8
+ import { contextValue } from "./context.js";
9
+ // src/evaluate.ts
10
+ /**
11
+ * The reference interpreter: a query body run over rows already in memory.
12
+ *
13
+ * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body
14
+ * directly, which is what makes "source-neutral" a fact rather than a claim —
15
+ * the two are checked against each other over a real database, and a body that
16
+ * means one thing here and another there is a bug in one of them.
17
+ *
18
+ * It is also the interpreter to reach for when there is no database: a test
19
+ * that wants rows, a server assembling a page from values it already holds, or
20
+ * a client judging rows it already has.
21
+ *
22
+ * It lives in `foldkit-entity` because it is the **reference semantics** of the
23
+ * IR this package owns — what §6.0.1 means operationally rather than in prose —
24
+ * and a specification's reference implementation belongs with the
25
+ * specification. The rule that keeps it here: **it may depend on the IR and
26
+ * nothing else.** The moment it wants a Remote concept it has moved to the
27
+ * wrong place and should leave.
28
+ *
29
+ * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,
30
+ * because SQL is what the other interpreter runs. The important case is null:
31
+ * `null = null` is unknown in SQL and a row is not matched by it, where
32
+ * JavaScript would happily call the two equal.
33
+ */
34
+ var QueryEvaluateError = class extends Error {
35
+ constructor(message) {
36
+ super(`[foldkit-entity] ${message}`);
37
+ this.name = "QueryEvaluateError";
38
+ }
39
+ };
40
+ /**
41
+ * A call of a primitive operator the table does not implement. Its own class,
42
+ * because a form judging an invariant reads it as a judgement it cannot make
43
+ * (`Undecided`), not as a failure.
44
+ */
45
+ var OperatorMissingError = class extends QueryEvaluateError {
46
+ operator;
47
+ /** The operator by its id, and its version past the first. */
48
+ named;
49
+ /** `operators`, the table that lacks it, names the versions of it that it does hold. */
50
+ constructor(operator, operators = noOperators) {
51
+ super(`this interpreter does not run the operator "${missingName(operator, operators)}"`);
52
+ this.name = "OperatorMissingError";
53
+ this.operator = operator;
54
+ this.named = operatorName(operator);
55
+ }
56
+ };
57
+ /** An operator by its id, and its version when that is not the first. */
58
+ const operatorName = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
59
+ /** A run given one row: the viewer's row is another, which it does not have. */
60
+ const noRows = (entity) => new Unheld(`a path from the viewer reads a ${entity.name}, another row`);
61
+ /**
62
+ * A run that reads `Expr.viewer` or `Expr.now` and was given no context. No
63
+ * row causes it, so `evaluateEach` refuses the run rather than each row.
64
+ */
65
+ var ContextMissingError = class extends QueryEvaluateError {
66
+ constructor(term, why) {
67
+ super(`this run reads ${Expr.show(term)}, but ${why}`);
68
+ this.name = "ContextMissingError";
69
+ }
70
+ };
71
+ const contextOf = (node, scope) => {
72
+ if (scope.context === void 0) throw new ContextMissingError(node, "was given no context to read it from");
73
+ return Option.getOrThrowWith(contextValue(node, scope.context), () => new ContextMissingError(node, "its context has no reading of the time"));
74
+ };
75
+ /**
76
+ * What the interpreter does not know: a value, or a truth, that rests on
77
+ * something the holder does not have. Never a value a row holds, which is
78
+ * what lets one sit among values. SQL has no such thing; its unknown is null.
79
+ */
80
+ var Unheld = class {
81
+ reason;
82
+ constructor(reason) {
83
+ this.reason = reason;
84
+ }
85
+ };
86
+ const isUnheld = (value) => value instanceof Unheld;
87
+ /**
88
+ * One plain row, all a two-valued run is given: a key it lacks is null, as
89
+ * SQL binds a missing value, and no other row can be reached from it.
90
+ */
91
+ const flat = (row) => ({
92
+ field: (key) => own(row, key),
93
+ follow: (relation) => new Unheld(`${relation.owner.name}.${relation.key} leads to another row`),
94
+ pointing: (relation) => ({
95
+ rows: [],
96
+ missing: Option.some(`${relation.owner.name}.${relation.key} is read from other rows`)
97
+ })
98
+ });
99
+ /** A holder's row as the interpreter reads it. */
100
+ const viewOf = (row) => ({
101
+ field: (key) => Held.match(row.field(key), {
102
+ onHeld: (value) => value,
103
+ onUnheld: (reason) => new Unheld(reason)
104
+ }),
105
+ follow: (relation) => Held.match(row.follow(relation), {
106
+ onHeld: (target) => Option.match(target, {
107
+ onNone: () => null,
108
+ onSome: viewOf
109
+ }),
110
+ onUnheld: (reason) => new Unheld(reason)
111
+ }),
112
+ pointing: (relation, pinned) => {
113
+ const { rows, missing } = row.pointing(relation, pinned);
114
+ return {
115
+ rows: rows.map(viewOf),
116
+ missing
117
+ };
118
+ }
119
+ });
120
+ /** A run that is given no row: whatever it reads of one, it lacks. */
121
+ const noRow = flat({});
122
+ /**
123
+ * The row `via` reaches from `from`: null when a link is null or reaches a row
124
+ * the holder knows is not there.
125
+ */
126
+ const reached = (from, via) => {
127
+ let at = from;
128
+ for (const relation of via) {
129
+ if (at === null || isUnheld(at)) return at;
130
+ at = at.follow(relation);
131
+ }
132
+ return at;
133
+ };
134
+ /** A value two `eq`s agree on exactly, on both sides of the wire: never null, NaN or a structure. */
135
+ const pinnable = (value) => typeof value === "string" || typeof value === "boolean" || typeof value === "bigint" || typeof value === "number" && !Number.isNaN(value);
136
+ /** An `eq` of a field of the row and something else, the field first. */
137
+ const fieldAndSide = (predicate) => {
138
+ if (predicate._tag !== "Eq") return Option.none();
139
+ if (predicate.left._tag === "Field") return Option.some([predicate.left, predicate.right]);
140
+ if (predicate.right._tag === "Field") return Option.some([predicate.right, predicate.left]);
141
+ return Option.none();
142
+ };
143
+ const pinsOf = (predicates, input, context) => {
144
+ const pins = /* @__PURE__ */ new Map();
145
+ let whole = true;
146
+ const given = (node) => Match.value(node).pipe(Match.tags({
147
+ Literal: ({ value }) => Option.some(value),
148
+ Input: ({ key }) => Option.some(own(input, key)),
149
+ Viewer: (viewer) => context === void 0 ? Option.none() : contextValue(viewer, context)
150
+ }), Match.orElse(() => Option.none()));
151
+ for (const predicate of predicates) {
152
+ const pin = Option.flatMap(fieldAndSide(predicate), ([field, side]) => Option.map(Option.filter(given(side), pinnable), (value) => [field.key, value]));
153
+ if (Option.isNone(pin)) {
154
+ whole = false;
155
+ continue;
156
+ }
157
+ const [key, value] = pin.value;
158
+ if (pins.has(key) && pins.get(key) !== value) whole = false;
159
+ pins.set(key, value);
160
+ }
161
+ return {
162
+ pins,
163
+ whole
164
+ };
165
+ };
166
+ /**
167
+ * Whether some row pointing at the one `via` reaches holds the filter: true
168
+ * as soon as a held one does, false only when every one is held and none
169
+ * does. SQL's exists is never null; reached through a path that reaches no
170
+ * row, it is, as the path's field would be.
171
+ */
172
+ const exists = (node, scope) => {
173
+ const anchor = reached(scope.row, node.via);
174
+ if (anchor === null) return "unknown";
175
+ if (isUnheld(anchor)) return anchor;
176
+ const pinned = Option.match(node.where, {
177
+ onNone: () => /* @__PURE__ */ new Map(),
178
+ onSome: (where) => pinsOf(where._tag === "And" ? where.operands : [where], scope.input, scope.context).pins
179
+ });
180
+ const { rows, missing } = anchor.pointing(node.relation, pinned);
181
+ let unheld = Option.map(missing, (reason) => new Unheld(reason));
182
+ for (const row of rows) {
183
+ const truth = Option.match(node.where, {
184
+ onNone: () => true,
185
+ onSome: (where) => holds(where, {
186
+ ...scope,
187
+ row,
188
+ next: noRow
189
+ })
190
+ });
191
+ if (truth === true) return true;
192
+ if (isUnheld(truth)) unheld = Option.orElse(unheld, () => Option.some(truth));
193
+ }
194
+ return Option.getOrElse(unheld, () => false);
195
+ };
196
+ const valueOf = (node, scope) => {
197
+ switch (node._tag) {
198
+ case "Field": return scope.row.field(node.key);
199
+ case "Next": return scope.next.field(node.field.key);
200
+ case "Literal": return node.value;
201
+ case "Input": return own(scope.input, node.key);
202
+ case "Call": return called(node, scope);
203
+ case "Viewer":
204
+ case "Now": return contextOf(node, scope);
205
+ case "Path": {
206
+ const row = reached(scope.row, node.via);
207
+ return row === null || isUnheld(row) ? row : row.field(node.field.key);
208
+ }
209
+ case "ViewerPath": {
210
+ const id = contextOf(node.viewer, scope);
211
+ if (id === null) return null;
212
+ const start = scope.find(node.viewer.target(), id);
213
+ const row = start === null || isUnheld(start) ? start : reached(start, node.via);
214
+ return row === null || isUnheld(row) ? row : row.field(node.field.key);
215
+ }
216
+ default: return absurd(node);
217
+ }
218
+ };
219
+ /**
220
+ * What a run given one row could not decide without another: a path's or an
221
+ * exists' row. It refuses rather than read the others as absent, which would
222
+ * drop a row from a list on no evidence. `Judge` reads them from a holder.
223
+ */
224
+ var RowsMissingError = class extends QueryEvaluateError {
225
+ constructor(reason) {
226
+ super(`${reason}, which a run over one row cannot read; judge it with \`Judge\``);
227
+ this.name = "RowsMissingError";
228
+ }
229
+ };
230
+ /** A two-valued run's answer: what it could not decide is refused. */
231
+ const settled = (judged) => {
232
+ if (isUnheld(judged)) throw new RowsMissingError(judged.reason);
233
+ return judged;
234
+ };
235
+ /**
236
+ * What a call comes to, as a value (a predicate's truth as SQL's, unknown as
237
+ * null). A defined operator's is what it means, as SQL compiles it; a
238
+ * primitive one's is the table's implementation, or it is refused by name.
239
+ */
240
+ const called = (call, scope) => {
241
+ const expansion = call.expansion;
242
+ return Option.match(expansion, {
243
+ onSome: (body) => sideOf(body, scope),
244
+ onNone: () => Option.match(scope.operators.get(call.operator), {
245
+ onSome: (run) => ran(call, run, scope),
246
+ onNone: () => {
247
+ if (scope.judging) return new Unheld(`this holder does not run the operator "${operatorName(call.operator)}"`);
248
+ throw new OperatorMissingError(call.operator, scope.operators);
249
+ }
250
+ })
251
+ });
252
+ };
253
+ /**
254
+ * A call of a primitive operator run, its arguments worked out over the
255
+ * scope. With an argument not held it is not run: null when a strict
256
+ * operator is given a null besides, as SQL's would be, else not known.
257
+ */
258
+ const ran = (call, run, scope) => {
259
+ const values = call.args.map((arg) => sideOf(arg, scope));
260
+ const unheld = values.find(isUnheld);
261
+ if (unheld !== void 0) return call.operator.nulls === "strict" && values.some(isNull) ? null : unheld;
262
+ return runWith(call.operator, run, values, call.collation, call._tag === "Test", scope.operators.checked);
263
+ };
264
+ /**
265
+ * A primitive operator run over values: strict about null and NUL before it
266
+ * is asked, a throw it makes named as its own, and, in a checked table, its
267
+ * answer held to its output schema (a predicate's null is its unknown).
268
+ */
269
+ const runWith = (operator, run, values, collation, predicate, checked) => {
270
+ if (values.some(holdsNul)) throw new QueryEvaluateError(`the operator "${operatorName(operator)}" was given text holding a NUL character, which SQL text cannot hold portably`);
271
+ if (operator.nulls === "strict" && values.some(isNull)) return null;
272
+ let answer;
273
+ try {
274
+ answer = run(values.map((value) => value === void 0 ? null : value), { collation });
275
+ } catch (error) {
276
+ if (error instanceof QueryEvaluateError) throw error;
277
+ throw new QueryEvaluateError(`the operator "${operatorName(operator)}" failed: ${error instanceof Error ? error.message : String(error)}`);
278
+ }
279
+ 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`);
280
+ return answer;
281
+ };
282
+ /**
283
+ * A primitive operator over stored values, as a call of it is run: what a
284
+ * computed assignment comes to (`Write.apply`). Refused, as a call is, when
285
+ * `operators` does not implement it.
286
+ */
287
+ const applyOperator = (operator, values, options) => Option.match(options.operators.get(operator), {
288
+ onNone: () => {
289
+ throw new OperatorMissingError(operator, options.operators);
290
+ },
291
+ onSome: (run) => runWith(operator, run, values, options.collation, SchemaAST.isBoolean(Schema.toEncoded(operator.output).ast), options.operators.checked)
292
+ });
293
+ /** A predicate operator's answer as a truth: null is unknown, anything but a boolean refused. */
294
+ const truthOf = (call, answer) => {
295
+ if (isUnheld(answer)) return answer;
296
+ if (answer === null || answer === void 0) return "unknown";
297
+ if (typeof answer !== "boolean") throw new QueryEvaluateError(`the operator "${operatorName(call.operator)}" answered ${JSON.stringify(answer)}, which is not a truth`);
298
+ return answer;
299
+ };
300
+ const isNull = (value) => value === null || value === void 0;
301
+ const { foldAscii } = Collation;
302
+ const NUL = String.fromCharCode(0);
303
+ /**
304
+ * Whether `value` is text holding a NUL, which Postgres text cannot hold and
305
+ * SQLite compares only up to: no two interpreters agree on it.
306
+ */
307
+ const holdsNul = (value) => typeof value === "string" && value.includes(NUL);
308
+ /**
309
+ * Whether `value` is NaN, which no two interpreters agree on either: SQLite
310
+ * stores it as null, Postgres orders it after every number and equal to
311
+ * itself, JavaScript equal to nothing. Refused where values compare or
312
+ * order, as NUL is.
313
+ */
314
+ const isNaNValue = (value) => typeof value === "number" && Number.isNaN(value);
315
+ const refusedNaN = (what) => new QueryEvaluateError(`${what} was given NaN, which SQLite stores as null and Postgres orders after every number`);
316
+ /** Refuses NaN given to a comparison (a literal or an input), before a null beside it answers. */
317
+ const refuseGivenNaN = (what, sides) => {
318
+ if (sides.some(([side, value]) => !isPredicate(side) && (side._tag === "Literal" || side._tag === "Input") && isNaNValue(value))) throw refusedNaN(what);
319
+ };
320
+ /** A predicate used as a value is its own truth; anything else is its value. */
321
+ const sideOf = (node, scope) => isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope);
322
+ /**
323
+ * What an operand comes to over no row: a call of literals and inputs, run by
324
+ * `operators` (the kernel's when not given), a predicate as its truth with
325
+ * unknown as null. How a conformance check asks an implementation one
326
+ * question; refuses what `evaluate` refuses (an operator the table lacks,
327
+ * text holding NUL).
328
+ */
329
+ const valueOfOperand = (node, options = {}) => {
330
+ const value = sideOf(node, {
331
+ row: noRow,
332
+ input: options.input ?? {},
333
+ next: noRow,
334
+ operators: options.operators ?? Operators.kernel,
335
+ judging: false,
336
+ find: noRows,
337
+ context: options.context
338
+ });
339
+ if (isUnheld(value)) throw new RowsMissingError(value.reason);
340
+ return value;
341
+ };
342
+ /**
343
+ * Refuses a value the query was given (a literal or an input) holding a NUL,
344
+ * before any null beside it can answer: SQL refuses such a parameter where it
345
+ * compiles, whatever the row holds. A NUL stored in a row is refused after,
346
+ * as SQL meets it only beside a value that is not null.
347
+ */
348
+ const refuseGivenNul = (message, sides) => {
349
+ if (sides.some(([side, value]) => !isPredicate(side) && (side._tag === "Literal" || side._tag === "Input") && holdsNul(value))) throw new QueryEvaluateError(message);
350
+ };
351
+ /**
352
+ * A predicate compared as a value. SQL's unknown is null there too, so an
353
+ * unknown compared to anything stays unknown rather than becoming false.
354
+ */
355
+ const truthValue = (truth) => truth === "unknown" ? null : truth;
356
+ /**
357
+ * A predicate's truth, SQL's three values, or `Unheld` where it rests on what
358
+ * the holder lacks. A null decides before anything unheld beside it, as it
359
+ * decides SQL's answer whatever the other side holds; past that, what is not
360
+ * held is not known, except where `and`'s false or `or`'s true settles it.
361
+ */
362
+ const holds = (node, scope) => {
363
+ switch (node._tag) {
364
+ case "Exists": return exists(node, scope);
365
+ case "Test": return truthOf(node, called(node, scope));
366
+ case "Eq": {
367
+ const left = sideOf(node.left, scope);
368
+ const right = sideOf(node.right, scope);
369
+ const nul = "an equality was given text holding a NUL character, which SQL text cannot hold portably";
370
+ refuseGivenNul(nul, [[node.left, left], [node.right, right]]);
371
+ refuseGivenNaN("an equality", [[node.left, left], [node.right, right]]);
372
+ if (isNull(left) || isNull(right)) return "unknown";
373
+ if (isUnheld(left)) return left;
374
+ if (isUnheld(right)) return right;
375
+ if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul);
376
+ if (isNaNValue(left) || isNaNValue(right)) throw refusedNaN("an equality");
377
+ return left === right;
378
+ }
379
+ case "Null": {
380
+ const value = valueOf(node.operand, scope);
381
+ return isUnheld(value) ? value : isNull(value) !== node.present;
382
+ }
383
+ case "Contains": {
384
+ const value = valueOf(node.value, scope);
385
+ const search = sideOf(node.search, scope);
386
+ refuseGivenNul("a containment test was given text holding a NUL character, which SQL text cannot hold portably", [[node.search, search], [node.value, value]]);
387
+ if (isNull(value) || isNull(search)) return "unknown";
388
+ if (isUnheld(value)) return value;
389
+ if (isUnheld(search)) return search;
390
+ if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
391
+ if (holdsNul(value) || holdsNul(search)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
392
+ return foldAscii(value).includes(foldAscii(search));
393
+ }
394
+ case "In": {
395
+ const among = valueOf(node.among, scope);
396
+ if (isUnheld(among)) return among;
397
+ if (!Array.isArray(among)) throw new QueryEvaluateError("a membership test was given a list that is not a list");
398
+ if (among.length === 0) return false;
399
+ const value = valueOf(node.value, scope);
400
+ if (holdsNul(value) || among.some(holdsNul)) throw new QueryEvaluateError("a membership test was given text holding a NUL character, which SQL text cannot hold portably");
401
+ if (isNaNValue(value) || among.some(isNaNValue)) throw refusedNaN("a membership test");
402
+ if (isNull(value)) return "unknown";
403
+ if (isUnheld(value)) return value;
404
+ if (among.some((each) => each === value)) return true;
405
+ return among.some(isNull) ? "unknown" : false;
406
+ }
407
+ case "And": {
408
+ const truths = node.operands.map((operand) => holds(operand, scope));
409
+ if (truths.includes(false)) return false;
410
+ const unheld = truths.find(isUnheld);
411
+ if (unheld !== void 0) return unheld;
412
+ return truths.includes("unknown") ? "unknown" : true;
413
+ }
414
+ case "Or": {
415
+ const truths = node.operands.map((operand) => holds(operand, scope));
416
+ if (truths.includes(true)) return true;
417
+ const unheld = truths.find(isUnheld);
418
+ if (unheld !== void 0) return unheld;
419
+ return truths.includes("unknown") ? "unknown" : false;
420
+ }
421
+ case "Not": {
422
+ const truth = holds(node.operand, scope);
423
+ return truth === "unknown" || isUnheld(truth) ? truth : !truth;
424
+ }
425
+ case "Compare": {
426
+ const left = valueOf(node.left, scope);
427
+ const right = valueOf(node.right, scope);
428
+ const nul = "a comparison was given text holding a NUL character, which SQL text cannot hold portably";
429
+ refuseGivenNul(nul, [[node.left, left], [node.right, right]]);
430
+ refuseGivenNaN("a comparison", [[node.left, left], [node.right, right]]);
431
+ if (isNull(left) || isNull(right)) return "unknown";
432
+ if (isUnheld(left)) return left;
433
+ if (isUnheld(right)) return right;
434
+ if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul);
435
+ if (isNaNValue(left) || isNaNValue(right)) throw refusedNaN("a comparison");
436
+ const kind = typeof left;
437
+ if (kind !== typeof right || kind !== "number" && kind !== "string") throw new QueryEvaluateError("a comparison was given values that do not order together");
438
+ const order = compare(left, right, node.collation);
439
+ return Match.value(node.operator).pipe(Match.when("lt", () => order < 0), Match.when("lte", () => order <= 0), Match.when("gt", () => order > 0), Match.when("gte", () => order >= 0), Match.exhaustive);
440
+ }
441
+ }
442
+ };
443
+ /** What a predicate reads besides its input, asked once per node: nodes are frozen. */
444
+ const readsBeyond = /* @__PURE__ */ new WeakMap();
445
+ /**
446
+ * A predicate's truth from the input (and the context, when given) alone,
447
+ * when it reads no field; none when it reads one, or reads the context and
448
+ * none is given. An interpreter that runs per request decides such a
449
+ * predicate before it builds anything: `isNull($status)` is known before any
450
+ * row is. Refuses what `evaluate` refuses (text holding a NUL).
451
+ */
452
+ const decided = (node, input, operators = Operators.kernel, context) => {
453
+ let reads = readsBeyond.get(node);
454
+ if (reads === void 0) {
455
+ const read = dependenciesOf(node);
456
+ reads = {
457
+ field: read.fields.length + read.next.length + read.reaches.length > 0,
458
+ context: read.operations.some((operation) => operation === "viewer" || operation === "now")
459
+ };
460
+ readsBeyond.set(node, reads);
461
+ }
462
+ return reads.field || reads.context && context === void 0 ? Option.none() : Option.some(settled(holds(node, {
463
+ row: noRow,
464
+ input,
465
+ next: noRow,
466
+ operators,
467
+ judging: false,
468
+ find: noRows,
469
+ context
470
+ })));
471
+ };
472
+ /** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
473
+ const truthOver = (node, row, input = {}, next = {}, operators = Operators.kernel) => settled(holds(node, {
474
+ row: flat(row),
475
+ input,
476
+ next: flat(next),
477
+ operators,
478
+ judging: false,
479
+ find: noRows
480
+ }));
481
+ const known = (truth) => ({
482
+ _tag: "Known",
483
+ truth
484
+ });
485
+ const unknownBecause = (reason) => ({
486
+ _tag: "Unknown",
487
+ reason
488
+ });
489
+ /** How a judgement reaches a row by its id: through the holder's rows, when it was given them. */
490
+ const finder = (rows) => (entity, id) => rows === void 0 ? noRows(entity) : Held.match(rows.find(entity, id), {
491
+ onHeld: (found) => Option.match(found, {
492
+ onNone: () => null,
493
+ onSome: viewOf
494
+ }),
495
+ onUnheld: (reason) => new Unheld(reason)
496
+ });
497
+ /**
498
+ * The reference interpreter over what a holder has (`HeldRow`), three-valued:
499
+ * where an answer rests on a row or field the holder lacks or may not see, or
500
+ * on an operator only the server runs, it is unknown, and is never guessed.
501
+ * Where it is known, it is what SQL answers over the same rows: the law the
502
+ * conformance suite checks.
503
+ */
504
+ const Judge = {
505
+ /** A predicate over one held row, and, for an invariant, the row a write would leave. */
506
+ predicate: (predicate, row, options = {}) => {
507
+ const judged = holds(predicate, {
508
+ row: viewOf(row),
509
+ input: options.input ?? {},
510
+ next: options.next === void 0 ? noRow : viewOf(options.next),
511
+ operators: options.operators ?? Operators.kernel,
512
+ judging: true,
513
+ context: options.context,
514
+ find: finder(options.rows)
515
+ });
516
+ return isUnheld(judged) ? unknownBecause(judged.reason) : known(judged);
517
+ },
518
+ /**
519
+ * Whether a held row is in a query's result: known when every predicate
520
+ * holds (in) or one fails or is null (out), unknown otherwise. `serverOnly`
521
+ * names a filter the server conjoins that this holder does not run (a Read
522
+ * rule, a source's own `where`): a row the body admits is then unknown, and
523
+ * one it refuses is still out. Refuses, as `evaluate` does, a given value
524
+ * holding a NUL.
525
+ */
526
+ query: (body, input, row, options = {}) => {
527
+ if (givenUnportable(body.where, Query.dependencies(body).inputs, input)) throw new QueryEvaluateError(`query "${body.entity.name}" was given text holding a NUL character, or NaN, which no two backends agree on`);
528
+ const scope = {
529
+ row: viewOf(row),
530
+ input,
531
+ next: noRow,
532
+ operators: options.operators ?? Operators.kernel,
533
+ judging: true,
534
+ context: options.context,
535
+ find: finder(options.rows)
536
+ };
537
+ const truths = body.where.map((each) => holds(each, scope));
538
+ if (truths.some((truth) => truth === false || truth === "unknown")) return known(false);
539
+ const unheld = truths.find(isUnheld);
540
+ if (unheld !== void 0) return unknownBecause(unheld.reason);
541
+ return options.serverOnly === void 0 ? known(true) : unknownBecause(`the server also filters by ${options.serverOnly}`);
542
+ },
543
+ /**
544
+ * What a conjunction fixes by field: each `eq` of a field and a literal, an
545
+ * input or the viewer, by the field's key, and whether that is all it says
546
+ * (`whole`), so every row holding those values satisfies it. A holder holding
547
+ * every row a `whole` list's body fixes this way holds every row an exists
548
+ * whose filter fixes the same values counts.
549
+ */
550
+ pins: (predicates, options = {}) => pinsOf(predicates, options.input ?? {}, options.context),
551
+ match: (verdict, cases) => verdict._tag === "Known" ? cases.onKnown(verdict.truth) : cases.onUnknown(verdict.reason)
552
+ };
553
+ /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
554
+ const matches = (body, row, input, operators, context) => body.where.map((node) => settled(holds(node, {
555
+ row: flat(row),
556
+ input,
557
+ next: noRow,
558
+ operators,
559
+ judging: false,
560
+ find: noRows,
561
+ context
562
+ }))).every((truth) => truth === true);
563
+ /** The kinds of value this interpreter orders by; every key of one term must share one. */
564
+ const comparable = /* @__PURE__ */ new Set([
565
+ "string",
566
+ "number",
567
+ "boolean"
568
+ ]);
569
+ /**
570
+ * Text by code point, as SQLite's `BINARY` and Postgres's `"C"` compare it.
571
+ * JavaScript's `<` compares UTF-16 code units, which puts a character past
572
+ * U+FFFF (two units, the first from U+D800) before U+E000 to U+FFFF, where
573
+ * every byte-ordered backend puts it after.
574
+ */
575
+ const byCodePoint = (left, right) => {
576
+ let i = 0;
577
+ let j = 0;
578
+ while (i < left.length && j < right.length) {
579
+ const a = left.codePointAt(i);
580
+ const b = right.codePointAt(j);
581
+ if (a !== b) return a < b ? -1 : 1;
582
+ i += a > 65535 ? 2 : 1;
583
+ j += b > 65535 ? 2 : 1;
584
+ }
585
+ return i < left.length ? 1 : j < right.length ? -1 : 0;
586
+ };
587
+ /** Two keys of one term, text by its collation (code point when none is declared). */
588
+ const compare = (left, right, collation) => {
589
+ if (typeof left === "string" && typeof right === "string") return Option.exists(collation, (declared) => declared._tag === "AsciiFold") ? byCodePoint(foldAscii(left), foldAscii(right)) : byCodePoint(left, right);
590
+ if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
591
+ return left - right;
592
+ };
593
+ /** Each term's key for one row: a field's value, or what a call comes to over the row. */
594
+ const keysOf = (row, terms, scope) => terms.map((term) => {
595
+ const key = valueOf(term.expr, {
596
+ row: flat(row),
597
+ input: scope.input,
598
+ next: noRow,
599
+ operators: scope.operators,
600
+ judging: false,
601
+ find: noRows,
602
+ context: scope.context
603
+ });
604
+ if (isNaNValue(key)) throw refusedNaN(`an order by ${Expr.show(term.expr)}`);
605
+ return key;
606
+ });
607
+ /**
608
+ * Refuses an ordering this interpreter will not answer for, before sorting, so
609
+ * the refusal names the first offending row in row order rather than whichever
610
+ * pair the engine's sort happened to compare first. Every term is checked over
611
+ * every row's keys: a key whose kind differs from the first present one's. A
612
+ * null key is not refused; the term says where it goes.
613
+ */
614
+ const checkOrder = (keys, terms, query) => terms.forEach((term, index) => {
615
+ 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`);
616
+ 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`);
617
+ let first;
618
+ for (const row of keys) {
619
+ const value = row[index];
620
+ if (isNull(value)) continue;
621
+ const kind = typeof value;
622
+ first ??= kind;
623
+ if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
624
+ }
625
+ });
626
+ /** Two rows' keys by checked terms: negative when `left` sorts first. */
627
+ const byTerms = (terms, left, right) => {
628
+ for (const [index, term] of terms.entries()) {
629
+ const absentLeft = isNull(left[index]);
630
+ const absentRight = isNull(right[index]);
631
+ if (absentLeft || absentRight) {
632
+ if (absentLeft && absentRight) continue;
633
+ return absentLeft === (term.nulls === "first") ? -1 : 1;
634
+ }
635
+ const sign = compare(left[index], right[index], term.collation);
636
+ if (sign !== 0) return term.direction === "asc" ? sign : -sign;
637
+ }
638
+ return 0;
639
+ };
640
+ const ordered = (rows, terms, query, scope) => {
641
+ if (terms.length === 0) return [...rows];
642
+ const keyed = rows.map((row) => ({
643
+ row,
644
+ keys: keysOf(row, terms, scope)
645
+ }));
646
+ checkOrder(keyed.map(({ keys }) => keys), terms, query);
647
+ return keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row);
648
+ };
649
+ /**
650
+ * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),
651
+ * as `evaluate` sorts: negative when it comes first. A call among them runs
652
+ * over each row with `input` and `operators` (the kernel's when not given).
653
+ * Refuses what `evaluate` refuses, for these two rows: a term over neither a
654
+ * field nor a call, a locale collation, keys of different kinds, or an
655
+ * operator the table lacks. For a client placing one row among others it
656
+ * holds.
657
+ */
658
+ const compareRows = (terms, left, right, query, options = {}) => {
659
+ const scope = {
660
+ input: options.input ?? {},
661
+ operators: options.operators ?? Operators.kernel,
662
+ context: options.context
663
+ };
664
+ const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)];
665
+ checkOrder(keys, terms, query);
666
+ return byTerms(terms, keys[0], keys[1]);
667
+ };
668
+ /**
669
+ * The operations this interpreter runs. It is the reference, so this is the
670
+ * whole kernel — but it is declared rather than assumed, because an
671
+ * interpreter that gains an operator and forgets to say so is exactly what
672
+ * `Query.unsupported` exists to catch.
673
+ */
674
+ const supported = [
675
+ "eq",
676
+ "isNull",
677
+ "isNotNull",
678
+ "contains",
679
+ "in",
680
+ "and",
681
+ "or",
682
+ "not",
683
+ "compare",
684
+ "viewer",
685
+ "now"
686
+ ];
687
+ /**
688
+ * Refuses a body needing an operation this interpreter does not run, rather
689
+ * than skipping it and answering a different question. Called by `evaluate`;
690
+ * call it directly to check a body once instead of on every run.
691
+ */
692
+ const assertSupported = (body, operators = Operators.kernel) => {
693
+ const missing = Query.unsupported(body, supported, operators);
694
+ if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
695
+ };
696
+ /**
697
+ * The rows the body matches, in the order it asks for. Pure: it reads the rows
698
+ * it is given and nothing else.
699
+ *
700
+ * `input` holds the values this run was given, by the keys the body's
701
+ * placeholders were built with — the same record the query would be called
702
+ * with anywhere else.
703
+ */
704
+ const evaluate = (body, input, rows, options = {}) => {
705
+ const operators = options.operators ?? Operators.kernel;
706
+ const { context } = options;
707
+ assertSupported(body, operators);
708
+ return ordered(rows.filter((row) => matches(body, row, input, operators, context)), Query.orderFor(body, input), body.entity.name, {
709
+ input,
710
+ operators,
711
+ context
712
+ });
713
+ };
714
+ /**
715
+ * As `evaluate`, with each row judged alone: a row whose own values are
716
+ * refused (text holding a NUL, a value an operator fails on) is set aside in
717
+ * `refused` and the others are still answered. A client judging the rows it
718
+ * holds wants this, since one bad stored row says nothing about the rest.
719
+ *
720
+ * What no single row causes still refuses the run: an operation or operator
721
+ * the table lacks, an order by a locale collation, an input the body reads
722
+ * holding a NUL (every row would refuse, and no row is the cause), and order
723
+ * keys of different kinds across rows.
724
+ */
725
+ const evaluateEach = (body, input, rows, options = {}) => {
726
+ const operators = options.operators ?? Operators.kernel;
727
+ const { context } = options;
728
+ assertSupported(body, operators);
729
+ const terms = Query.orderFor(body, input);
730
+ const read = [...body.where, ...terms.map((term) => term.expr)];
731
+ const scope = {
732
+ input,
733
+ operators,
734
+ context
735
+ };
736
+ const keyed = [];
737
+ const refused = [];
738
+ for (const row of rows) try {
739
+ if (matches(body, row, input, operators, context)) keyed.push({
740
+ row,
741
+ keys: keysOf(row, terms, scope)
742
+ });
743
+ } catch (error) {
744
+ if (!(error instanceof QueryEvaluateError) || error instanceof ContextMissingError || givenUnportable(read, dependenciesOf(...read).inputs, input)) throw error;
745
+ refused.push(row);
746
+ }
747
+ checkOrder(keyed.map(({ keys }) => keys), terms, body.entity.name);
748
+ return {
749
+ matched: keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row),
750
+ refused
751
+ };
752
+ };
753
+ /**
754
+ * Whether a constant of `read`, or a value of `input` that `inputs` name, is
755
+ * one no two backends agree on (text holding a NUL, NaN), or a list holding
756
+ * one: every row would refuse.
757
+ */
758
+ const givenUnportable = (read, inputs, input) => Expr.givesUnportable(...read) || inputs.some((key) => {
759
+ const value = input[key];
760
+ const unportable = (each) => holdsNul(each) || isNaNValue(each);
761
+ return Array.isArray(value) ? value.some(unportable) : unportable(value);
762
+ });
763
+ export { ContextMissingError, Judge, OperatorMissingError, QueryEvaluateError, RowsMissingError, applyOperator, assertSupported, compareRows, decided, evaluate, evaluateEach, supported, truthOver, valueOfOperand };
764
+
765
+ //# sourceMappingURL=evaluate.js.map