@mark1russell7/vex 0.19.1 → 0.20.1

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.
package/src/evaluate.ts CHANGED
@@ -1127,6 +1127,8 @@ class Compiler {
1127
1127
  const i = okValues.indexOf(x);
1128
1128
  return i >= 0 ? ok(i) : this.#err("missing-field", `the list has no item with the value ${JSON.stringify(x)}`, f, path, { op });
1129
1129
  }
1130
+ case "includes":
1131
+ return this.#includes(rest[0], okValues, f, path);
1130
1132
  case "nth": {
1131
1133
  const i = whole();
1132
1134
  if (!i.ok) return i;
@@ -1293,6 +1295,28 @@ class Compiler {
1293
1295
  return ok(out);
1294
1296
  }
1295
1297
 
1298
+ /**
1299
+ * This method tells if an item of a list equals a value (LIST.INCLUDES). The op `eq` of the first domain that accepts
1300
+ * the value compares the value with each item, in the order of the list. The first `true` stops the walk, and the first
1301
+ * error is the result. A value without such an op gives `#NAME?`, also for an empty list.
1302
+ */
1303
+ #includes(x: unknown, values: readonly unknown[], f: Frame, path: readonly number[]): Result<boolean> {
1304
+ if (x === undefined) return this.#at(errorText.needsArgument("includes", 1), f, path);
1305
+ let op: ResolvedOp | undefined;
1306
+ for (const d of this.#domains) {
1307
+ op = safeIs(d, x) ? resolveOp(d, x, "eq") : undefined;
1308
+ if (op !== undefined) break;
1309
+ }
1310
+ if (op === undefined) return this.#at(errorText.noStep("eq", x), f, path);
1311
+ for (const item of values) {
1312
+ const r = this.#callResolved(op, x, "eq", [item], f, path);
1313
+ if (!r.ok) return r;
1314
+ if (typeof r.value !== "boolean") return this.#err("kind-mismatch", `"includes" needs a boolean from "eq", but "eq" gave a ${describeType(r.value)}`, f, path, { op: "includes" });
1315
+ if (r.value) return ok(true);
1316
+ }
1317
+ return ok(false);
1318
+ }
1319
+
1296
1320
  /**
1297
1321
  * This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
1298
1322
  * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
@@ -1327,7 +1351,7 @@ class Compiler {
1327
1351
  }
1328
1352
 
1329
1353
  /** The list ops with a second argument before their options: a count, a position, an op name or a list. */
1330
- const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf", "group", "join"]);
1354
+ const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf", "group", "join", "includes"]);
1331
1355
 
1332
1356
  /**
1333
1357
  * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
package/src/kernel.ts CHANGED
@@ -779,7 +779,7 @@ function callFound(found: Found, op: string, self: unknown, args: readonly unkno
779
779
  }
780
780
 
781
781
  /** The list ops with a second argument before their options: a count, a position, an op name or a list. */
