@m6d/cortex 0.2.0 → 0.3.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.
package/dist/drizzle.d.ts CHANGED
@@ -22,6 +22,7 @@ declare const datasetDefinitionSchema: z.ZodObject<{
22
22
  date: "date";
23
23
  }>;
24
24
  description: z.ZodDefault<z.ZodString>;
25
+ values: z.ZodOptional<z.ZodArray<z.ZodString>>;
25
26
  }, z.core.$strip>>;
26
27
  relations: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
27
28
  dataset: z.ZodString;
@@ -648,6 +649,11 @@ export type DrizzleDatasetOptions<TUser> = {
648
649
  exclude?: readonly string[];
649
650
  };
650
651
  descriptions?: Record<string, string>;
652
+ /**
653
+ * Every value a string column can hold, which the agent reads and a query
654
+ * may only compare it to; a column drizzle knows as an enum lists its own.
655
+ */
656
+ values?: Record<string, readonly string[]>;
651
657
  /** The dataset type of a column the table cannot describe, such as a date kept as ISO text. */
652
658
  types?: Record<string, DatasetColumnType>;
653
659
  /** Read late, so datasets may refer to each other and to themselves. */
package/dist/drizzle.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  filterRefs,
5
5
  groupKeyName,
6
6
  isColumnValue
7
- } from "./index-z0594rs3.js";
7
+ } from "./index-dck60t84.js";
8
8
 
9
9
  // src/datasets/drizzle.ts
