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,33 @@
1
+ import { Option } from "effect";
2
+ import { Metadata } from "foldkit-metadata";
3
+ export type Collation =
4
+ /** By code point: SQLite `BINARY`, Postgres `COLLATE "C"`. */
5
+ {
6
+ readonly _tag: 'Binary';
7
+ } |
8
+ /** ASCII letters folded to lower case, then by code point: SQLite `NOCASE`, Postgres `lower(x COLLATE "C")`. */
9
+ {
10
+ readonly _tag: 'AsciiFold';
11
+ } |
12
+ /** The backend's collation by this name: ordered by the server, never by a client. */
13
+ {
14
+ readonly _tag: 'Locale';
15
+ readonly locale: string;
16
+ };
17
+ export declare const Collation: {
18
+ binary: Collation;
19
+ asciiFold: Collation;
20
+ locale: (locale: string) => Collation;
21
+ /** Member metadata: how a text field orders, wherever a query orders by it. */
22
+ of: (collation: Collation) => Metadata;
23
+ /** The collation a member's metadata declares, if any. */
24
+ declared: (metadata: Metadata) => Option.Option<Collation>;
25
+ /**
26
+ * Text as `asciiFold` compares it: ASCII letters lowercased, every other
27
+ * character as it is, which is what SQLite's `lower` does without ICU and so
28
+ * what compiled SQL folds to. `toLowerCase` would fold `É` to `é` here and not
29
+ * there. An operator implementing `asciiFold` folds with this.
30
+ */
31
+ foldAscii: (text: string) => string;
32
+ };
33
+ //# sourceMappingURL=collation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collation.d.ts","names":[],"sources":["../src/collation.ts"],"mappings":";;YAeY;;;WAEG;;;;WAEA;;;;WAEA;WAAyB;;qBAW3B;EACX,QAA6C;EAC7C,WAAmD;EACnD,SAAM,mBAAoB;;EAQ1B,KAAE,WAAc,cAAY;;EAG5B,WAAQ,UAAa,aAAW,OAAO,OAAO;;;;;;;EAS9C,YAAS"}
@@ -0,0 +1,46 @@
1
+ import { Option } from "effect";
2
+ import { Metadata } from "foldkit-metadata";
3
+ // src/collation.ts
4
+ /**
5
+ * How text compares when a query orders by it, declared rather than left to
6
+ * the backend. Left unsaid, SQLite compares bytes, Postgres follows the
7
+ * database's locale and a JavaScript sort follows UTF-16 code units, so the
8
+ * same body could order the same rows three ways. A declared collation is one
9
+ * every interpreter that can honour it compiles to the same order, and one
10
+ * that cannot refuses.
11
+ *
12
+ * It is a trait of a field (`Entity.annotateMembers({ title: Collation.of(
13
+ * Collation.binary) })`), so most queries declare nothing; an order term may
14
+ * override it (`Order.asc(field, { collation })`).
15
+ */
16
+ const key = Metadata.key("foldkit-entity/collation", {
17
+ merge: (collations) => collations.slice(-1),
18
+ summarize: (collation) => collation._tag
19
+ });
20
+ /** A collation name a backend can be told, and nothing that could be read as SQL. */
21
+ const localeName = /^[A-Za-z0-9_.@-]{1,64}$/;
22
+ const Collation = {
23
+ binary: Object.freeze({ _tag: "Binary" }),
24
+ asciiFold: Object.freeze({ _tag: "AsciiFold" }),
25
+ locale: (locale) => {
26
+ if (!localeName.test(locale)) throw new Error(`[foldkit-entity] Collation.locale: "${locale}" is not a collation name`);
27
+ return Object.freeze({
28
+ _tag: "Locale",
29
+ locale
30
+ });
31
+ },
32
+ /** Member metadata: how a text field orders, wherever a query orders by it. */
33
+ of: (collation) => key.of(collation),
34
+ /** The collation a member's metadata declares, if any. */
35
+ declared: (metadata) => Option.fromUndefinedOr(key.get(metadata)[0]),
36
+ /**
37
+ * Text as `asciiFold` compares it: ASCII letters lowercased, every other
38
+ * character as it is, which is what SQLite's `lower` does without ICU and so
39
+ * what compiled SQL folds to. `toLowerCase` would fold `É` to `é` here and not
40
+ * there. An operator implementing `asciiFold` folds with this.
41
+ */
42
+ foldAscii: (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase())
43
+ };
44
+ export { Collation };
45
+
46
+ //# sourceMappingURL=collation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collation.js","names":[],"sources":["../src/collation.ts"],"sourcesContent":["/**\n * How text compares when a query orders by it, declared rather than left to\n * the backend. Left unsaid, SQLite compares bytes, Postgres follows the\n * database's locale and a JavaScript sort follows UTF-16 code units, so the\n * same body could order the same rows three ways. A declared collation is one\n * every interpreter that can honour it compiles to the same order, and one\n * that cannot refuses.\n *\n * It is a trait of a field (`Entity.annotateMembers({ title: Collation.of(\n * Collation.binary) })`), so most queries declare nothing; an order term may\n * override it (`Order.asc(field, { collation })`).\n */\nimport { Option } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\n\nexport type Collation =\n /** By code point: SQLite `BINARY`, Postgres `COLLATE \"C\"`. */\n | { readonly _tag: 'Binary' }\n /** ASCII letters folded to lower case, then by code point: SQLite `NOCASE`, Postgres `lower(x COLLATE \"C\")`. */\n | { readonly _tag: 'AsciiFold' }\n /** The backend's collation by this name: ordered by the server, never by a client. */\n | { readonly _tag: 'Locale'; readonly locale: string }\n\nconst key = Metadata.key<Collation>('foldkit-entity/collation', {\n // The last collation attached wins: a later annotation refines an earlier one.\n merge: collations => collations.slice(-1),\n summarize: collation => collation._tag,\n})\n\n/** A collation name a backend can be told, and nothing that could be read as SQL. */\nconst localeName = /^[A-Za-z0-9_.@-]{1,64}$/\n\nexport const Collation = {\n binary: Object.freeze({ _tag: 'Binary' }) as Collation,\n asciiFold: Object.freeze({ _tag: 'AsciiFold' }) as Collation,\n locale: (locale: string): Collation => {\n if (!localeName.test(locale)) {\n throw new Error(`[foldkit-entity] Collation.locale: \"${locale}\" is not a collation name`)\n }\n return Object.freeze({ _tag: 'Locale', locale })\n },\n\n /** Member metadata: how a text field orders, wherever a query orders by it. */\n of: (collation: Collation): Metadata => key.of(collation),\n\n /** The collation a member's metadata declares, if any. */\n declared: (metadata: Metadata): Option.Option<Collation> =>\n Option.fromUndefinedOr(key.get(metadata)[0]),\n\n /**\n * Text as `asciiFold` compares it: ASCII letters lowercased, every other\n * character as it is, which is what SQLite's `lower` does without ICU and so\n * what compiled SQL folds to. `toLowerCase` would fold `É` to `é` here and not\n * there. An operator implementing `asciiFold` folds with this.\n */\n foldAscii: (text: string): string => text.replace(/[A-Z]+/g, upper => upper.toLowerCase()),\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAM,MAAM,SAAS,IAAe,4BAA4B;CAE9D,QAAO,eAAc,WAAW,MAAM,EAAE;CACxC,YAAW,cAAa,UAAU;AACpC,CAAC;;AAGD,MAAM,aAAa;AAEnB,MAAa,YAAY;CACvB,QAAQ,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;CACxC,WAAW,OAAO,OAAO,EAAE,MAAM,YAAY,CAAC;CAC9C,SAAS,WAA8B;EACrC,IAAI,CAAC,WAAW,KAAK,MAAM,GACzB,MAAM,IAAI,MAAM,uCAAuC,OAAO,0BAA0B;EAE1F,OAAO,OAAO,OAAO;GAAE,MAAM;GAAU;EAAO,CAAC;CACjD;;CAGA,KAAK,cAAmC,IAAI,GAAG,SAAS;;CAGxD,WAAW,aACT,OAAO,gBAAgB,IAAI,IAAI,QAAQ,CAAC,CAAC,EAAE;;;;;;;CAQ7C,YAAY,SAAyB,KAAK,QAAQ,YAAW,UAAS,MAAM,YAAY,CAAC;AAC3F"}
@@ -0,0 +1,66 @@
1
+ import { Schema } from "effect";
2
+ import { AnyQuery, Entity } from "../index.js";
3
+ export * from "./operator.js";
4
+ export * from "./relational.js";
5
+ export * from "./variants.js";
6
+ /** The one Entity every case reads, with a column of each kind that matters. */
7
+ export declare const Subject: Entity<"Subject", {
8
+ readonly id: Schema.String;
9
+ /** Mixed case on purpose: a case-blind `contains` must be caught. */
10
+ readonly label: Schema.String;
11
+ readonly rank: Schema.Number;
12
+ /** Nullable on purpose: three-valued logic has to be exercised. */
13
+ readonly tag: Schema.String;
14
+ /** Encoded and decoded forms differ on purpose: see `Timestamp`. */
15
+ readonly at: Schema.decodeTo<Schema.Date, Schema.String, never, never>;
16
+ }, {}, {}>;
17
+ /**
18
+ * How a row looks to an interpreter reading values, and to SQL as a table. The
19
+ * index signature is what lets one be read by key without a cast, which is how
20
+ * an interpreter over plain rows reads one.
21
+ */
22
+ export interface ConformanceRow {
23
+ readonly id: string;
24
+ readonly label: string;
25
+ readonly rank: number;
26
+ readonly tag: string | null;
27
+ /** The **encoded** form: what a store holds and an interpreter compares. */
28
+ readonly at: string;
29
+ readonly [key: string]: unknown;
30
+ }
31
+ export declare const rows: ReadonlyArray<ConformanceRow>;
32
+ export interface ConformanceCase {
33
+ /** What the case pins, as a sentence an interpreter fails by name. */
34
+ readonly what: string;
35
+ readonly body: AnyQuery;
36
+ /**
37
+ * The inputs, **encoded** — the space a store's rows are in, not the domain
38
+ * space the body's types describe. For every column but `at` the two are the
39
+ * same value, which is exactly why this has to be said rather than inferred
40
+ * from the fixtures.
41
+ */
42
+ readonly input: Readonly<Record<string, unknown>>;
43
+ /** The ids the body matches, in the order it asks for. */
44
+ readonly expected: ReadonlyArray<string>;
45
+ }
46
+ export declare const cases: ReadonlyArray<ConformanceCase>;
47
+ /**
48
+ * Bodies calling the kernel's primitive operators (`Text.startsWith`). An
49
+ * interpreter runs these once it implements them: the in-memory one through
50
+ * `Operators.kernel`, a compiler through its own table.
51
+ */
52
+ export declare const primitiveCases: ReadonlyArray<ConformanceCase>;
53
+ /**
54
+ * A body whose answer no two interpreters agree on, so every interpreter must
55
+ * refuse it rather than answer. Run each through yours and expect a failure.
56
+ */
57
+ export interface ConformanceRefusal {
58
+ readonly what: string;
59
+ readonly body: AnyQuery;
60
+ /** The inputs, encoded, as in `ConformanceCase`. */
61
+ readonly input: Readonly<Record<string, unknown>>;
62
+ }
63
+ export declare const refusals: ReadonlyArray<ConformanceRefusal>;
64
+ /** As `refusals`, for bodies calling the kernel's primitive operators. */
65
+ export declare const primitiveRefusals: ReadonlyArray<ConformanceRefusal>;
66
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/conformance/index.ts"],"mappings":";;;;;;qBA4Ca,SAAO;;;;;;;;;;;;;;;iBAmBH;WACN;WACA;WACA;WACA;;WAEA;YACC;;qBAGC,MAAM,cAAc;iBAQhB;;WAEN;WACA,MAAM;;;;;;;WAON,OAAO,SAAS;;WAEhB,UAAU;;qBAwCR,OAAO,cAAc;;;;;;qBAqfrB,gBAAgB,cAAc;;;;;iBA0D1B;WACN;WACA,MAAM;;WAEN,OAAO,SAAS;;qBAKd,UAAU,cAAc;;qBA0CxB,mBAAmB,cAAc"}
@@ -1,361 +1,8 @@
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
- };
1
+ import { Schema, SchemaGetter } from "effect";
2
+ import { Collation, Entity, Expr, Order, Query, Text } from "../index.js";
3
+ export * from "./operator.js";
4
+ export * from "./relational.js";
5
+ export * from "./variants.js";
359
6
  // src/conformance/index.ts
