foldkit-entity 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,362 @@
1
- import { b as Query, n as Entity, v as Expr, w as Collation, y as Order } from "../src-DwKdHZDu.mjs";
2
- import { Schema, SchemaGetter } from "effect";
3
- //#region src/conformance/index.ts
1
+ import { A as Query, D as stampTested, E as stampRun, I as Law, O as Expr, S as Evidence, T as Text, f as QueryEvaluateError, k as Order, n as Entity, w as Operators, x as valueOfOperand, z as Collation } from "../src-DBAilaDV.mjs";
2
+ import { Data, Option, Schema, SchemaAST, SchemaGetter } from "effect";
3
+ // src/conformance/operator.ts
4
+ /**
5
+ * An operator held to what it declares (expr-operations-DESIGN §10.4): its
6
+ * laws tested against an implementation, and one set of calls run through
7
+ * every implementation given, their answers and refusals compared.
8
+ *
9
+ * Cases are drawn from a fixed sample of each kind of value (text with the
10
+ * empty string, mixed case, non-ASCII and an astral character; numbers with
11
+ * zero, negatives and a fraction; both booleans), kept where the operator's
12
+ * input schema and the law's domain decode them, and chosen by a seeded
13
+ * shuffle when there are more than asked for, so a run is repeatable.
14
+ */
15
+ const Outcome = Data.taggedEnum();
16
+ const LawsVerdict = Data.taggedEnum();
17
+ const NUL$1 = String.fromCharCode(0);
18
+ const texts = [
19
+ "",
20
+ "a",
21
+ "A",
22
+ "ab",
23
+ "aB",
24
+ "b",
25
+ "B",
26
+ "é",
27
+ "É",
28
+ String.fromCodePoint(128512)
29
+ ];
30
+ const numbers = [
31
+ -2,
32
+ -1,
33
+ 0,
34
+ 1,
35
+ 2,
36
+ 7,
37
+ .5,
38
+ -.5,
39
+ 1e6
40
+ ];
41
+ const booleans = [true, false];
42
+ /** The sample values of a stored kind, before any schema narrows them. */
43
+ const candidates = (ast) => {
44
+ if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return texts;
45
+ if (SchemaAST.isNumber(ast)) return numbers;
46
+ if (SchemaAST.isBoolean(ast)) return booleans;
47
+ if (SchemaAST.isLiteral(ast)) return [ast.literal];
48
+ if (SchemaAST.isUnion(ast)) return ast.types.flatMap(candidates);
49
+ return [];
50
+ };
51
+ /** Whether a stored value is one `schema` stores. */
52
+ const decodes = (schema) => (value) => Schema.is(Schema.toEncoded(schema))(value);
53
+ /** The non-null samples every schema of `schemas` decodes, and the domain too when one is given. */
54
+ const samplesOf = (schemas, domain) => [...new Set(candidates(Schema.toEncoded(schemas[0]).ast))].filter((value) => value !== null && schemas.every((schema) => decodes(schema)(value)) && Option.match(domain, {
55
+ onNone: () => true,
56
+ onSome: (within) => decodes(within)(value)
57
+ }));
58
+ /** Every tuple of one value from each list. */
59
+ const product = (lists) => lists.reduce((tuples, list) => tuples.flatMap((tuple) => list.map((value) => [...tuple, value])), [[]]);
60
+ /** A small seeded generator (mulberry32), so a chosen subset is the same on every run. */
61
+ const random = (seed) => {
62
+ let state = seed >>> 0;
63
+ return () => {
64
+ state = state + 1831565813 >>> 0;
65
+ let t = state;
66
+ t = Math.imul(t ^ t >>> 15, t | 1);
67
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
68
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
69
+ };
70
+ };
71
+ /** At most `limit` of the tuples, a seeded shuffle choosing which when there are more. */
72
+ const chosen$1 = (tuples, limit, seed) => {
73
+ if (tuples.length <= limit) return tuples;
74
+ const next = random(seed);
75
+ const shuffled = [...tuples];
76
+ for (let i = shuffled.length - 1; i > 0; i--) {
77
+ const j = Math.floor(next() * (i + 1));
78
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
79
+ }
80
+ return shuffled.slice(0, limit);
81
+ };
82
+ /** A plain object: what JSON makes, and nothing whose data sits in a prototype. */
83
+ const isRecord = (value) => {
84
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
85
+ const prototype = Object.getPrototypeOf(value);
86
+ return prototype === Object.prototype || prototype === null;
87
+ };
88
+ /** A plain object's keys holding a value: one holding `undefined` is as absent, as JSON writes it. */
89
+ const keysOf = (record) => Object.keys(record).filter((key) => record[key] !== void 0);
90
+ /**
91
+ * Two stored values alike, structurally. Not by their JSON, which writes
92
+ * `Infinity` and `NaN` as `null`: a division by zero answering `Infinity` in
93
+ * memory and null in SQL would read as agreeing. An object that is not plain
94
+ * (its data in a prototype: a Date) is compared by its JSON, a Date's its time.
95
+ */
96
+ const sameValue = (left, right) => {
97
+ if (typeof left === "number" && typeof right === "number") return left === right || Number.isNaN(left) && Number.isNaN(right);
98
+ if (Array.isArray(left) && Array.isArray(right)) return left.length === right.length && left.every((each, i) => sameValue(each, right[i]));
99
+ if (isRecord(left) && isRecord(right)) {
100
+ const keys = keysOf(left);
101
+ return keys.length === keysOf(right).length && keys.every((key) => Object.hasOwn(right, key) && sameValue(left[key], right[key]));
102
+ }
103
+ if (typeof left === "object" && left !== null && typeof right === "object" && right !== null) return JSON.stringify(left) === JSON.stringify(right);
104
+ return left === right;
105
+ };
106
+ /** Two outcomes alike: equal values as stored, or both refusals. */
107
+ const same = (left, right) => left._tag === "Refused" || right._tag === "Refused" ? left._tag === right._tag : sameValue(left.value, right.value);
108
+ /** Text by code point, as every interpreter's `binary` orders it; `<` compares UTF-16 units. */
109
+ const byCodePoint = (left, right) => {
110
+ const [a, b] = [[...left], [...right]];
111
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
112
+ const sign = a[i].codePointAt(0) - b[i].codePointAt(0);
113
+ if (sign !== 0) return sign;
114
+ }
115
+ return a.length - b.length;
116
+ };
117
+ /** Two values of one kind in order: numbers, booleans, text by code point. */
118
+ const orderOf = (left, right) => typeof left === "string" && typeof right === "string" ? byCodePoint(left, right) : Number(left) - Number(right);
119
+ /** A call of `op`, given `collation` when its rule takes one. */
120
+ const callOf = (op, args, collation) => Option.match(collation, {
121
+ onNone: () => op(...args),
122
+ onSome: (each) => op(...args, { collation: each })
123
+ });
124
+ const foldText = (value) => typeof value === "string" ? Collation.foldAscii(value) : value;
125
+ const nameOf = (op) => op.descriptor.version === 1 ? op.descriptor.id : `${op.descriptor.id}@${op.descriptor.version}`;
126
+ /**
127
+ * The equations of every law `op` declares, over up to `limit` tuples a law
128
+ * chosen by `seed`. Nothing is run: a memory table and an SQL runner
129
+ * evaluate the same plans.
130
+ */
131
+ const lawPlans = (op, limit, seed) => {
132
+ const { descriptor } = op;
133
+ const comparesText = (each) => each.descriptor.collation !== "none";
134
+ const under = (each, collation) => comparesText(each) ? collation : Option.none();
135
+ const run = (node) => ({
136
+ node,
137
+ fold: false
138
+ });
139
+ const value = (held) => ({ value: held });
140
+ return descriptor.laws.map((law) => {
141
+ const shared = samplesOf(descriptor.input, law.domain);
142
+ const tuples = (arity) => chosen$1(product(Array.from({ length: arity }, () => shared)), limit, seed);
143
+ const plans = ([op, ...Law.$match(law, {
144
+ Inverse: ({ other }) => [other],
145
+ Distributes: ({ over }) => [over],
146
+ Associative: () => [],
147
+ Commutative: () => [],
148
+ Idempotent: () => [],
149
+ Identity: () => [],
150
+ Absorbing: () => [],
151
+ Monotonic: () => [],
152
+ PreservesCollation: () => []
153
+ })].some(comparesText) ? [Option.some(Collation.binary), Option.some(Collation.asciiFold)] : [Option.none()]).flatMap((collation) => {
154
+ const call = (...args) => callOf(op, args, under(op, collation));
155
+ const witness = (other, ...args) => callOf(other, args, under(other, collation));
156
+ const equal = (args, left, right) => ({
157
+ args,
158
+ collation,
159
+ left,
160
+ right,
161
+ holds: same
162
+ });
163
+ const sided = (witness, side, answer) => tuples(1).flatMap(([a]) => [...side === "right" ? [] : [equal([witness, a], run(call(witness, a)), value(answer(a)))], ...side === "left" ? [] : [equal([a, witness], run(call(a, witness)), value(answer(a)))]]);
164
+ return Law.$match(law, {
165
+ Associative: () => tuples(3).map(([a, b, c]) => equal([
166
+ a,
167
+ b,
168
+ c
169
+ ], run(call(call(a, b), c)), run(call(a, call(b, c))))),
170
+ Commutative: () => tuples(2).map(([a, b]) => equal([a, b], run(call(a, b)), run(call(b, a)))),
171
+ Idempotent: () => tuples(1).map(([a]) => equal([a], run(call(a, a)), value(a))),
172
+ Identity: ({ value: witness, side }) => sided(witness, side, (a) => a),
173
+ Absorbing: ({ value: witness, side }) => sided(witness, side, () => witness),
174
+ Inverse: ({ other, identity }) => tuples(1).map(([a]) => equal([a], run(call(a, witness(other, a))), value(identity))),
175
+ Distributes: ({ over }) => tuples(3).map(([a, b, c]) => equal([
176
+ a,
177
+ b,
178
+ c
179
+ ], run(call(a, witness(over, b, c))), run(witness(over, call(a, b), call(a, c))))),
180
+ Monotonic: ({ direction, position }) => {
181
+ const under = (held) => Option.exists(collation, (each) => each._tag === "AsciiFold") ? foldText(held) : held;
182
+ const order = (left, right) => orderOf(under(left), under(right));
183
+ const each = descriptor.input.map((schema) => samplesOf([schema], law.domain));
184
+ const pairs = each[position].flatMap((low) => each[position].filter((high) => order(low, high) < 0).map((high) => [low, high]));
185
+ const rest = product(each.filter((_, index) => index !== position));
186
+ const sign = direction === "increasing" ? 1 : -1;
187
+ return chosen$1(product([pairs, rest]), limit, seed).map(([pair, others]) => {
188
+ const [low, high] = pair;
189
+ const at = (held) => {
190
+ const args = [...others];
191
+ args.splice(position, 0, held);
192
+ return args;
193
+ };
194
+ return {
195
+ args: at(low),
196
+ collation,
197
+ left: run(call(...at(low))),
198
+ right: run(call(...at(high))),
199
+ holds: (left, right) => left._tag === "Value" && right._tag === "Value" && sign * order(left.value, right.value) <= 0
200
+ };
201
+ });
202
+ },
203
+ PreservesCollation: () => Option.exists(collation, (each) => each._tag === "AsciiFold") ? tuples(2).map(([a, b]) => equal([a, b], {
204
+ node: call(a, b),
205
+ fold: true
206
+ }, {
207
+ node: call(foldText(a), foldText(b)),
208
+ fold: true
209
+ })) : []
210
+ });
211
+ });
212
+ if (plans.length === 0) throw new Error(`[foldkit-entity] Conformance.laws: no sample of ${nameOf(op)}'s arguments is in ${Law.describe(law).kind}'s domain`);
213
+ return {
214
+ law: Law.describe(law),
215
+ plans
216
+ };
217
+ });
218
+ };
219
+ /**
220
+ * The verdict over laws whose calls' outcomes `answered` gives: the first
221
+ * failure, or evidence of each.
222
+ */
223
+ const verdictOf = (op, laws, answered, options) => {
224
+ const outcomes = (side) => {
225
+ if ("value" in side) return Outcome.Value({ value: side.value });
226
+ const outcome = answered(side.node);
227
+ return side.fold ? Outcome.$match(outcome, {
228
+ Value: ({ value }) => Outcome.Value({ value: foldText(value) }),
229
+ Refused: (refused) => refused
230
+ }) : outcome;
231
+ };
232
+ const evidence = [];
233
+ for (const { law, plans } of laws) {
234
+ for (const plan of plans) {
235
+ const left = outcomes(plan.left);
236
+ const right = outcomes(plan.right);
237
+ if (!plan.holds(left, right)) return LawsVerdict.Counterexample({
238
+ law,
239
+ args: plan.args,
240
+ collation: plan.collation,
241
+ left,
242
+ right
243
+ });
244
+ }
245
+ evidence.push(Evidence.Tested({
246
+ operator: nameOf(op),
247
+ law,
248
+ implementation: options.implementation,
249
+ cases: plans.length,
250
+ seed: options.seed
251
+ }));
252
+ }
253
+ return LawsVerdict.Holds({ evidence });
254
+ };
255
+ const Conformance = {
256
+ /** A runner of calls through a memory table: `Conformance.operator`'s for the in-memory interpreter. */
257
+ memory: (operators) => (call) => valueOfOperand(call, { operators }),
258
+ /**
259
+ * Tests every law `op` declares against `operators`' implementation of it,
260
+ * up to `cases` tuples a law (200 by default), chosen by `seed` (0); a law
261
+ * of both sides checks each tuple from each. Holds with a `Tested` record a
262
+ * law, which `Operators.withEvidence` keeps; or the first case a law fails,
263
+ * with both sides.
264
+ */
265
+ laws: (op, operators, options = {}) => {
266
+ const operator = op;
267
+ const seed = options.seed ?? 0;
268
+ const outcome = (node) => {
269
+ try {
270
+ return Outcome.Value({ value: valueOfOperand(node, { operators }) });
271
+ } catch (error) {
272
+ if (error instanceof QueryEvaluateError) return Outcome.Refused({ reason: error.message });
273
+ throw error;
274
+ }
275
+ };
276
+ const verdict = verdictOf(operator, lawPlans(operator, options.cases ?? 200, seed), outcome, {
277
+ implementation: options.implementation ?? "memory",
278
+ seed
279
+ });
280
+ const tested = operators.implementations.find((each) => each.operator === operator.descriptor);
281
+ if (verdict._tag === "Holds" && tested !== void 0) verdict.evidence.forEach((record) => stampTested(record, tested));
282
+ return verdict;
283
+ },
284
+ /**
285
+ * As `laws`, each call run by `run` instead of a memory table: an SQL
286
+ * implementation selected from a database, say, whose evidence a binding's
287
+ * SQL table records. A throw is a refusal.
288
+ */
289
+ lawsBy: async (op, run, options) => {
290
+ const operator = op;
291
+ const seed = options.seed ?? 0;
292
+ const laws = lawPlans(operator, options.cases ?? 200, seed);
293
+ const answers = /* @__PURE__ */ new Map();
294
+ for (const { plans } of laws) for (const side of plans.flatMap((plan) => [plan.left, plan.right])) {
295
+ if (!("node" in side) || answers.has(side.node)) continue;
296
+ try {
297
+ answers.set(side.node, Outcome.Value({ value: await run(side.node) }));
298
+ } catch (error) {
299
+ answers.set(side.node, Outcome.Refused({ reason: String(error) }));
300
+ }
301
+ }
302
+ const verdict = verdictOf(operator, laws, (node) => answers.get(node), {
303
+ implementation: options.implementation,
304
+ seed
305
+ });
306
+ if (verdict._tag === "Holds") verdict.evidence.forEach(stampRun);
307
+ return verdict;
308
+ },
309
+ /**
310
+ * Runs one set of calls of `op` through every implementation and compares
311
+ * what each answered or refused. The calls are `cases` (argument tuples, as
312
+ * stored), or generated: each argument a sample of its kind, null where its
313
+ * schema admits one, and text holding NUL, under `binary` and `asciiFold` where the operator compares
314
+ * text, up to `limit` (300) chosen by `seed` (0). A defined operator's
315
+ * expansion is run beside the others, as `expansion`, by `expansionTable`
316
+ * (the kernel's when not given).
317
+ */
318
+ operator: async (op, options) => {
319
+ const operator = op;
320
+ const { descriptor } = operator;
321
+ const runners = { ...options.implementations };
322
+ if (Option.isSome(descriptor.definedAs)) {
323
+ const table = options.expansionTable ?? Operators.kernel;
324
+ runners.expansion = (call) => valueOfOperand(Expr.expanded(call), { operators: table });
325
+ }
326
+ const generated = () => chosen$1(product(descriptor.input.map((schema) => {
327
+ const text = candidates(Schema.toEncoded(schema).ast).some((value) => typeof value === "string");
328
+ return [
329
+ ...decodes(schema)(null) ? [null] : [],
330
+ ...samplesOf([schema], Option.none()),
331
+ ...text ? [`a${NUL$1}`] : []
332
+ ];
333
+ })), options.limit ?? 300, options.seed ?? 0);
334
+ const collations = descriptor.collation === "none" ? [Option.none()] : [Option.some(Collation.binary), Option.some(Collation.asciiFold)];
335
+ const disagreements = [];
336
+ let cases = 0;
337
+ for (const args of options.cases ?? generated()) for (const collation of collations) {
338
+ cases += 1;
339
+ const call = callOf(operator, args, collation);
340
+ const outcomes = {};
341
+ for (const [name, run] of Object.entries(runners)) try {
342
+ outcomes[name] = Outcome.Value({ value: await run(call) });
343
+ } catch (error) {
344
+ outcomes[name] = Outcome.Refused({ reason: String(error) });
345
+ }
346
+ const [first, ...others] = Object.values(outcomes);
347
+ if (first !== void 0 && others.some((each) => !same(first, each))) disagreements.push({
348
+ args,
349
+ collation,
350
+ outcomes
351
+ });
352
+ }
353
+ return {
354
+ cases,
355
+ disagreements
356
+ };
357
+ }
358
+ };
359
+ // src/conformance/index.ts
4
360
  /**
5
361
  * The conformance suite for a query body: what
6
362
  * [data-query-DESIGN §6.0.1](../../../../docs/design/data-query-DESIGN.md) says
@@ -105,6 +461,17 @@ const sort = Expr.input("sort", Schema.NullOr(Schema.Struct({
105
461
  by: Schema.Literals(["rank"]),
106
462
  direction: Schema.Literals(["asc", "desc"])
107
463
  })));
464
+ /** Defined operators: an interpreter runs what each means, and needs nothing of its own. */
465
+ const tagged = Expr.operator("conformance.tagged", {
466
+ input: [Schema.Unknown],
467
+ output: Schema.Boolean,
468
+ definedAs: (value) => Expr.isNotNull(value)
469
+ });
470
+ const rankOf = Expr.operator("conformance.rankOf", {
471
+ input: [Schema.Number],
472
+ output: Schema.Number,
473
+ definedAs: (rank) => rank
474
+ });
108
475
  const chosen = Query.orderBy(Order.chosen(sort, { rank: Subject.fields.rank }), Order.asc(Subject.fields.id));
