@m6d/cortex 0.5.0 → 0.7.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/README.md +37 -0
- package/dist/drizzle.js +20 -20
- package/dist/{index-jw8cnjqv.js → index-j0kpmpfv.js} +32 -246
- package/dist/index.d.ts +5907 -73
- package/dist/index.js +849 -482
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -129,6 +129,35 @@ if (isFiringRunning(firing)) {
|
|
|
129
129
|
|
|
130
130
|
A firing parked on a tool that needs approval is resumed with `triggers.answer`. Until it is, a firing on the same thread (a `single` or `keyed` policy) is dropped with reason `approval_pending` (409). A status other than 2xx, 409 or 422, or a body that is no firing, throws `TriggerClientError`.
|
|
131
131
|
|
|
132
|
+
## Management API
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
import { createManagementClient, ManagementClientError, type ManagementOutput } from "@m6d/cortex";
|
|
136
|
+
|
|
137
|
+
const cortex = createManagementClient({
|
|
138
|
+
url: "https://cortex.example.com", // the console's origin
|
|
139
|
+
key: process.env.CORTEX_MANAGEMENT_KEY!, // a management key, cortex_mgmt_…
|
|
140
|
+
locale: "ar", // optional: the language Cortex words its refusals in
|
|
141
|
+
timeZone: "Asia/Dubai", // optional: the zone a day range is read in, else UTC days
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const agent: ManagementOutput<"agents.get"> = await cortex.agents.get({ id });
|
|
145
|
+
try {
|
|
146
|
+
// Each setting sent is replaced whole, so the other locales go along; the
|
|
147
|
+
// settings left out keep their values.
|
|
148
|
+
await cortex.agents.saveSettings({
|
|
149
|
+
id,
|
|
150
|
+
greeting: { ...agent.greeting, en: "How can I help?" },
|
|
151
|
+
});
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (!(error instanceof ManagementClientError)) throw error;
|
|
154
|
+
// error.status 403, error.code "FORBIDDEN", error.message "read_only",
|
|
155
|
+
// error.detail { error: "read_only", fields: [...] }, error.refusal: Cortex's sentence, when it has one
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Every procedure of [the management API](../../apps/cortex/docs/management-api.md) is a typed call, `cortex.<router>.<procedure>(input)`: a query is sent as a GET, a mutation as a POST, its input and output typed from the procedures of the Cortex release this package ships with (`ManagementInput<"…">` and `ManagementOutput<"…">` name them). A refusal throws `ManagementClientError`; a Cortex that cannot be reached rejects as `fetch` does. A server acting for many users builds a client per request, with each caller's `locale` and `timeZone`. M6d.Cortex has the same client for .NET.
|
|
160
|
+
|
|
132
161
|
## Manifests
|
|
133
162
|
|
|
134
163
|
```ts
|
|
@@ -153,6 +182,14 @@ export default defineManifest({
|
|
|
153
182
|
audience: { agents: ["support"] },
|
|
154
183
|
},
|
|
155
184
|
],
|
|
185
|
+
collections: [
|
|
186
|
+
{
|
|
187
|
+
name: "Order policies",
|
|
188
|
+
// Read from beside this file by `cortex apply`.
|
|
189
|
+
documents: [{ path: "./docs/returns.pdf" }],
|
|
190
|
+
audience: { agents: ["support"] },
|
|
191
|
+
},
|
|
192
|
+
],
|
|
156
193
|
});
|
|
157
194
|
```
|
|
158
195
|
|
package/dist/drizzle.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
FUNCTION_SIGNATURES,
|
|
2
|
+
CortexError2,
|
|
4
3
|
datasetColumnSchema,
|
|
5
|
-
filterRefs,
|
|
6
4
|
groupKeyName,
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
filterRefs,
|
|
6
|
+
isColumnValue,
|
|
7
|
+
FUNCTION_SIGNATURES
|
|
8
|
+
} from "./index-j0kpmpfv.js";
|
|
9
9
|
|
|
10
10
|
// src/datasets/drizzle.ts
|
|
11
11
|
import {
|
|
@@ -231,7 +231,7 @@ function refuseOversized(statement) {
|
|
|
231
231
|
let left = STATEMENT_MAX_PARTS;
|
|
232
232
|
const walk = (chunk) => {
|
|
233
233
|
if (--left < 0) {
|
|
234
|
-
throw new
|
|
234
|
+
throw new CortexError2("invalid_request", `The query writes out to more than ${STATEMENT_MAX_PARTS} parts of SQL; ask for fewer computed values or simpler ones`);
|
|
235
235
|
}
|
|
236
236
|
for (const part of partsOf(chunk))
|
|
237
237
|
walk(part);
|
|
@@ -254,7 +254,7 @@ function compile(root, options, query, user, clock) {
|
|
|
254
254
|
const dot = ref.lastIndexOf(".");
|
|
255
255
|
const table = joined.get(dot === -1 ? "" : ref.slice(0, dot));
|
|
256
256
|
if (!table)
|
|
257
|
-
throw new
|
|
257
|
+
throw new CortexError2("unsupported", `"${ref}" is not reachable`);
|
|
258
258
|
const name = ref.slice(dot + 1);
|
|
259
259
|
const column = columnOf(table, name);
|
|
260
260
|
const type = table.types.get(name) ?? "string";
|
|
@@ -271,13 +271,13 @@ function compile(root, options, query, user, clock) {
|
|
|
271
271
|
...query.filter.map((filter) => filterSql(dialect, filter, resolve))
|
|
272
272
|
];
|
|
273
273
|
const select = (fields) => {
|
|
274
|
-
let
|
|
274
|
+
let chain = db.select(fields).from(root.table);
|
|
275
275
|
for (const join of joins)
|
|
276
|
-
|
|
277
|
-
|
|
276
|
+
chain = chain.leftJoin(join.table, join.on);
|
|
277
|
+
chain = chain.where(and(...conditions));
|
|
278
278
|
if (shape.groupKeys.length)
|
|
279
|
-
|
|
280
|
-
return shape.having ?
|
|
279
|
+
chain = chain.groupBy(...shape.groupKeys);
|
|
280
|
+
return shape.having ? chain.having(shape.having) : chain;
|
|
281
281
|
};
|
|
282
282
|
const { chain, target } = query.rank || query.qualify.length ? finished(dialect, db, select, shape, query) : { chain: select(shape.fields), target: (name) => sortTarget(shape, name) };
|
|
283
283
|
const orderings = query.sort.map(({ col, dir }) => ordering(dialect, target(col), dir));
|
|
@@ -364,7 +364,7 @@ function joinRelations(root, join, user, db) {
|
|
|
364
364
|
const name = path.slice(dot + 1);
|
|
365
365
|
const relation = parent.relations[name];
|
|
366
366
|
if (!relation)
|
|
367
|
-
throw new
|
|
367
|
+
throw new CortexError2("unsupported", `Relation "${path}" is not declared`);
|
|
368
368
|
const { table: target, columns: targetColumns } = sourceOf(relation.dataset, `j${index}`);
|
|
369
369
|
if (relation.through) {
|
|
370
370
|
const { table: link, columns: linkColumns } = sourceOf(relation.through.dataset, `l${index}`);
|
|
@@ -441,8 +441,8 @@ function prefixes(path) {
|
|
|
441
441
|
const segments = path.split(".");
|
|
442
442
|
return segments.map((_, index) => segments.slice(0, index + 1).join("."));
|
|
443
443
|
}
|
|
444
|
-
function aliasColumns(columns,
|
|
445
|
-
const aliasedColumns = getTableColumns(
|
|
444
|
+
function aliasColumns(columns, aliased) {
|
|
445
|
+
const aliasedColumns = getTableColumns(aliased);
|
|
446
446
|
return new Map([...columns.keys()].map((name) => [name, aliasedColumns[name]]));
|
|
447
447
|
}
|
|
448
448
|
function columnOf(table, name) {
|
|
@@ -451,7 +451,7 @@ function columnOf(table, name) {
|
|
|
451
451
|
function columnIn(columns, name) {
|
|
452
452
|
const column = columns.get(name);
|
|
453
453
|
if (!column)
|
|
454
|
-
throw new
|
|
454
|
+
throw new CortexError2("unsupported", `Column "${name}" is not exposed`);
|
|
455
455
|
return column;
|
|
456
456
|
}
|
|
457
457
|
var FLOAT = { postgres: "double precision", mssql: "float", sqlite: "real" };
|
|
@@ -528,12 +528,12 @@ function meeting(parts) {
|
|
|
528
528
|
const dates = parts.filter((part) => part.type === "date");
|
|
529
529
|
const clock = dates.find((part) => part.clock !== undefined)?.clock;
|
|
530
530
|
if (clock !== undefined && dates.some((part) => part.clock === undefined)) {
|
|
531
|
-
throw new
|
|
531
|
+
throw new CortexError2("unsupported", "an instant cannot meet a calendar or truncated date; compare or combine like with like");
|
|
532
532
|
}
|
|
533
533
|
const kept = dates.flatMap((part) => part.stored ? [part.stored] : []);
|
|
534
534
|
const [stored] = kept;
|
|
535
535
|
if (stored && kept.some((other) => storageOf(other) !== storageOf(stored))) {
|
|
536
|
-
throw new
|
|
536
|
+
throw new CortexError2("unsupported", "dates kept differently (in seconds and in milliseconds, say) cannot meet; compare or combine like with like");
|
|
537
537
|
}
|
|
538
538
|
return { stored, clock };
|
|
539
539
|
}
|
|
@@ -587,7 +587,7 @@ function aggregateOf(dialect, aggregate, resolve, over) {
|
|
|
587
587
|
};
|
|
588
588
|
case "countDistinct":
|
|
589
589
|
if (over) {
|
|
590
|
-
throw new
|
|
590
|
+
throw new CortexError2("unsupported", `window "${aggregate.as}": countDistinct cannot be a window; SQL allows no DISTINCT in OVER`);
|
|
591
591
|
}
|
|
592
592
|
return { expression: countDistinct(filtered), type: "number" };
|
|
593
593
|
case "sum":
|
|
@@ -611,7 +611,7 @@ function instantOf(text, clock) {
|
|
|
611
611
|
const iso = text.replace(/^(\d{4}-\d\d-\d\d)[t ](?=\d)/, "$1T");
|
|
612
612
|
const instant = OWN_OFFSET.test(iso) ? new Date(iso) : new Date(new Date(iso.includes("T") ? `${iso}Z` : iso).getTime() - clock * 60000);
|
|
613
613
|
if (!/^[+-]?\d{4}/.test(iso) || Number.isNaN(instant.getTime())) {
|
|
614
|
-
throw new
|
|
614
|
+
throw new CortexError2("invalid_request", `"${text}" is not a date this host can read`);
|
|
615
615
|
}
|
|
616
616
|
return instant;
|
|
617
617
|
}
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// src/cortex-error.ts
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
|
-
import { bodyLimit } from "hono/body-limit";
|
|
4
|
-
|
|
5
1
|
// ../../internal/contracts/src/errors/index.ts
|
|
6
2
|
import { z } from "zod";
|
|
7
3
|
var BACKEND_ERROR_KINDS = [
|
|
@@ -31,37 +27,6 @@ function errorEnvelope(kind, detail) {
|
|
|
31
27
|
};
|
|
32
28
|
}
|
|
33
29
|
|
|
34
|
-
// src/cortex-error.ts
|
|
35
|
-
class CortexError extends Error {
|
|
36
|
-
kind;
|
|
37
|
-
constructor(kind, detail) {
|
|
38
|
-
super(detail);
|
|
39
|
-
this.kind = kind;
|
|
40
|
-
this.name = "CortexError";
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
var malformedBody = errorEnvelope("invalid_request", "Malformed request body");
|
|
44
|
-
function envelopeOf(error) {
|
|
45
|
-
if (error instanceof CortexError)
|
|
46
|
-
return errorEnvelope(error.kind, error.message);
|
|
47
|
-
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
|
48
|
-
return errorEnvelope("timeout", "The call did not finish in time");
|
|
49
|
-
}
|
|
50
|
-
return errorEnvelope("internal", "The call failed");
|
|
51
|
-
}
|
|
52
|
-
function protocolBodyLimit(maxSize) {
|
|
53
|
-
return bodyLimit({
|
|
54
|
-
maxSize,
|
|
55
|
-
onError: (c) => c.json(errorEnvelope("invalid_request", "Request body too large"), 413)
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
function contentVersion(value) {
|
|
59
|
-
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// ../../internal/contracts/src/datasets/datasets.ts
|
|
63
|
-
import { z as z2 } from "zod";
|
|
64
|
-
|
|
65
30
|
// ../../internal/contracts/src/json/index.ts
|
|
66
31
|
function isRecord(value) {
|
|
67
32
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -97,7 +62,38 @@ function readJsonPointer(document, pointer) {
|
|
|
97
62
|
return pointerTokens(pointer)?.reduce(pointerChild, document);
|
|
98
63
|
}
|
|
99
64
|
|
|
65
|
+
// src/cortex-error.ts
|
|
66
|
+
import { createHash } from "node:crypto";
|
|
67
|
+
import { bodyLimit } from "hono/body-limit";
|
|
68
|
+
class CortexError2 extends Error {
|
|
69
|
+
kind;
|
|
70
|
+
constructor(kind, detail) {
|
|
71
|
+
super(detail);
|
|
72
|
+
this.kind = kind;
|
|
73
|
+
this.name = "CortexError";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
var malformedBody = errorEnvelope("invalid_request", "Malformed request body");
|
|
77
|
+
function envelopeOf(error) {
|
|
78
|
+
if (error instanceof CortexError2)
|
|
79
|
+
return errorEnvelope(error.kind, error.message);
|
|
80
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
|
81
|
+
return errorEnvelope("timeout", "The call did not finish in time");
|
|
82
|
+
}
|
|
83
|
+
return errorEnvelope("internal", "The call failed");
|
|
84
|
+
}
|
|
85
|
+
function protocolBodyLimit(maxSize) {
|
|
86
|
+
return bodyLimit({
|
|
87
|
+
maxSize,
|
|
88
|
+
onError: (c) => c.json(errorEnvelope("invalid_request", "Request body too large"), 413)
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
function contentVersion(value) {
|
|
92
|
+
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
93
|
+
}
|
|
94
|
+
|
|
100
95
|
// ../../internal/contracts/src/datasets/datasets.ts
|
|
96
|
+
import { z as z2 } from "zod";
|
|
101
97
|
var DATASET_IDENTIFIER_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;
|
|
102
98
|
var DATASET_IDENTIFIER_MAX = 64;
|
|
103
99
|
var DATASET_COLUMN_REF_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)*$/;
|
|
@@ -934,8 +930,6 @@ function firstColumnOf(catalog, from, path) {
|
|
|
934
930
|
return dataset?.columns[0]?.name ?? "";
|
|
935
931
|
}
|
|
936
932
|
// ../../internal/contracts/src/datasets/dataset-sql.ts
|
|
937
|
-
class DatasetSqlError extends Error {
|
|
938
|
-
}
|
|
939
933
|
var AGGREGATE_WORDS = {
|
|
940
934
|
COUNT: "count",
|
|
941
935
|
SUM: "sum",
|
|
@@ -971,214 +965,6 @@ var FUNCTIONS = [
|
|
|
971
965
|
"NOW()",
|
|
972
966
|
"RANK() OVER (...)"
|
|
973
967
|
].join(", ");
|
|
974
|
-
function datasetJoinSql(from, relation, alias) {
|
|
975
|
-
const { through } = relation;
|
|
976
|
-
const target = alias ?? relation.dataset;
|
|
977
|
-
const as = alias ? ` AS ${alias}` : "";
|
|
978
|
-
if (!through) {
|
|
979
|
-
return `LEFT JOIN ${relation.dataset}${as} ON ${from}.${relation.on[0]} = ${target}.${relation.on[1]}`;
|
|
980
|
-
}
|
|
981
|
-
return [
|
|
982
|
-
`LEFT JOIN ${through.dataset} ON ${from}.${relation.on[0]} = ${through.dataset}.${relation.on[1]}`,
|
|
983
|
-
`LEFT JOIN ${relation.dataset}${as} ON ${through.dataset}.${through.on[0]} = ${target}.${through.on[1]}`
|
|
984
|
-
].join(" ");
|
|
985
|
-
}
|
|
986
|
-
function datasetJoinLines(definition) {
|
|
987
|
-
const relations = Object.entries(definition.relations);
|
|
988
|
-
const targets = relations.map(([, r]) => r.dataset);
|
|
989
|
-
return relations.map(([name, relation]) => {
|
|
990
|
-
const repeated = targets.filter((t) => t === relation.dataset).length > 1;
|
|
991
|
-
return datasetJoinSql(definition.name, relation, repeated ? name : undefined);
|
|
992
|
-
});
|
|
993
|
-
}
|
|
994
|
-
function unknownDataset(catalog, name) {
|
|
995
|
-
for (const definition of catalog.values()) {
|
|
996
|
-
for (const relation of Object.values(definition.relations)) {
|
|
997
|
-
if (relation.through?.dataset === name) {
|
|
998
|
-
return `"${name}" is the link table between "${definition.name}" and "${relation.dataset}"; start FROM one of those.`;
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
return `Unknown dataset "${name}".`;
|
|
1003
|
-
}
|
|
1004
|
-
function isLink(entry) {
|
|
1005
|
-
return "relation" in entry;
|
|
1006
|
-
}
|
|
1007
|
-
function keyOf(ref) {
|
|
1008
|
-
const parts = ref.split(".");
|
|
1009
|
-
if (parts.length !== 2) {
|
|
1010
|
-
throw new DatasetSqlError(`ON needs dataset.column on both sides; "${ref}" is not that.`);
|
|
1011
|
-
}
|
|
1012
|
-
return parts;
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
class Sources {
|
|
1016
|
-
catalog;
|
|
1017
|
-
byName = new Map;
|
|
1018
|
-
root;
|
|
1019
|
-
paths = [];
|
|
1020
|
-
matched = [];
|
|
1021
|
-
constructor(catalog, from, aliases) {
|
|
1022
|
-
this.catalog = catalog;
|
|
1023
|
-
const dataset = catalog.get(from);
|
|
1024
|
-
if (!dataset)
|
|
1025
|
-
throw new DatasetSqlError(unknownDataset(catalog, from));
|
|
1026
|
-
this.root = { path: "", dataset };
|
|
1027
|
-
for (const name of [from, ...aliases])
|
|
1028
|
-
this.name(name, this.root);
|
|
1029
|
-
}
|
|
1030
|
-
join({ dataset, alias, left, right, inner }) {
|
|
1031
|
-
const [leftQualifier, leftColumn] = keyOf(left);
|
|
1032
|
-
const [rightQualifier, rightColumn] = keyOf(right);
|
|
1033
|
-
const own = alias ?? dataset;
|
|
1034
|
-
const isNew = (qualifier) => qualifier === own;
|
|
1035
|
-
if (!isNew(leftQualifier) && !isNew(rightQualifier)) {
|
|
1036
|
-
throw new DatasetSqlError(`JOIN ${dataset} ... ON must compare a column of ${own} with a column of a dataset already in the query.`);
|
|
1037
|
-
}
|
|
1038
|
-
const [parentQualifier, parentKey, targetKey] = isNew(rightQualifier) ? [leftQualifier, leftColumn, rightColumn] : [rightQualifier, rightColumn, leftColumn];
|
|
1039
|
-
const parent = this.byName.get(parentQualifier);
|
|
1040
|
-
if (parent === undefined || parent === "ambiguous") {
|
|
1041
|
-
throw new DatasetSqlError(`"${parentQualifier}" is not in the query before JOIN ${dataset}.`);
|
|
1042
|
-
}
|
|
1043
|
-
const source = isLink(parent) ? this.completeLink(parent, dataset, parentKey, targetKey) : this.joinTo(parent, dataset, parentKey, targetKey, inner);
|
|
1044
|
-
if (isLink(parent) && parent.inner !== inner) {
|
|
1045
|
-
throw new DatasetSqlError(`JOIN ${parent.relation.through.dataset} and JOIN ${dataset} are one many-to-many join: write both as JOIN or both as LEFT JOIN.`);
|
|
1046
|
-
}
|
|
1047
|
-
this.name(own, source);
|
|
1048
|
-
if ("path" in source && inner) {
|
|
1049
|
-
this.matched.push({ col: `${source.path}.${targetKey}`, op: "isNotNull" });
|
|
1050
|
-
}
|
|
1051
|
-
}
|
|
1052
|
-
assertComplete() {
|
|
1053
|
-
for (const [qualifier, entry] of this.byName) {
|
|
1054
|
-
if (entry === "ambiguous" || !isLink(entry) || entry.completed)
|
|
1055
|
-
continue;
|
|
1056
|
-
throw new DatasetSqlError(`"${qualifier}" is only the link to "${entry.relation.dataset}"; write ${datasetJoinSql(entry.from.dataset.name, entry.relation)}.`);
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
resolve(ref) {
|
|
1060
|
-
const dot = ref.indexOf(".");
|
|
1061
|
-
if (dot === -1)
|
|
1062
|
-
return this.bareColumn(ref);
|
|
1063
|
-
const qualifier = ref.slice(0, dot);
|
|
1064
|
-
const column = ref.slice(dot + 1);
|
|
1065
|
-
if (column.includes(".")) {
|
|
1066
|
-
throw new DatasetSqlError(`"${ref}": write one JOIN per dataset and reference dataset.column.`);
|
|
1067
|
-
}
|
|
1068
|
-
const source = this.byName.get(qualifier);
|
|
1069
|
-
if (source === undefined)
|
|
1070
|
-
throw new DatasetSqlError(this.unknownQualifier(qualifier));
|
|
1071
|
-
if (source === "ambiguous") {
|
|
1072
|
-
throw new DatasetSqlError(`"${qualifier}" names more than one dataset in the query; give each JOIN its own alias.`);
|
|
1073
|
-
}
|
|
1074
|
-
if (isLink(source)) {
|
|
1075
|
-
throw new DatasetSqlError(`"${qualifier}" is a link table; read its columns from the datasets it links.`);
|
|
1076
|
-
}
|
|
1077
|
-
if (!source.dataset.columns.some((c) => c.name === column)) {
|
|
1078
|
-
throw new DatasetSqlError(unknownColumnError(source.dataset, column));
|
|
1079
|
-
}
|
|
1080
|
-
return source.path ? `${source.path}.${column}` : column;
|
|
1081
|
-
}
|
|
1082
|
-
name(qualifier, source) {
|
|
1083
|
-
this.byName.set(qualifier, this.byName.has(qualifier) ? "ambiguous" : source);
|
|
1084
|
-
}
|
|
1085
|
-
get columnNames() {
|
|
1086
|
-
return this.root.dataset.columns.map((column) => column.name);
|
|
1087
|
-
}
|
|
1088
|
-
placeOf(wireRef) {
|
|
1089
|
-
const dot = wireRef.lastIndexOf(".");
|
|
1090
|
-
if (dot === -1)
|
|
1091
|
-
return [wireRef];
|
|
1092
|
-
const path = wireRef.slice(0, dot);
|
|
1093
|
-
for (const [qualifier, entry] of this.byName) {
|
|
1094
|
-
if (entry !== "ambiguous" && !isLink(entry) && entry.path === path) {
|
|
1095
|
-
return [qualifier, wireRef.slice(dot + 1)];
|
|
1096
|
-
}
|
|
1097
|
-
}
|
|
1098
|
-
return [wireRef];
|
|
1099
|
-
}
|
|
1100
|
-
joinTo(parent, dataset, parentKey, targetKey, inner) {
|
|
1101
|
-
const candidates = Object.entries(parent.dataset.relations).filter(([, r]) => (r.through?.dataset ?? r.dataset) === dataset);
|
|
1102
|
-
if (candidates.length === 0) {
|
|
1103
|
-
throw new DatasetSqlError(`"${parent.dataset.name}" declares no join to "${dataset}". ${this.inverseOf(parent, dataset) ?? this.joinsOf(parent)}`);
|
|
1104
|
-
}
|
|
1105
|
-
const found = candidates.find(([, r]) => r.on[0] === parentKey && r.on[1] === targetKey);
|
|
1106
|
-
if (!found) {
|
|
1107
|
-
const all = datasetJoinLines(parent.dataset);
|
|
1108
|
-
const names = Object.keys(parent.dataset.relations);
|
|
1109
|
-
const lines = candidates.map(([name]) => all[names.indexOf(name)]);
|
|
1110
|
-
throw new DatasetSqlError(`"${parent.dataset.name}" reaches "${dataset}" as ${lines.join(", or ")}.`);
|
|
1111
|
-
}
|
|
1112
|
-
const [relationName, relation] = found;
|
|
1113
|
-
if (!relation.through)
|
|
1114
|
-
return this.source(parent, relationName, relation.dataset);
|
|
1115
|
-
return { from: parent, relationName, relation, inner };
|
|
1116
|
-
}
|
|
1117
|
-
completeLink(link, dataset, linkKey, targetKey) {
|
|
1118
|
-
const { relation } = link;
|
|
1119
|
-
const through = relation.through;
|
|
1120
|
-
const matches = relation.dataset === dataset && through.on[0] === linkKey && through.on[1] === targetKey;
|
|
1121
|
-
if (!matches) {
|
|
1122
|
-
throw new DatasetSqlError(`"${through.dataset}" is the link to "${relation.dataset}": ${datasetJoinSql(link.from.dataset.name, relation)}.`);
|
|
1123
|
-
}
|
|
1124
|
-
link.completed = true;
|
|
1125
|
-
return this.source(link.from, link.relationName, dataset);
|
|
1126
|
-
}
|
|
1127
|
-
source(parent, relationName, datasetName) {
|
|
1128
|
-
const dataset = this.catalog.get(datasetName);
|
|
1129
|
-
if (!dataset)
|
|
1130
|
-
throw new DatasetSqlError(`"${datasetName}" is not an exposed dataset.`);
|
|
1131
|
-
const path = parent.path ? `${parent.path}.${relationName}` : relationName;
|
|
1132
|
-
this.paths.push(path);
|
|
1133
|
-
return { path, dataset };
|
|
1134
|
-
}
|
|
1135
|
-
bareColumn(column) {
|
|
1136
|
-
const has = (source) => source.dataset.columns.some((c) => c.name === column);
|
|
1137
|
-
if (has(this.root))
|
|
1138
|
-
return column;
|
|
1139
|
-
const owners = this.sources().filter((source) => source.path && has(source));
|
|
1140
|
-
if (owners.length === 1)
|
|
1141
|
-
return `${owners[0].path}.${column}`;
|
|
1142
|
-
if (owners.length > 1) {
|
|
1143
|
-
throw new DatasetSqlError(`"${column}" is a column of ${owners.map((o) => o.dataset.name).join(" and ")}; qualify it as dataset.column.`);
|
|
1144
|
-
}
|
|
1145
|
-
const joined = this.paths.length ? " Nor does any joined dataset." : "";
|
|
1146
|
-
throw new DatasetSqlError(unknownColumnError(this.root.dataset, column) + joined);
|
|
1147
|
-
}
|
|
1148
|
-
sources() {
|
|
1149
|
-
const seen = new Set;
|
|
1150
|
-
for (const entry of this.byName.values()) {
|
|
1151
|
-
if (entry !== "ambiguous" && !isLink(entry))
|
|
1152
|
-
seen.add(entry);
|
|
1153
|
-
}
|
|
1154
|
-
return [...seen];
|
|
1155
|
-
}
|
|
1156
|
-
unknownQualifier(qualifier) {
|
|
1157
|
-
for (const source of this.sources()) {
|
|
1158
|
-
const relations = Object.entries(source.dataset.relations);
|
|
1159
|
-
const index = relations.findIndex(([name, r]) => name === qualifier || r.dataset === qualifier);
|
|
1160
|
-
if (index === -1)
|
|
1161
|
-
continue;
|
|
1162
|
-
const [, relation] = relations[index];
|
|
1163
|
-
const line = datasetJoinLines(source.dataset)[index];
|
|
1164
|
-
return this.byName.has(relation.dataset) ? `"${qualifier}" is the relation's name; reference ${relation.dataset}.column.` : `"${qualifier}" is not joined. Add ${line} and reference ${relation.dataset}.column.`;
|
|
1165
|
-
}
|
|
1166
|
-
return `"${qualifier}" is neither the dataset, a joined dataset nor an alias. ${this.joinsOf(this.root)}`;
|
|
1167
|
-
}
|
|
1168
|
-
inverseOf(parent, dataset) {
|
|
1169
|
-
const child = this.catalog.get(dataset);
|
|
1170
|
-
if (!child)
|
|
1171
|
-
return;
|
|
1172
|
-
const index = Object.values(child.relations).findIndex((r) => r.dataset === parent.dataset.name && !r.through);
|
|
1173
|
-
if (index === -1)
|
|
1174
|
-
return;
|
|
1175
|
-
return `"${dataset}" joins "${parent.dataset.name}", so start there: FROM ${dataset} ${datasetJoinLines(child)[index]}.`;
|
|
1176
|
-
}
|
|
1177
|
-
joinsOf(source) {
|
|
1178
|
-
const lines = datasetJoinLines(source.dataset);
|
|
1179
|
-
return lines.length ? `Joins "${source.dataset.name}" declares: ${lines.join("; ")}.` : `"${source.dataset.name}" declares no joins.`;
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
968
|
// ../../internal/contracts/src/datasets/dataset-sql-guide.ts
|
|
1183
969
|
var DATASET_SQL_GRAMMAR = "One SELECT over one dataset. LEFT JOIN related datasets exactly as the dataset's description lists them (LEFT JOIN keeps rows without a match; JOIN or INNER JOIN drops them); reference dataset.column. " + "SELECT: columns, DATE_TRUNC('unit', column), EXTRACT(part FROM column), CASE WHEN ... END, LOWER/UPPER/TRIM/LENGTH/ABS/ROUND/COALESCE, COUNT/SUM/AVG/MIN/MAX over a column or arithmetic each with an optional FILTER (WHERE ...), and named arithmetic between aggregates (SUM(a) / COUNT(*) AS avg). " + "WHERE and HAVING: AND, OR, NOT, parentheses, comparisons with literals or other columns, IN, BETWEEN, LIKE, IS NULL; CURRENT_DATE and INTERVAL arithmetic on it. " + "GROUP BY columns or select aliases. An aggregate with OVER () or OVER (PARTITION BY ...) is a window: that aggregate over the rows sharing the partition, on every row (SUM(COUNT(*)) OVER () is the grand total); name it AS, use it in arithmetic, and QUALIFY filters the finished rows. " + "QUALIFY RANK() OVER (PARTITION BY ... ORDER BY ...) <= n for the top n per group (rows tied on every ORDER BY key share a rank and all stay); ORDER BY; LIMIT; OFFSET. " + "Rows nest qualified columns under the qualifier as written (pets.name comes back as row.pets.name); aliases and aggregates are top-level.";
|
|
1184
|
-
export { BACKEND_ERROR_STATUS, backendErrorSchema, errorEnvelope, isRecord, readJsonPointer,
|
|
970
|
+
export { BACKEND_ERROR_STATUS, backendErrorSchema, errorEnvelope, isRecord, readJsonPointer, CortexError2, malformedBody, envelopeOf, protocolBodyLimit, contentVersion, datasetIdentifierSchema, datasetColumnSchema, datasetDefinitionSchema, DATASET_REQUEST_MAX_BYTES, datasetRequestSchema, datasetCatalogOf, groupKeyName, filterRefs, isColumnValue, checkDatasetQuery, boundDatasetResult, FUNCTION_SIGNATURES };
|