360
7
  /**
361
8
  * The conformance suite for a query body: what
@@ -1146,6 +793,21 @@ const refusals = [
1146
793
  text: `a${NUL}b`,
1147
794
  label: "b"
1148
795
  }
796
+ },
797
+ {
798
+ what: "an equality refuses NaN",
799
+ body: from.pipe(Query.where(Expr.eq(Subject.fields.rank, below)), byId),
800
+ input: { below: NaN }
801
+ },
802
+ {
803
+ what: "a comparison refuses NaN",
804
+ body: from.pipe(Query.where(Expr.gt(Subject.fields.rank, below)), byId),
805
+ input: { below: NaN }
806
+ },
807
+ {
808
+ what: "a membership test refuses a list holding NaN",
809
+ body: from.pipe(Query.where(Expr.in(Subject.fields.rank, Expr.input("ranks", Schema.Array(Schema.Number)))), byId),
810
+ input: { ranks: [1, NaN] }
1149
811
  }
1150
812
  ];
1151
813
  /** As `refusals`, for bodies calling the kernel's primitive operators. */
@@ -1154,6 +816,6 @@ const primitiveRefusals = [{
1154
816
  body: from.pipe(Query.where(Text.startsWith(Subject.fields.label, prefix, binary)), byId),
1155
817
  input: { prefix: `In${NUL}` }
1156
818
  }];
1157
- export { Conformance, LawsVerdict, Outcome, Subject, cases, primitiveCases, primitiveRefusals, refusals, rows };
819
+ export { Subject, cases, primitiveCases, primitiveRefusals, refusals, rows };
1158
820
 
1159
- //# sourceMappingURL=index.mjs.map
821
+ //# sourceMappingURL=index.js.map