782
- const WITH_ARGUMENT: ReadonlySet<string> = /* @__PURE__ */ new Set(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf", "group", "join"]);
782
+ const WITH_ARGUMENT: ReadonlySet<string> = /* @__PURE__ */ new Set(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf", "group", "join", "includes"]);
783
783
 
784
784
  /**
785
785
  * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
@@ -910,6 +910,8 @@ function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[]
910
910
  const i = vs.indexOf(x);
911
911
  return i >= 0 ? i : stop("missing-field", `the list has no item with the value ${JSON.stringify(x)}`);
912
912
  }
913
+ case "includes":
914
+ return includes(rest[0], vs, domains);
913
915
  case "sum":
914
916
  // Stryker disable next-line ArrayDeclaration: a sum needs no domain, and a text in the list accepts no value
915
917
  return checked(nums().reduce((s, x) => s + x, 0), op, []);
@@ -948,6 +950,22 @@ function sortValues(o: unknown, vs: readonly unknown[], domains: readonly AnyDom
948
950
  });
949
951
  }
950
952
 
953
+ /**
954
+ * This function tells if an item equals the value `x` by the op `eq` of the first domain that accepts `x`
955
+ * (LIST.INCLUDES). The walk goes in the order of the list, and it stops at the first `true` or the first error.
956
+ */
957
+ function includes(x: unknown, vs: readonly unknown[], domains: readonly AnyDomain[]): boolean {
958
+ if (x === undefined) return stop("bad-expression", '"includes" needs argument 2');
959
+ const found = domains.filter((d) => accepts(d, x)).map((d) => opOf(d, x, "eq")).find((f) => f !== undefined);
960
+ if (found === undefined) return stop("unknown-op", `no domain gives "eq" for a ${describe(x)}`);
961
+ for (const item of vs) {
962
+ const same = callFound(found, "eq", x, [item], domains);
963
+ if (typeof same !== "boolean") return stop("kind-mismatch", '"includes" needs a boolean from "eq"');
964
+ if (same) return true;
965
+ }
966
+ return false;
967
+ }
968
+
951
969
  /** This function compares two numbers or two texts for `sortBy`. Equal values keep their order (LIST.SORT). */
952
970
  const compare = (a: unknown, b: unknown): number => ((a as number) < (b as number) ? -1 : (a as number) > (b as number) ? 1 : 0);
953
971
 
package/src/list.ts CHANGED
@@ -54,15 +54,16 @@ export const isVexList = (u: unknown): u is VexList => {
54
54
  * The name of a core list op. `sortBy`, `take`, `drop`, `append`, `flat` and `without` give a list (LIST.BUILD), and
55
55
  * the other ops give a value. `get` gives the value at a key (LIST.GET), and `indexOf` gives the position of a value
56
56
  * (LIST.INDEXOF). `distinct` and `group` give a list, and `join` gives a text (LIST.DISTINCT, LIST.GROUP, LIST.JOIN).
57
- * `setNth` gives a list with a new value at one position (LIST.SETNTH).
57
+ * `setNth` gives a list with a new value at one position (LIST.SETNTH). `includes` tells if an item equals a value by
58
+ * the op `eq` of a domain (LIST.INCLUDES).
58
59
  */
59
- export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors" | "sortBy" | "take" | "nth" | "setNth" | "drop" | "append" | "flat" | "without" | "get" | "indexOf" | "distinct" | "group" | "join";
60
+ export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors" | "sortBy" | "take" | "nth" | "setNth" | "drop" | "append" | "flat" | "without" | "get" | "indexOf" | "distinct" | "group" | "join" | "includes";
60
61
 
61
62
  /**
62
63
  * The names of the core list ops. They apply when the first argument is a list. They apply to an array too, when no
63
64
  * domain and no function of the host has the op for it (LIST.ARRAY).
64
65
  */
65
- export const LIST_OPS: ReadonlySet<string> = new Set<ListOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors", "sortBy", "take", "nth", "setNth", "drop", "append", "flat", "without", "get", "indexOf", "distinct", "group", "join"]);
66
+ export const LIST_OPS: ReadonlySet<string> = new Set<ListOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors", "sortBy", "take", "nth", "setNth", "drop", "append", "flat", "without", "get", "indexOf", "distinct", "group", "join", "includes"]);
66
67
 
67
68
  /**
68
69
  * The size rules of the core list ops and of `fill` (LOOP.SIZE.OPS). Each op that gives a list has a rule here. An
@@ -78,6 +79,7 @@ export const LIST_SIZES: Readonly<Record<ListOp | "fill", SizeRule>> = Object.fr
78
79
  all: "scalar",
79
80
  none: "scalar",
80
81
  indexOf: "scalar",
82
+ includes: "scalar",
81
83
  values: { size: [1], count: [1], inner: [1], item: [1], part: [1], keys: "position" },
82
84
  keys: { size: [1], count: [1], keys: "position" },
83
85
  errors: { size: ["unbounded"] },
package/src/query.ts ADDED
@@ -0,0 +1,445 @@
1
+ /**
2
+ * The query model of flat records (QUERY.ENTRY). It holds the field catalog and the compile of a view to one program.
3
+ * It also holds the matches with the counts of the facets, the sort and the link of a view.
4
+ *
5
+ * - A record is an id and its fields. A field holds a text, a number or a boolean. A record with no value for a field has no key for it.
6
+ * - The catalog finds the fields in the records. Thus a new field in the data shows with no change to the code.
7
+ * - The programs use the ops `contains`, `lower`, `eq` and `epochMillis` of the domains of the caller. They also use `and` and `includes` of the kernel.
8
+ */
9
+ import type { AnyDomain } from "./domain.ts";
10
+ import { evaluate, isFieldName } from "./evaluate.ts";
11
+ import { app, lit, type Expr } from "./ir.ts";
12
+ import { parse, serialize } from "./json.ts";
13
+ import { space, type Space } from "./space.ts";
14
+
15
+ /** A value of a field of a record. */
16
+ export type FieldValue = string | number | boolean;
17
+
18
+ /** A flat record: its id and its fields. The id is a field too. */
19
+ export type QueryRecord = { readonly id: string } & Readonly<Record<string, FieldValue>>;
20
+
21
+ /** The type of a field. A field with values of more than one type is a `text` field, but times and dates make a `time` field. */
22
+ export type FieldType = "text" | "number" | "boolean" | "time" | "date";
23
+
24
+ /** A value of a facet and the count of the records that hold it. */
25
+ export interface FacetValue {
26
+ readonly value: string;
27
+ readonly count: number;
28
+ }
29
+
30
+ /** A field of the catalog. */
31
+ export interface FieldInfo {
32
+ readonly name: string;
33
+ readonly type: FieldType;
34
+ /** The count of the records with a value in the field. */
35
+ readonly count: number;
36
+ /** The count of the different values. */
37
+ readonly distinct: number;
38
+ /** The values of a facet, the most frequent first, then by value. A field that is not a facet has none. */
39
+ readonly values?: readonly FacetValue[];
40
+ /** True for a text field that is not a facet. The search reads it. */
41
+ readonly search: boolean;
42
+ /** The smallest value of a number, a time or a date field. Times and dates compare as texts. */
43
+ readonly min?: FieldValue;
44
+ /** The largest value of a number, a time or a date field. Times and dates compare as texts. */
45
+ readonly max?: FieldValue;
46
+ }
47
+
48
+ /** The options of the catalog. */
49
+ export interface CatalogOptions {
50
+ /** The largest count of different values of a facet. The default is 12. */
51
+ readonly maxFacet?: number;
52
+ /** The fields that the catalog leaves out. The default is `["id"]`. */
53
+ readonly skip?: readonly string[];
54
+ }
55
+
56
+ /**
57
+ * The form of a time that `epochMillis` reads: a date, a time of day, and `Z` or an offset. An example is `2026-11-18T18:47:12Z`.
58
+ * A `t` and a `z` in lower case are valid, as in RFC 3339 section 5.6.
59
+ */
60
+ export const ISO_TIME: RegExp = /^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:\d{2})$/;
61
+
62
+ /** The form of a date with no time of day, for example `2026-11-18`. */
63
+ export const ISO_DATE: RegExp = /^\d{4}-\d{2}-\d{2}$/;
64
+
65
+ const typeOfValue = (value: FieldValue): FieldType => {
66
+ if (typeof value === "number") return "number";
67
+ if (typeof value === "boolean") return "boolean";
68
+ if (ISO_TIME.test(value)) return "time";
69
+ return ISO_DATE.test(value) ? "date" : "text";
70
+ };
71
+
72
+ /** This function compares two values: numbers by value, and other values by the code units of their texts. */
73
+ const compare = (a: FieldValue, b: FieldValue): number => {
74
+ if (typeof a === "number" && typeof b === "number") return a - b;
75
+ const x = String(a);
76
+ const y = String(b);
77
+ return x < y ? -1 : x > y ? 1 : 0;
78
+ };
79
+
80
+ const isValue = (value: unknown): value is FieldValue =>
81
+ typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value));
82
+
83
+ /** This function gives the type of a field from the set of the types of its values. */
84
+ function fieldType(types: ReadonlySet<FieldType>): FieldType {
85
+ if (types.size === 2 && types.has("time") && types.has("date")) return "time";
86
+ const [only] = types;
87
+ return types.size === 1 && only !== undefined ? only : "text";
88
+ }
89
+
90
+ /**
91
+ * This function gives the catalog of the fields of the records, by the name of the field (QUERY.CATALOG).
92
+ * A field with no value in each record is not in it. A number that is not finite is no value.
93
+ * A name that a reference cannot read (`isFieldName`, REF.FORBIDDEN) is not in it, for example `__proto__`.
94
+ * The type of a field comes from the forms of its values (QUERY.CATALOG.TYPE).
95
+ * A text, a boolean or a date field with `maxFacet` or fewer different values is a facet (QUERY.CATALOG.FACET).
96
+ */
97
+ export function fieldCatalog(records: readonly QueryRecord[], options: CatalogOptions = {}): FieldInfo[] {
98
+ const maxFacet = options.maxFacet ?? 12;
99
+ const skip = new Set(options.skip ?? ["id"]);
100
+ const fields = new Map<string, { types: Set<FieldType>; counts: Map<string, number>; values: FieldValue[] }>();
101
+ for (const record of records) {
102
+ for (const [name, value] of Object.entries(record)) {
103
+ if (skip.has(name) || !isFieldName(name) || !isValue(value)) continue;
104
+ let field = fields.get(name);
105
+ if (field === undefined) fields.set(name, (field = { types: new Set(), counts: new Map(), values: [] }));
106
+ field.types.add(typeOfValue(value));
107
+ field.counts.set(String(value), (field.counts.get(String(value)) ?? 0) + 1);
108
+ field.values.push(value);
109
+ }
110
+ }
111
+ const catalog: FieldInfo[] = [];
112
+ for (const [name, field] of fields) {
113
+ const type = fieldType(field.types);
114
+ const distinct = field.counts.size;
115
+ const facet = (type === "text" || type === "boolean" || type === "date") && distinct <= maxFacet;
116
+ const ordered = type === "number" || type === "time" || type === "date";
117
+ const sorted = ordered ? field.values.toSorted(compare) : [];
118
+ const min = sorted[0];
119
+ const max = sorted.at(-1);
120
+ catalog.push({
121
+ name,
122
+ type,
123
+ count: field.values.length,
124
+ distinct,
125
+ ...(facet ? { values: [...field.counts].map(([value, count]) => ({ value, count })).toSorted((a, b) => b.count - a.count || compare(a.value, b.value)) } : {}),
126
+ search: type === "text" && !facet,
127
+ ...(min !== undefined && max !== undefined ? { min, max } : {}),
128
+ });
129
+ }
130
+ return catalog.toSorted((a, b) => compare(a.name, b.name));
131
+ }
132
+
133
+ /** The sort of a view: a field and a direction. */
134
+ export interface ViewSort {
135
+ readonly field: string;
136
+ readonly dir: "asc" | "desc";
137
+ }
138
+
139
+ /** A view of a collection of records. Each control of a page changes one field of the view. */
140
+ export interface RecordView {
141
+ /** The search words. Each word must be in the search field of a record. */
142
+ readonly text?: string;
143
+ /** The facets: the values of each field. In one field, the values are alternatives. The fields must all agree. */
144
+ readonly where?: Readonly<Record<string, readonly string[]>>;
145
+ /** An advanced filter: a program that gives a boolean at each record. */
146
+ readonly formula?: Expr;
147
+ /** The order of the matches. */
148
+ readonly sort?: ViewSort;
149
+ /** The field that groups the matches. */
150
+ readonly group?: string;
151
+ /** The way that a page shows the matches. */
152
+ readonly show?: "glow" | "only";
153
+ /** The id of the picked record. */
154
+ readonly box?: string;
155
+ }
156
+
157
+ /** The options of the compile. */
158
+ export interface CompileOptions {
159
+ /** The field of the search words. The default is `search`. */
160
+ readonly searchField?: string;
161
+ }
162
+
163
+ /** This function makes a reference to one field. A dot in the name of the field does not split it. */
164
+ const field = (name: string): Expr => ({ tag: "ref", path: [name] });
165
+
166
+ /** This function gives the words of a search text: in lower case, split at the white space, with no empty word and no repeat. */
167
+ export function searchWords(text: string): string[] {
168
+ return [...new Set(text.toLowerCase().split(/\s+/).filter((word) => word !== ""))];
169
+ }
170
+
171
+ /** This function gives the value of a facet, with the type of its field in the catalog. */
172
+ function facetValue(value: string, type: FieldType | undefined): FieldValue {
173
+ if (type === "boolean" && (value === "true" || value === "false")) return value === "true";
174
+ if (type === "number" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value);
175
+ return value;
176
+ }
177
+
178
+ /** This function gives the fields of `where` with one or more values, in the order of their names. */
179
+ const whereEntries = (view: RecordView): [string, readonly string[]][] =>
180
+ Object.entries(view.where ?? {})
181
+ .filter(([, values]) => values.length > 0)
182
+ .toSorted(([a], [b]) => compare(a, b));
183
+
184
+ /**
185
+ * This function compiles a view to one program that gives true at each record that matches (QUERY.COMPILE).
186
+ * A view with no search word, no value of a facet and no formula gives null.
187
+ * - Each search word gives `contains(lower(search), word)` (QUERY.COMPILE.SEARCH).
188
+ * - One value of a facet gives `eq(field, value)`. Two or more give `includes(values, field)` (QUERY.COMPILE.FACET).
189
+ * - The formula comes with no change. The terms make one `and`.
190
+ */
191
+ export function compileView(view: RecordView, catalog: readonly FieldInfo[], options: CompileOptions = {}): Expr | null {
192
+ const search = field(options.searchField ?? "search");
193
+ const types = new Map(catalog.map((info) => [info.name, info.type]));
194
+ const terms: Expr[] = searchWords(view.text ?? "").map((word) => app("contains", app("lower", search), lit(word)));
195
+ for (const [name, values] of whereEntries(view)) {
196
+ const each = [...new Set(values)].map((value) => facetValue(value, types.get(name)));
197
+ terms.push(each.length === 1 ? app("eq", field(name), lit(each[0])) : app("includes", lit(each), field(name)));
198
+ }
199
+ if (view.formula !== undefined) terms.push(view.formula);
200
+ if (terms.length < 2) return terms[0] ?? null;
201
+ return app("and", ...terms);
202
+ }
203
+
204
+ /** This function tells if a view has a search word, a value of a facet or a formula. */
205
+ export function isActive(view: RecordView): boolean {
206
+ return searchWords(view.text ?? "").length > 0 || view.formula !== undefined || whereEntries(view).length > 0;
207
+ }
208
+
209
+ /** The options of the matches and of the sort. */
210
+ export interface MatchOptions extends CompileOptions {
211
+ /** The domains of the evaluation. Each program evaluates at each record with them. */
212
+ readonly domains: readonly AnyDomain[];
213
+ /** The catalog of the records. The default is the catalog that `fieldCatalog` gives. */
214
+ readonly catalog?: readonly FieldInfo[];
215
+ /** The fields that get counts. The default is each facet of the catalog, in its order. */
216
+ readonly facets?: readonly string[];
217
+ }
218
+
219
+ /** The matches of a view. */
220
+ export interface MatchResult {
221
+ /** True when the view has a search word, a value of a facet or a formula (`isActive`). */
222
+ readonly active: boolean;
223
+ /** The ids of the matches, in the order of the records. A view that is not active matches each record. */
224
+ readonly matches: readonly string[];
225
+ /** For each facet, the count of each value in the records that agree with each other term of the view. */
226
+ readonly counts: ReadonlyMap<string, ReadonlyMap<string, number>>;
227
+ }
228
+
229
+ /** This function gives a space of the records, with the id of each record as its key. */
230
+ const recordSpace = (records: readonly QueryRecord[]): Space => space.record(Object.fromEntries(records.map((record) => [record.id, record])));
231
+
232
+ /**
233
+ * This function gives the matches of a view and the counts of its facets (QUERY.MATCH, QUERY.MATCH.COUNTS).
234
+ * A record matches when each program gives `true` there. An error or another value does not match.
235
+ *
236
+ * - One program holds the search words and the formula, and one program holds each field with values. Thus the matches are the matches of `compileView`.
237
+ * - The count of a value of a facet comes from the records that agree with each other program. A chosen value does not hide the other values of its facet.
238
+ */
239
+ export function matchView(view: RecordView, records: readonly QueryRecord[], options: MatchOptions): MatchResult {
240
+ const catalog = options.catalog ?? fieldCatalog(records);
241
+ const facets = options.facets ?? catalog.filter((info) => info.values !== undefined).map((info) => info.name);
242
+ const compile = (part: RecordView): Expr | null => compileView(part, catalog, options);
243
+ const base = compile({ ...(view.text === undefined ? {} : { text: view.text }), ...(view.formula === undefined ? {} : { formula: view.formula }) });
244
+ const terms = facets.map((name) => {
245
+ // Only an own field counts. Thus a facet named `__proto__` does not read the prototype.
246
+ const values = view.where !== undefined && Object.hasOwn(view.where, name) ? (view.where[name] ?? []) : [];
247
+ return values.length === 0 ? null : compile({ where: { [name]: values } });
248
+ });
249
+ // A field of `where` that is not a facet still filters the records.
250
+ const others = whereEntries(view).filter(([name]) => !facets.includes(name));
251
+ const extra = others.length === 0 ? null : compile({ where: Object.fromEntries(others) });
252
+ const keyed = recordSpace(records);
253
+ const pass = (program: Expr | null, id: string): boolean => {
254
+ if (program === null) return true;
255
+ const result = evaluate(program, { space: keyed, origin: id, domains: options.domains });
256
+ return result.ok && result.value === true;
257
+ };
258
+ const counts = new Map(facets.map((name) => [name, new Map<string, number>()]));
259
+ const matches: string[] = [];
260
+ for (const record of records) {
261
+ if (!pass(base, record.id) || !pass(extra, record.id)) continue;
262
+ const fails = terms.map((term) => !pass(term, record.id));
263
+ const failCount = fails.filter(Boolean).length;
264
+ if (failCount === 0) matches.push(record.id);
265
+ facets.forEach((name, i) => {
266
+ // A record counts for a facet when each other term holds. The term of the facet itself can fail.
267
+ if (failCount > (fails[i] === true ? 1 : 0)) return;
268
+ const value = record[name];
269
+ const count = counts.get(name);
270
+ if (count === undefined || !isValue(value)) return;
271
+ count.set(String(value), (count.get(String(value)) ?? 0) + 1);
272
+ });
273
+ }
274
+ return { active: isActive(view), matches, counts };
275
+ }
276
+
277
+ /** This function gives the key program of a sort: `epochMillis(field)` for a time or a date field, else the field (QUERY.SORT). */
278
+ export function sortKey(sort: ViewSort, catalog: readonly FieldInfo[]): Expr {
279
+ const type = catalog.find((info) => info.name === sort.field)?.type;
280
+ return type === "time" || type === "date" ? app("epochMillis", field(sort.field)) : field(sort.field);
281
+ }
282
+
283
+ /**
284
+ * This function compares two keys of a sort. Numbers compare by value. Texts compare in the order of words, with no
285
+ * case, and the numbers in them compare by value.
286
+ */
287
+ const compareKeys = (a: FieldValue, b: FieldValue): number => {
288
+ if (typeof a === "number" && typeof b === "number") return a - b;
289
+ return String(a).localeCompare(String(b), "en", { numeric: true, sensitivity: "base" });
290
+ };
291
+
292
+ /**
293
+ * This function gives the ids in the order of a sort (QUERY.SORT). The key of each record comes from `sortKey`.
294
+ * A record with no key, or with an error as its key, comes last in each direction. A tie keeps the order of the ids.
295
+ */
296
+ export function sortIds(ids: readonly string[], records: readonly QueryRecord[], sort: ViewSort, options: MatchOptions): string[] {
297
+ const key = sortKey(sort, options.catalog ?? fieldCatalog(records));
298
+ const keyed = recordSpace(records);
299
+ const sign = sort.dir === "desc" ? -1 : 1;
300
+ const rows = ids.map((id, at) => {
301
+ const result = evaluate(key, { space: keyed, origin: id, domains: options.domains });
302
+ return { id, at, key: result.ok && isValue(result.value) ? result.value : undefined };
303
+ });
304
+ return rows
305
+ .toSorted((a, b) => {
306
+ if (a.key === undefined || b.key === undefined) return a.key === b.key ? a.at - b.at : a.key === undefined ? 1 : -1;
307
+ return sign * compareKeys(a.key, b.key) || a.at - b.at;
308
+ })
309
+ .map((row) => row.id);
310
+ }
311
+
312
+ /**
313
+ * This function tells if two views have the same filter and order (QUERY.SAME). The search words must be the same.
314
+ * The values of each field must be the same, in any order. The formula and the sort must be the same.
315
+ * The group, the show and the box do not count. A view with no sort has the sort `defaultSort`.
316
+ */
317
+ export function sameFilter(a: RecordView, b: RecordView, defaultSort?: ViewSort): boolean {
318
+ const words = (v: RecordView): string => searchWords(v.text ?? "").join(" ");
319
+ const where = (v: RecordView): string =>
320
+ whereEntries(v)
321
+ .map(([name, values]) => JSON.stringify([name, [...new Set(values)].toSorted()]))
322
+ .join("\n");
323
+ const sort = (v: RecordView): string => {
324
+ const s = v.sort ?? defaultSort;
325
+ return s === undefined ? "" : `${s.dir}:${s.field}`;
326
+ };
327
+ return words(a) === words(b) && where(a) === where(b) && JSON.stringify(a.formula ?? null) === JSON.stringify(b.formula ?? null) && sort(a) === sort(b);
328
+ }
329
+
330
+ /** The keys of the link of a view that are not facets. A facet with one of these names gets the key `f.<name>`. */
331
+ export const VIEW_KEYS: readonly string[] = ["q", "sort", "group", "show", "box", "vex"];
332
+
333
+ /** The options of the link of a view. */
334
+ export interface LinkOptions {
335
+ /** The domains that write and read the domain values of the formula. */
336
+ readonly domains?: readonly AnyDomain[];
337
+ }
338
+
339
+ /** A view read from a link: the view, the parts of the link that are not of the view (with no change), and the problems. */
340
+ export interface ViewLink {
341
+ readonly view: RecordView;
342
+ /** Each part `key=value` of the link that the view does not use, in its order. Thus a newer link keeps its keys in an older page. */
343
+ readonly rest: readonly string[];
344
+ readonly problems: readonly string[];
345
+ }
346
+
347
+ // The link uses the URI functions of ECMAScript. A plus in a link is a space, as in the form encoding of HTML.
348
+ const encode = (value: string): string => encodeURIComponent(value);
349
+ const decode = (value: string): string => decodeURIComponent(value.replaceAll("+", " "));
350
+
351
+ /** This function tells if a text of the view is there and not empty. */
352
+ const filled = (value: string | undefined): value is string => value !== undefined && value !== "";
353
+
354
+ /** This function gives the key of a facet in a link. An empty name, a key of the view and a name that starts with `f.` get the prefix `f.`. */
355
+ const facetKey = (name: string): string => (name === "" || VIEW_KEYS.includes(name) || name.startsWith("f.") ? `f.${name}` : name);
356
+
357
+ /**
358
+ * This function gives the query of the link of a view, with no `?` (QUERY.LINK).
359
+ *
360
+ * - The order is `q`, the facets by name, `sort`, `group`, `show`, `box`, `vex` and the rest.
361
+ * - The different values of a facet are joined with commas. A comma in a value is encoded, so each value comes back.
362
+ * - The sort is the field, with `-` before it for the direction `desc`. A `-` at the start of the field is encoded.
363
+ * - An empty search text, sort field, group or box is not in the link.
364
+ * - The formula is `vex`, the encoded text of `serialize`. A formula that `serialize` refuses throws a `TypeError` (QUERY.LINK.FORMULA).
365
+ * - A text with a lone surrogate has no form in a link. Thus `encodeURIComponent` throws its `URIError`.
366
+ */
367
+ export function viewToQuery(view: RecordView, rest: readonly string[] = [], options: LinkOptions = {}): string {
368
+ const parts: string[] = [];
369
+ if (filled(view.text)) parts.push(`q=${encode(view.text)}`);
370
+ for (const [name, values] of whereEntries(view)) parts.push(`${encode(facetKey(name))}=${[...new Set(values)].map(encode).join(",")}`);
371
+ if (view.sort !== undefined && view.sort.field !== "") parts.push(`sort=${view.sort.dir === "desc" ? "-" : ""}${encode(view.sort.field).replace(/^-/, "%2D")}`);
372
+ if (filled(view.group)) parts.push(`group=${encode(view.group)}`);
373
+ if (view.show !== undefined) parts.push(`show=${view.show}`);
374
+ if (filled(view.box)) parts.push(`box=${encode(view.box)}`);
375
+ if (view.formula !== undefined) {
376
+ const text = serialize(view.formula, options.domains);
377
+ if (!text.ok) throw new TypeError(`The formula of the view has no JSON form: ${text.error.message}`);
378
+ parts.push(`vex=${encode(text.value)}`);
379
+ }
380
+ return [...parts, ...rest].join("&");
381
+ }
382
+
383
+ type MutableView = { -readonly [K in keyof RecordView]: RecordView[K] };
384
+
385
+ /**
386
+ * This function reads a view from the query of a link, with or without `?` (QUERY.LINK.READ). A `#` ends the query.
387
+ * A key is a facet when it is in `facets`, or when it starts with `f.`. A part with another key goes into `rest`.
388
+ * An empty value of a facet is a value, as in `URLSearchParams`. A facet named `__proto__` is a field of `where`.
389
+ * A part with a bad value is a problem, and the view does not get it. `parse` reads the formula (QUERY.LINK.FORMULA).
390
+ */
391
+ export function viewFromQuery(query: string, facets: Iterable<string>, options: LinkOptions = {}): ViewLink {
392
+ const facetNames = new Set(facets);
393
+ const problems: string[] = [];
394
+ const rest: string[] = [];
395
+ // A map keeps each name, also `__proto__`. Object.fromEntries then makes each name a field.
396
+ const where = new Map<string, string[]>();
397
+ const view: MutableView = {};
398
+ const [search = ""] = query.replace(/^\?/, "").split("#");
399
+ for (const part of search.split("&")) {
400
+ if (part === "") continue;
401
+ const at = part.indexOf("=");
402
+ const rawKey = at < 0 ? part : part.slice(0, at);
403
+ const raw = at < 0 ? "" : part.slice(at + 1);
404
+ let key: string;
405
+ try {
406
+ key = decode(rawKey);
407
+ } catch {
408
+ problems.push(`The key of the part "${part}" does not decode.`);
409
+ continue;
410
+ }
411
+ const facet = key.startsWith("f.") ? key.slice(2) : !VIEW_KEYS.includes(key) && facetNames.has(key) ? key : undefined;
412
+ try {
413
+ if (facet !== undefined) {
414
+ const values = raw.split(",").map(decode);
415
+ where.set(facet, [...new Set([...(where.get(facet) ?? []), ...values])]);
416
+ } else if (key === "q") {
417
+ const text = decode(raw);
418
+ if (text !== "") view.text = text;
419
+ } else if (key === "sort") {
420
+ // The direction is the raw `-`. An encoded `-` (`%2D`) is the start of the field.
421
+ const desc = raw.startsWith("-");
422
+ const name = decode(desc ? raw.slice(1) : raw);
423
+ if (name === "") problems.push("The sort has no field.");
424
+ else view.sort = { field: name, dir: desc ? "desc" : "asc" };
425
+ } else if (key === "show") {
426
+ const show = decode(raw);
427
+ if (show === "glow" || show === "only") view.show = show;
428
+ else problems.push(`The show "${show}" is not glow or only.`);
429
+ } else if (key === "group" || key === "box") {
430
+ const value = decode(raw);
431
+ if (value !== "") view[key] = value;
432
+ } else if (key === "vex") {
433
+ const formula = parse(decode(raw), options.domains);
434
+ if (formula.ok) view.formula = formula.value;
435
+ else problems.push(`The formula of the link is not a Vex program: ${formula.error.message}`);
436
+ } else {
437
+ rest.push(part);
438
+ }
439
+ } catch {
440
+ problems.push(`The value of "${key}" does not decode.`);
441
+ }
442
+ }
443
+ if (where.size > 0) view.where = Object.fromEntries(where);
444
+ return { view, rest, problems };
445
+ }
package/src/size.ts CHANGED
@@ -792,6 +792,7 @@ function listResult(op: ListOp | "fill", item: Kind, args: readonly Shape[]): Ki
792
792
  case "any":
793
793
  case "all":
794
794
  case "none":
795
+ case "includes":
795
796
  return BOOLEAN;
796
797
  case "join":
797
798
  return STRING;