109
476
  const cases = [
110
477
  {
@@ -669,6 +1036,95 @@ const cases = [
669
1036
  "c",
670
1037
  "e"
671
1038
  ]
1039
+ },
1040
+ {
1041
+ what: "a defined operator matches the rows what it means does",
1042
+ body: from.pipe(Query.where(tagged(Subject.fields.tag)), byId),
1043
+ input: {},
1044
+ expected: [
1045
+ "b",
1046
+ "d",
1047
+ "e"
1048
+ ]
1049
+ },
1050
+ {
1051
+ what: "a defined operator under not is the negation of what it means",
1052
+ body: from.pipe(Query.where(Expr.not(tagged(Subject.fields.tag))), byId),
1053
+ input: {},
1054
+ expected: ["a", "c"]
1055
+ },
1056
+ {
1057
+ what: "a defined operator over an input only is decided by the request",
1058
+ body: from.pipe(Query.where(Expr.or(tagged(maybeTag), Expr.eq(Subject.fields.rank, 3))), byId),
1059
+ input: { maybeTag: null },
1060
+ expected: ["c", "d"]
1061
+ },
1062
+ {
1063
+ what: "a defined scalar operator compares as what it means",
1064
+ body: from.pipe(Query.where(Expr.eq(rankOf(Subject.fields.rank), 3)), byId),
1065
+ input: {},
1066
+ expected: ["c", "d"]
1067
+ }
1068
+ ];
1069
+ const prefix = Expr.input("prefix", Schema.NullOr(Schema.String));
1070
+ const asciiFold = { collation: Collation.asciiFold };
1071
+ /**
1072
+ * Bodies calling the kernel's primitive operators (`Text.startsWith`). An
1073
+ * interpreter runs these once it implements them: the in-memory one through
1074
+ * `Operators.kernel`, a compiler through its own table.
1075
+ */
1076
+ const primitiveCases = [
1077
+ {
1078
+ what: "startsWith under binary is exact about case",
1079
+ body: from.pipe(Query.where(Text.startsWith(Subject.fields.label, "In", binary)), byId),
1080
+ input: {},
1081
+ expected: ["a"]
1082
+ },
1083
+ {
1084
+ what: "startsWith under asciiFold folds ASCII case on both sides",
1085
+ body: from.pipe(Query.where(Text.startsWith(Subject.fields.label, "IN", asciiFold)), byId),
1086
+ input: {},
1087
+ expected: ["a", "b"]
1088
+ },
1089
+ {
1090
+ what: "startsWith the empty prefix holds for every row with text",
1091
+ body: from.pipe(Query.where(Text.startsWith(Subject.fields.label, prefix, binary)), byId),
1092
+ input: { prefix: "" },
1093
+ expected: [
1094
+ "a",
1095
+ "b",
1096
+ "c",
1097
+ "d",
1098
+ "e"
1099
+ ]
1100
+ },
1101
+ {
1102
+ what: "startsWith over null text is unknown, so its rows are not matched",
1103
+ body: from.pipe(Query.where(Text.startsWith(Subject.fields.tag, "", binary)), byId),
1104
+ input: {},
1105
+ expected: [
1106
+ "b",
1107
+ "d",
1108
+ "e"
1109
+ ]
1110
+ },
1111
+ {
1112
+ what: "startsWith a null prefix is unknown for every row",
1113
+ body: from.pipe(Query.where(Text.startsWith(Subject.fields.label, prefix, binary)), byId),
1114
+ input: { prefix: null },
1115
+ expected: []
1116
+ },
1117
+ {
1118
+ what: "startsWith reads % and _ as characters, never as like wildcards",
1119
+ body: from.pipe(Query.where(Expr.or(Text.startsWith(Subject.fields.label, "100%", binary), Text.startsWith(Subject.fields.label, "sn_", binary), Text.startsWith(Subject.fields.label, "O%", binary))), byId),
1120
+ input: {},
1121
+ expected: ["d"]
1122
+ },
1123
+ {
1124
+ what: "startsWith under not keeps a null unknown",
1125
+ body: from.pipe(Query.where(Expr.not(Text.startsWith(Subject.fields.tag, "x", binary))), byId),
1126
+ input: {},
1127
+ expected: ["e"]
672
1128
  }
673
1129
  ];
674
1130
  const NUL = String.fromCharCode(0);
@@ -692,7 +1148,12 @@ const refusals = [
692
1148
  }
693
1149
  }
694
1150
  ];
695
- //#endregion
696
- export { Subject, cases, refusals, rows };
1151
+ /** As `refusals`, for bodies calling the kernel's primitive operators. */
1152
+ const primitiveRefusals = [{
1153
+ what: "startsWith refuses a prefix holding NUL",
1154
+ body: from.pipe(Query.where(Text.startsWith(Subject.fields.label, prefix, binary)), byId),
1155
+ input: { prefix: `In${NUL}` }
1156
+ }];
1157
+ export { Conformance, LawsVerdict, Outcome, Subject, cases, primitiveCases, primitiveRefusals, refusals, rows };
697
1158
 
698
1159
  //# sourceMappingURL=index.mjs.map