10
10
  import {
@@ -38,6 +38,10 @@ import {
38
38
  SQL
39
39
  } from "drizzle-orm";
40
40
  import { SQLiteTimestamp } from "drizzle-orm/sqlite-core";
41
+ function enumValuesOf(column) {
42
+ const values = column.enumValues;
43
+ return values && values.length >= 1 && values.length <= 100 && values.every((value) => value.length >= 1 && value.length <= 200) ? values : undefined;
44
+ }
41
45
  function columnTypeOf(column) {
42
46
  const dataType = column.dataType;
43
47
  if (dataType.startsWith("boolean"))
@@ -123,13 +127,21 @@ function drizzleDataset(options) {
123
127
  });
124
128
  const columns = picked.flatMap(([name, column]) => {
125
129
  const type = options.types?.[name] ?? columnTypeOf(column);
126
- return type ? [
130
+ if (!type)
131
+ return [];
132
+ const declared = options.values?.[name];
133
+ if (declared && type !== "string") {
134
+ throw new Error(`Dataset "${options.name}": only a string column lists its values, and ${name} is a ${type}`);
135
+ }
136
+ const values = declared ?? enumValuesOf(column);
137
+ return [
127
138
  {
128
139
  name,
129
140
  type,
130
- description: options.descriptions?.[name] ?? ""
141
+ description: options.descriptions?.[name] ?? "",
142
+ ...type === "string" && values && { values: [...values] }
131
143
  }
132
- ] : [];
144
+ ];
133
145
  });
134
146
  const columnsByName = new Map(picked.map(([name, column]) => [name, column]));
135
147
  let definition;
@@ -66,7 +66,11 @@ var DATASET_COLUMN_TYPES = ["string", "number", "boolean", "date"];
66
66
  var datasetColumnSchema = z2.object({
67
67
  name: datasetIdentifierSchema,
68
68
  type: z2.enum(DATASET_COLUMN_TYPES),
69
- description: z2.string().max(200).default("")
69
+ description: z2.string().max(200).default(""),
70
+ values: z2.array(z2.string().min(1).max(200)).min(1).max(100).optional()
71
+ }).refine((column) => column.values === undefined || column.type === "string", {
72
+ message: "only a string column lists its values",
73
+ path: ["values"]
70
74
  });
71
75
  var datasetRelationSchema = z2.object({
72
76
  dataset: datasetIdentifierSchema,
@@ -248,9 +252,31 @@ function resolveDatasetColumn(catalog, from, ref) {
248
252
  }
249
253
  const column = dataset.columns.find((candidate) => candidate.name === columnName);
250
254
  if (!column)
251
- return missing(`"${dataset.name}" has no column "${columnName}"`);
255
+ return missing(unknownColumnError(dataset, columnName));
252
256
  return { ok: true, column, path: segments.join(".") };
253
257
  }
258
+ function unknownColumnError(dataset, name) {
259
+ const columns = dataset.columns.map((column) => column.name);
260
+ const wanted = name.toLowerCase();
261
+ const containing = columns.filter((column) => {
262
+ const lower = column.toLowerCase();
263
+ return wanted.length > 2 && lower.includes(wanted) || lower.length > 2 && wanted.includes(lower);
264
+ });
265
+ const closest = (containing.length > 0 ? containing : columns.filter((column) => Math.abs(column.length - wanted.length) <= 2 && editDistance(column.toLowerCase(), wanted) <= 2)).slice(0, 3);
266
+ const hint = closest.length > 0 ? ` Closest: ${closest.join(", ")}.` : "";
267
+ return `${dataset.name} has no column "${name}".${hint} Columns: ${columns.join(", ")}.`;
268
+ }
269
+ function editDistance(a, b) {
270
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
271
+ for (let i = 1;i <= a.length; i++) {
272
+ const current = [i];
273
+ for (let j = 1;j <= b.length; j++) {
274
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
275
+ }
276
+ previous = current;
277
+ }
278
+ return previous[b.length];
279
+ }
254
280
  function refError(kind, ref, reason) {
255
281
  return `${kind} "${ref}": ${reason}`;
256
282
  }
@@ -449,6 +475,12 @@ function validateDatasetQuery(catalog, query) {
449
475
  };
450
476
  for (const filter of query.filter)
451
477
  checkFilter(check, filter);
478
+ const row = checkAnsweredRow(check, catalog, query);
479
+ checkFinishedRow(check, query, row);
480
+ checkExpansion(check, query, catalog.get(query.from)?.columns.length ?? 0);
481
+ return issues;
482
+ }
483
+ function checkAnsweredRow(check, catalog, query) {
452
484
  const groupKeys = checkGroupBy(check, query.groupBy);
453
485
  const aliases = checkAggregates(check, query.aggregate);
454
486
  for (const alias of aliases.keys()) {
@@ -465,10 +497,15 @@ function validateDatasetQuery(catalog, query) {
465
497
  check.issue("a grouped query answers the group keys, the aggregate aliases and the computed aliases; put computed values in aggregate or compute and leave select out");
466
498
  }
467
499
  const selectAliases = checkSelect(check, query.select ?? []);
468
- const row = grouped ? { names: new Map([...groupKeys, ...aliases]), kind: "grouped" } : { names: selectAliases, kind: "plain" };
469
- checkFinishedRow(check, query, row);
470
- checkExpansion(check, query, catalog.get(query.from)?.columns.length ?? 0);
471
- return issues;
500
+ return grouped ? {
501
+ names: new Map([...groupKeys, ...aliases]),
502
+ kind: "grouped",
503
+ columns: passedColumns(catalog, query, query.groupBy)
504
+ } : {
505
+ names: selectAliases,
506
+ kind: "plain",
507
+ columns: passedColumns(catalog, query, query.select ?? [])
508
+ };
472
509
  }
473
510
  var DATASET_EXPANSION_BUDGET = 2000;
474
511
  function checkExpansion(check, query, columnCount) {
@@ -586,7 +623,7 @@ function rowScope(check, row) {
586
623
  columnOf(kind, ref) {
587
624
  const type = row.names.get(ref);
588
625
  if (type)
589
- return { name: ref, type, description: "" };
626
+ return row.columns.get(ref) ?? { name: ref, type, description: "" };
590
627
  if (row.kind === "plain")
591
628
  return check.columnOf(kind, ref);
592
629
  check.issue(refError(kind, ref, `${kind} names a group key, an aggregate alias, a window alias or a computed alias`));
@@ -803,10 +840,23 @@ function checkFilter(check, filter, kind = "filter") {
803
840
  check.issue(refError(kind, shown, `${filter.op} is not valid on a ${type} column`));
804
841
  return;
805
842
  }
806
- const issue = isColumnValue(filter.value) ? columnValueIssue(check, kind, type, filter.op, filter.value.col) : filterValueIssue(filter) ?? filterValueTypeIssue(type, filter) ?? truncatedDateIssue(filter);
843
+ const issue = isColumnValue(filter.value) ? columnValueIssue(check, kind, type, filter.op, filter.value.col) : filterValueIssue(filter) ?? filterValueTypeIssue(type, filter) ?? truncatedDateIssue(filter) ?? listedValueIssue(check, kind, filter);
807
844
  if (issue)
808
845
  check.issue(refError(kind, shown, issue));
809
846
  }
847
+ var LISTED_VALUE_OPS = new Set(["=", "!=", "in", "notIn"]);
848
+ function listedValueIssue(check, kind, filter) {
849
+ if (typeof filter.col !== "string" || !LISTED_VALUE_OPS.has(filter.op))
850
+ return;
851
+ if (filter.value === undefined || isColumnValue(filter.value))
852
+ return;
853
+ const listed = check.columnOf(kind, filter.col)?.values;
854
+ if (!listed)
855
+ return;
856
+ const values = Array.isArray(filter.value) ? filter.value : [filter.value];
857
+ const odd = values.find((value) => !listed.includes(String(value)));
858
+ return odd === undefined ? undefined : `${JSON.stringify(odd)} is not one of its values: ${listed.join(", ")}`;
859
+ }
810
860
  function truncatedDateIssue(filter) {
811
861
  const truncated = typeof filter.col === "object" && "fn" in filter.col && filter.col.fn === "dateTrunc";
812
862
  if (!truncated || filter.value === undefined || isColumnValue(filter.value))
@@ -880,6 +930,15 @@ function aggregateType(check, aggregate, label = `aggregate "${aggregate.as}"`)
880
930
  const counts = aggregate.fn === "count" || aggregate.fn === "countDistinct";
881
931
  return counts || numeric ? "number" : type ?? "number";
882
932
  }
933
+ function passedColumns(catalog, query, entries) {
934
+ return new Map(entries.flatMap((entry) => {
935
+ const [name, ref] = typeof entry === "string" ? [entry, entry] : [entry.as, entry.expr];
936
+ if (typeof ref !== "string")
937
+ return [];
938
+ const resolved = resolveDatasetColumn(catalog, query.from, ref);
939
+ return resolved.ok ? [[name, resolved.column]] : [];
940
+ }));
941
+ }
883
942
  function checkSort(check, sort, kind, row) {
884
943
  for (const { col } of sort)
885
944
  checkRowName(check, kind, col, row);
@@ -1042,6 +1101,9 @@ class Sources {
1042
1101
  if (isLink(source)) {
1043
1102
  throw new DatasetSqlError(`"${qualifier}" is a link table; read its columns from the datasets it links.`);
1044
1103
  }
1104
+ if (!source.dataset.columns.some((c) => c.name === column)) {
1105
+ throw new DatasetSqlError(unknownColumnError(source.dataset, column));
1106
+ }
1045
1107
  return source.path ? `${source.path}.${column}` : column;
1046
1108
  }
1047
1109
  name(qualifier, source) {
@@ -1107,8 +1169,8 @@ class Sources {
1107
1169
  if (owners.length > 1) {
1108
1170
  throw new DatasetSqlError(`"${column}" is a column of ${owners.map((o) => o.dataset.name).join(" and ")}; qualify it as dataset.column.`);
1109
1171
  }
1110
- const joined = this.paths.length ? " or of the joined datasets" : "";
1111
- throw new DatasetSqlError(`"${column}" is not a column of ${this.root.dataset.name}${joined}.`);
1172
+ const joined = this.paths.length ? " Nor does any joined dataset." : "";
1173
+ throw new DatasetSqlError(unknownColumnError(this.root.dataset, column) + joined);
1112
1174
  }
1113
1175
  sources() {
1114
1176
  const seen = new Set;