@m6d/cortex 0.13.1 → 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.
- package/README.md +39 -8
- package/dist/drizzle.d.ts +15 -3
- package/dist/drizzle.js +35 -10
- package/dist/{index-j0kpmpfv.js → index-ycr8n8r9.js} +88 -121
- package/dist/index.d.ts +45570 -4328
- package/dist/index.js +1254 -1079
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -30,21 +30,24 @@ export const cortexServer = defineServer({
|
|
|
30
30
|
description: "Display name of the signed-in user",
|
|
31
31
|
example: "Sara",
|
|
32
32
|
type: "string",
|
|
33
|
-
|
|
33
|
+
// Every handler also gets the request it came in and a signal that aborts on disconnect.
|
|
34
|
+
resolve: ({ user, token }, { signal }) => lookUpName(user?.id, token, signal),
|
|
34
35
|
},
|
|
35
36
|
},
|
|
36
37
|
tools: {
|
|
37
38
|
cancelOrder: {
|
|
38
39
|
description: "Cancel one of the user's open orders.",
|
|
39
40
|
input: z.object({ orderId: z.string() }),
|
|
41
|
+
// Types what `run` returns, and parses it before Cortex reads it.
|
|
42
|
+
output: z.object({ cancelled: z.boolean() }),
|
|
40
43
|
readOnly: false,
|
|
41
44
|
// Every call parks until the end user approves it, on a card titled with
|
|
42
45
|
// what the model says that call will do.
|
|
43
46
|
requiresApproval: true,
|
|
44
|
-
run: async ({ orderId }, { user }) => {
|
|
47
|
+
run: async ({ orderId }, { user }, { request }) => {
|
|
45
48
|
if (!user)
|
|
46
49
|
throw new CortexError("forbidden", "Only a signed-in user can cancel an order");
|
|
47
|
-
return cancel(orderId, user.id);
|
|
50
|
+
return cancel(orderId, user.id, request.headers.get("x-request-id"));
|
|
48
51
|
},
|
|
49
52
|
},
|
|
50
53
|
},
|
|
@@ -64,7 +67,9 @@ app.route("/cortex", cortexServer);
|
|
|
64
67
|
|
|
65
68
|
Cortex reads `GET /` (the manifest, versioned by its own content) on every sync, and calls `POST /variables`, `POST /tools/:name`, `POST /verify` and `POST /events/:event` (`run_waiting`, `run_finished`) behind it. A run-scoped call carries the run's token, which `resolve` and `run` receive as `token`: the end user's bearer in a chat, the trigger's credential in a trigger run. A tool's input is an object schema (any other fails at startup, since every call's `input` is an object), parsed before `run` sees it. With `delegation: true`, Cortex also calls the server for a user whose token is gone (a message that waited past it): such a call carries no token, and `user.delegated` (`{ reason, runId }`) says why, so a tool can refuse what it should not do for a user who is not there. A refusal answers as described in [Errors](#errors).
|
|
66
69
|
|
|
67
|
-
|
|
70
|
+
Each handler's last argument is `{ request, signal }`: the HTTP `Request` it came in, for its headers, and a signal that aborts when Cortex hangs up. With an `output` schema, `run` returns what that schema takes, and the server parses the result with it before answering, so a default fills in and a wrong shape fails to compile. What the handlers receive is exported by name: `VariablesRequest`, `ToolContext`, `VerifiedUser`, `RunWaitingEvent`, `RunFinishedEvent` and `RunWait`.
|
|
71
|
+
|
|
72
|
+
A blank `key` fails `defineServer` at startup. So does a name Cortex would refuse: a tool or variable name that is no identifier, or one of Cortex's built-in names (`utcTime`, `locale`, `timezone`, `threadId`, and the built-in tools such as `executeCode` and `requestLocation`), and so does an input of a tool that needs approval that names `approvalTitle` or closes a sub-schema to it (`additionalProperties: false` inside `allOf`, `anyOf` or `oneOf`), since Cortex adds the card's title to it. The protocol is described in full in `apps/cortex/docs/cortex-integration.md`.
|
|
68
73
|
|
|
69
74
|
## Dataset hosts
|
|
70
75
|
|
|
@@ -90,7 +95,30 @@ export const datasets = defineDatasetHost({
|
|
|
90
95
|
app.route("/datasets", datasets);
|
|
91
96
|
```
|
|
92
97
|
|
|
93
|
-
Register the host on the console's **Datasets** page with that URL. The host checks every query against its own manifest, as Cortex does, and runs it under the user `resolveUser` returns. A body past 256 KiB is refused before it is read, one nested past 32 levels as malformed, and a drizzle dataset refuses a query whose SQL would be written out past 50,000 parts before it reaches the database.
|
|
98
|
+
Register the host on the console's **Datasets** page with that URL. The host checks every query against its own manifest, as Cortex does, and runs it under the user `resolveUser` returns. A name exposed twice fails at startup. A body past 256 KiB is refused before it is read, one nested past 32 levels as malformed, and a drizzle dataset refuses a query whose SQL would be written out past 50,000 parts before it reaches the database.
|
|
99
|
+
|
|
100
|
+
Behind a gateway that already verified the end user's token, `resolveUser: unverifiedJwtSubject` runs queries as `{ sub }`, read from the JWT without checking its signature. A call without a token resolves to null, and a token that is no JWT with a subject is refused as `forbidden`. Anywhere else, verify the token in your own `resolveUser`.
|
|
101
|
+
|
|
102
|
+
`project` replaces the table's columns with named ones: a table column under a name of its own, or a computed expression whose type `types` names. A join reaches a projected dataset through a subquery of its rows.
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
const lines = drizzleDataset<User>({
|
|
106
|
+
name: "lines",
|
|
107
|
+
description: "One row per order line.",
|
|
108
|
+
table: ordersTable,
|
|
109
|
+
dialect: "postgres",
|
|
110
|
+
db,
|
|
111
|
+
project: {
|
|
112
|
+
id: ordersTable.id,
|
|
113
|
+
buyer: ordersTable.customerId,
|
|
114
|
+
unitPrice: sql`${ordersTable.total} / ${ordersTable.quantity}`,
|
|
115
|
+
},
|
|
116
|
+
types: { unitPrice: "number" },
|
|
117
|
+
scoped: (user) => eq(ordersTable.customerId, user.customerId),
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
A custom source implements `DatasetSource` itself: its `definition`, and a `run` that gets the checked query, the user, an abort signal and the request's context.
|
|
94
122
|
|
|
95
123
|
`values: { status: ["pending", "shipped", "cancelled"] }` lists every value a string column can hold: the model reads them, and a query comparing the column to any other value is refused. A column drizzle knows as an enum (a `pgEnum`, or `text({ enum })`) lists its own values.
|
|
96
124
|
|
|
@@ -108,7 +136,7 @@ Both protocols refuse in one envelope, `{ error: { kind, detail } }`, under the
|
|
|
108
136
|
| `timeout` | 504 | The call did not finish in time |
|
|
109
137
|
| `internal` | 500 | Anything else, answered without the underlying message |
|
|
110
138
|
|
|
111
|
-
Throw `new CortexError(kind, detail)` from a tool, a variable resolver, `verify`, an event handler, a dataset source or `resolveUser` to answer that kind with your detail, which the model reads. A timeout or an abort answers `timeout`, and any other error answers `internal`. The package answers `invalid_request` itself for a malformed body, an input that fails its schema, a query the manifest refuses, and an unknown dataset or tool. An unknown tool answers under 404, a body over the size limit under 413, and a wrong server key `forbidden` under 401.
|
|
139
|
+
Throw `new CortexError(kind, detail)` from a tool, a variable resolver, `verify`, an event handler, a dataset source or `resolveUser` to answer that kind with your detail, which the model reads. A timeout or an abort answers `timeout`, and any other error answers `internal` and reaches `onError`. `defineServer` and `defineDatasetHost` both take `onError(error, context)`, which logs with `console.error` by default. Its context is the handler's `{ request, signal }` on a server, and `{ dataset, request }` on a dataset host. The package answers `invalid_request` itself for a malformed body, an input that fails its schema, a query the manifest refuses, and an unknown dataset or tool. An unknown tool answers under 404, a body over the size limit under 413, and a wrong server key `forbidden` under 401.
|
|
112
140
|
|
|
113
141
|
## Triggers
|
|
114
142
|
|
|
@@ -153,11 +181,13 @@ const { runs } = await triggers.list("pr-opened", { limit: 20 });
|
|
|
153
181
|
if (runs[0]) await triggers.cancel("pr-opened", runs[0].id);
|
|
154
182
|
```
|
|
155
183
|
|
|
184
|
+
`url` may be left out. Without it, or without a usable secret for a trigger, `canFire(trigger)` is false and every call for that trigger throws before sending. A url that is not http or https fails at construction.
|
|
185
|
+
|
|
156
186
|
`fire` returns a typed union. A `state` identifies a started input, a waiting input, a refused input, an input cancelled before any run took it, or a rejected payload. A `status` identifies a run record returned after waiting. Run statuses are `running`, `waiting`, `completed`, `failed`, and `cancelled`. Completed runs carry `result`; waiting runs carry `waits`, the calls they wait on.
|
|
157
187
|
|
|
158
188
|
`wait` accepts 0 to 300000 milliseconds. `busy` (`"queue"` or `"steer"`) picks where a fire goes while a run holds its thread, within the trigger's busy rule, and never past one that refuses. Retrying the same idempotency key and payload returns the same input and run. Changing the payload under that key returns a `conflict` refusal. Refusals under 409 or 429 and payload issues under 422 are typed results. `answer` returns the same union, so a decision queued behind another run returns its waiting input. Other HTTP errors and malformed responses throw `TriggerClientError`. Answering a call that is no longer waiting throws under 409.
|
|
159
189
|
|
|
160
|
-
Every method takes a trigger name to select its secret. `read`, `answer`, and `cancel` use the agent's run routes. `list` uses the trigger's runs route and preserves newest-first order. Every method accepts an abort `signal`.
|
|
190
|
+
Every method takes a trigger name to select its secret. `read`, `answer`, and `cancel` use the agent's run routes. `list` uses the trigger's runs route and preserves newest-first order. Every method accepts an abort `signal`, and gives up after its `wait` plus 30 seconds with a `TimeoutError`.
|
|
161
191
|
|
|
162
192
|
### Telling a user's thread
|
|
163
193
|
|
|
@@ -188,6 +218,7 @@ const cortex = createManagementClient({
|
|
|
188
218
|
key: process.env.CORTEX_MANAGEMENT_KEY!, // a management key, cortex_mgmt_…
|
|
189
219
|
locale: "ar", // optional: the language Cortex words its refusals in
|
|
190
220
|
timeZone: "Asia/Dubai", // optional: the zone a day range is read in, else UTC days
|
|
221
|
+
timeoutMs: 30_000, // optional: how long a call may take, 100 000 by default
|
|
191
222
|
});
|
|
192
223
|
|
|
193
224
|
const agent: ManagementOutput<"agents.get"> = await cortex.agents.get({ id });
|
|
@@ -205,7 +236,7 @@ try {
|
|
|
205
236
|
}
|
|
206
237
|
```
|
|
207
238
|
|
|
208
|
-
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.
|
|
239
|
+
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). What is free-form by nature (a trigger's payload, a JSON Schema document, a tool call's input and output) is `unknown` in an input and the recursive `JsonValue` in an output; every other value has its own type. A refusal throws `ManagementClientError`; a Cortex that cannot be reached rejects as `fetch` does, and a call past `timeoutMs` rejects with a `TimeoutError`. A url that is not http or https, a blank key, or a `timeoutMs` that is no whole number of milliseconds above 0 fails at construction. 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.
|
|
209
240
|
|
|
210
241
|
## Manifests
|
|
211
242
|
|
package/dist/drizzle.d.ts
CHANGED
|
@@ -1054,11 +1054,15 @@ export type DrizzleDialect = "postgres" | "mssql" | "sqlite";
|
|
|
1054
1054
|
export type DatasetDatabase = {
|
|
1055
1055
|
select(fields: Record<string, Column | SQL | SQL.Aliased>): unknown;
|
|
1056
1056
|
};
|
|
1057
|
+
/** A dataset column: a table column, or a computed expression over the table. */
|
|
1058
|
+
export type ColumnSource = Column | SQL;
|
|
1057
1059
|
/** What a relation needs of its target: the table to join, the columns it exposes, and its name for the manifest. */
|
|
1058
1060
|
export type RelationTarget = {
|
|
1059
1061
|
name: string;
|
|
1060
1062
|
table: Table;
|
|
1061
|
-
columnsByName: ReadonlyMap<string,
|
|
1063
|
+
columnsByName: ReadonlyMap<string, ColumnSource>;
|
|
1064
|
+
/** Whether the columns are a projection, which a join reaches through a subquery rather than the aliased table. */
|
|
1065
|
+
projected: boolean;
|
|
1062
1066
|
definition: DatasetDefinition;
|
|
1063
1067
|
relations(): Record<string, DrizzleRelation>;
|
|
1064
1068
|
/** The rows the caller may see of this dataset; a join reaches it through this, never the raw table. */
|
|
@@ -1093,7 +1097,15 @@ export type DrizzleDatasetOptions<TUser> = {
|
|
|
1093
1097
|
db: DatasetDatabase;
|
|
1094
1098
|
/** The rows this user may see, as a condition on `table`; undefined for all rows. */
|
|
1095
1099
|
scoped: (user: TUser) => SQL | undefined;
|
|
1096
|
-
/**
|
|
1100
|
+
/**
|
|
1101
|
+
* The dataset's columns by name, replacing the table's own, as .NET's
|
|
1102
|
+
* `Project` does: a table column under a name of its own, or a computed
|
|
1103
|
+
* expression over `table` (`` sql`${orders.total} / ${orders.quantity}` ``),
|
|
1104
|
+
* whose type `types` must name. A join reaches a projected dataset
|
|
1105
|
+
* through a subquery of its rows.
|
|
1106
|
+
*/
|
|
1107
|
+
project?: Record<string, ColumnSource>;
|
|
1108
|
+
/** Which table properties, or projected names, become columns; every mappable one when absent. */
|
|
1097
1109
|
columns?: {
|
|
1098
1110
|
pick?: readonly string[];
|
|
1099
1111
|
exclude?: readonly string[];
|
|
@@ -1104,7 +1116,7 @@ export type DrizzleDatasetOptions<TUser> = {
|
|
|
1104
1116
|
* may only compare it to; a column drizzle knows as an enum lists its own.
|
|
1105
1117
|
*/
|
|
1106
1118
|
values?: Record<string, readonly string[]>;
|
|
1107
|
-
/** The dataset type of a column the table cannot describe, such as a date kept as ISO text. */
|
|
1119
|
+
/** The dataset type of a column the table cannot describe, such as a date kept as ISO text or a computed value. */
|
|
1108
1120
|
types?: Record<string, DatasetColumnType>;
|
|
1109
1121
|
/** Read late, so datasets may refer to each other and to themselves. */
|
|
1110
1122
|
relations?: () => Record<string, DrizzleRelation>;
|
package/dist/drizzle.js
CHANGED
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
filterRefs,
|
|
6
6
|
isColumnValue,
|
|
7
7
|
FUNCTION_SIGNATURES
|
|
8
|
-
} from "./index-
|
|
8
|
+
} from "./index-ycr8n8r9.js";
|
|
9
9
|
|
|
10
10
|
// src/datasets/drizzle.ts
|
|
11
11
|
import {
|
|
@@ -36,6 +36,7 @@ import {
|
|
|
36
36
|
sum,
|
|
37
37
|
Column,
|
|
38
38
|
is,
|
|
39
|
+
noopDecoder,
|
|
39
40
|
SQL,
|
|
40
41
|
Subquery
|
|
41
42
|
} from "drizzle-orm";
|
|
@@ -146,21 +147,24 @@ var SQLITE_PART_FIELD = {
|
|
|
146
147
|
dayOfWeek: "%w"
|
|
147
148
|
};
|
|
148
149
|
function drizzleDataset(options) {
|
|
149
|
-
const all = Object.entries(getTableColumns(options.table));
|
|
150
|
+
const all = Object.entries(options.project ?? getTableColumns(options.table));
|
|
150
151
|
const picked = all.filter(([name]) => {
|
|
151
152
|
if (options.columns?.pick)
|
|
152
153
|
return options.columns.pick.includes(name);
|
|
153
154
|
return !options.columns?.exclude?.includes(name);
|
|
154
155
|
});
|
|
155
156
|
const columns = picked.flatMap(([name, column]) => {
|
|
156
|
-
const type = options.types?.[name] ?? columnTypeOf(column);
|
|
157
|
+
const type = options.types?.[name] ?? (is(column, Column) ? columnTypeOf(column) : undefined);
|
|
158
|
+
if (!type && options.project) {
|
|
159
|
+
throw new Error(`Dataset "${options.name}": the projected column ${name} needs its type in \`types\``);
|
|
160
|
+
}
|
|
157
161
|
if (!type)
|
|
158
162
|
return [];
|
|
159
163
|
const declared = options.values?.[name];
|
|
160
164
|
if (declared && type !== "string") {
|
|
161
165
|
throw new Error(`Dataset "${options.name}": only a string column lists its values, and ${name} is a ${type}`);
|
|
162
166
|
}
|
|
163
|
-
const values = declared ?? datasetColumnSchema.shape.values.safeParse(column.enumValues).data;
|
|
167
|
+
const values = declared ?? datasetColumnSchema.shape.values.safeParse(is(column, Column) ? column.enumValues : undefined).data;
|
|
164
168
|
return [
|
|
165
169
|
{
|
|
166
170
|
name,
|
|
@@ -176,6 +180,7 @@ function drizzleDataset(options) {
|
|
|
176
180
|
name: options.name,
|
|
177
181
|
table: options.table,
|
|
178
182
|
columnsByName,
|
|
183
|
+
projected: options.project !== undefined,
|
|
179
184
|
relations: () => options.relations?.() ?? {},
|
|
180
185
|
scope: (user) => options.scoped(user),
|
|
181
186
|
get definition() {
|
|
@@ -258,6 +263,8 @@ function compile(root, options, query, user, clock) {
|
|
|
258
263
|
const name = ref.slice(dot + 1);
|
|
259
264
|
const column = columnOf(table, name);
|
|
260
265
|
const type = table.types.get(name) ?? "string";
|
|
266
|
+
if (!is(column, Column))
|
|
267
|
+
return { column: rewrapped(column, type), type };
|
|
261
268
|
return {
|
|
262
269
|
column,
|
|
263
270
|
type,
|
|
@@ -347,14 +354,19 @@ function joinRelations(root, join, user, db) {
|
|
|
347
354
|
const joins = [];
|
|
348
355
|
const sourceOf = (target, alias) => {
|
|
349
356
|
const scope = target.scope(user);
|
|
350
|
-
if (!scope) {
|
|
357
|
+
if (!scope && !target.projected) {
|
|
351
358
|
const table = aliasedTable(target.table, alias);
|
|
352
359
|
return { table, columns: aliasColumns(target.columnsByName, table) };
|
|
353
360
|
}
|
|
354
|
-
const
|
|
361
|
+
const fields = Object.fromEntries([...target.columnsByName].map(([name, column]) => [
|
|
362
|
+
name,
|
|
363
|
+
is(column, Column) ? column : column.as(name)
|
|
364
|
+
]));
|
|
365
|
+
const rows = db.select(fields).from(target.table).where(scope).as(alias);
|
|
366
|
+
const columnOfRow = (field) => is(field, Column) ? field : rewrapped(field);
|
|
355
367
|
return {
|
|
356
368
|
table: rows,
|
|
357
|
-
columns: new Map([...target.columnsByName.keys()].map((name) => [name, rows[name]]))
|
|
369
|
+
columns: new Map([...target.columnsByName.keys()].map((name) => [name, columnOfRow(rows[name])]))
|
|
358
370
|
};
|
|
359
371
|
};
|
|
360
372
|
const paths = [...new Set(join.flatMap(prefixes))].sort((left, right) => left.split(".").length - right.split(".").length);
|
|
@@ -412,7 +424,7 @@ function groupedFields(dialect, query, resolve, named) {
|
|
|
412
424
|
const name = groupKeyName(group);
|
|
413
425
|
const value = typeof group === "string" ? resolve(group) : operandSql(dialect, group.expr, resolve);
|
|
414
426
|
const key = is(value.column, Column) ? value.column : value.column.inlineParams();
|
|
415
|
-
fields[name] = is(key, Column) ? key :
|
|
427
|
+
fields[name] = is(key, Column) ? key : expressionOf({ ...value, column: key });
|
|
416
428
|
groupKeys.push(key);
|
|
417
429
|
named.set(name, { ...value, column: key });
|
|
418
430
|
}
|
|
@@ -455,6 +467,17 @@ function columnIn(columns, name) {
|
|
|
455
467
|
return column;
|
|
456
468
|
}
|
|
457
469
|
var FLOAT = { postgres: "double precision", mssql: "float", sqlite: "real" };
|
|
470
|
+
function ownDecoder(expression) {
|
|
471
|
+
const decoder = Reflect.get(is(expression, SQL.Aliased) ? expression.sql : expression, "decoder");
|
|
472
|
+
return decoder !== noopDecoder && typeof decoder === "object" && decoder !== null && "mapFromDriverValue" in decoder ? decoder : undefined;
|
|
473
|
+
}
|
|
474
|
+
function rewrapped(expression, type) {
|
|
475
|
+
const own = ownDecoder(expression);
|
|
476
|
+
const fresh = sql`${expression}`;
|
|
477
|
+
if (own)
|
|
478
|
+
return fresh.mapWith(own);
|
|
479
|
+
return type ? decoded(fresh, type) : fresh;
|
|
480
|
+
}
|
|
458
481
|
function decoded(expression, type) {
|
|
459
482
|
if (type === "number")
|
|
460
483
|
return expression.mapWith(Number);
|
|
@@ -466,7 +489,9 @@ function columnSql(column) {
|
|
|
466
489
|
return sql`${column}`.mapWith(column);
|
|
467
490
|
}
|
|
468
491
|
function expressionOf({ column, type }) {
|
|
469
|
-
|
|
492
|
+
if (is(column, Column))
|
|
493
|
+
return columnSql(column);
|
|
494
|
+
return ownDecoder(column) ? column : decoded(column, type);
|
|
470
495
|
}
|
|
471
496
|
function operandSql(dialect, operand, resolve) {
|
|
472
497
|
if (typeof operand === "string")
|
|
@@ -577,7 +602,7 @@ function aggregateOf(dialect, aggregate, resolve, over) {
|
|
|
577
602
|
const partition = over.length ? sql`partition by ${sql.join(over, sql`, `)}` : sql``;
|
|
578
603
|
return sql`${fn} over (${partition})`;
|
|
579
604
|
};
|
|
580
|
-
const decoder = is(column, Column) ? column : operand?.stored;
|
|
605
|
+
const decoder = is(column, Column) ? column : operand?.stored ?? (column && ownDecoder(column));
|
|
581
606
|
const extreme = (expression) => decoder ? expression.mapWith(decoder) : decoded(expression, operand.type);
|
|
582
607
|
switch (aggregate.fn) {
|
|
583
608
|
case "count":
|
|
@@ -28,6 +28,10 @@ function errorEnvelope(kind, detail) {
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
// ../../internal/contracts/src/json/index.ts
|
|
31
|
+
import { z as z2 } from "zod";
|
|
32
|
+
var JSON_VALUE_ID = "JsonValue";
|
|
33
|
+
var jsonValueSchema = z2.unknown().meta({ id: JSON_VALUE_ID });
|
|
34
|
+
var jsonObjectSchema = z2.record(z2.string(), jsonValueSchema);
|
|
31
35
|
function isRecord(value) {
|
|
32
36
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
33
37
|
}
|
|
@@ -93,12 +97,12 @@ function contentVersion(value) {
|
|
|
93
97
|
}
|
|
94
98
|
|
|
95
99
|
// ../../internal/contracts/src/datasets/datasets.ts
|
|
96
|
-
import { z as
|
|
100
|
+
import { z as z3 } from "zod";
|
|
97
101
|
var DATASET_IDENTIFIER_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;
|
|
98
102
|
var DATASET_IDENTIFIER_MAX = 64;
|
|
99
103
|
var DATASET_COLUMN_REF_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)*$/;
|
|
100
|
-
var datasetIdentifierSchema =
|
|
101
|
-
var datasetColumnRefSchema =
|
|
104
|
+
var datasetIdentifierSchema = z3.string().regex(DATASET_IDENTIFIER_PATTERN).max(DATASET_IDENTIFIER_MAX);
|
|
105
|
+
var datasetColumnRefSchema = z3.string().regex(DATASET_COLUMN_REF_PATTERN).max(256);
|
|
102
106
|
var DATASET_COLUMN_TYPES = ["string", "number", "boolean", "date"];
|
|
103
107
|
var DATASET_DEFINITION_LIMITS = {
|
|
104
108
|
description: 500,
|
|
@@ -108,34 +112,34 @@ var DATASET_DEFINITION_LIMITS = {
|
|
|
108
112
|
valueLength: 200,
|
|
109
113
|
maxRows: 5000
|
|
110
114
|
};
|
|
111
|
-
var datasetColumnSchema =
|
|
115
|
+
var datasetColumnSchema = z3.object({
|
|
112
116
|
name: datasetIdentifierSchema,
|
|
113
|
-
type:
|
|
114
|
-
description:
|
|
115
|
-
values:
|
|
117
|
+
type: z3.enum(DATASET_COLUMN_TYPES).meta({ id: "DatasetColumnType" }),
|
|
118
|
+
description: z3.string().max(DATASET_DEFINITION_LIMITS.columnDescription).default(""),
|
|
119
|
+
values: z3.array(z3.string().min(1).max(DATASET_DEFINITION_LIMITS.valueLength)).min(1).max(DATASET_DEFINITION_LIMITS.values).optional()
|
|
116
120
|
}).refine((column) => column.values === undefined || column.type === "string", {
|
|
117
121
|
message: "only a string column lists its values",
|
|
118
122
|
path: ["values"]
|
|
119
123
|
});
|
|
120
|
-
var datasetRelationSchema =
|
|
124
|
+
var datasetRelationSchema = z3.object({
|
|
121
125
|
dataset: datasetIdentifierSchema,
|
|
122
|
-
on:
|
|
123
|
-
through:
|
|
126
|
+
on: z3.tuple([datasetIdentifierSchema, datasetIdentifierSchema]),
|
|
127
|
+
through: z3.object({
|
|
124
128
|
dataset: datasetIdentifierSchema,
|
|
125
|
-
on:
|
|
129
|
+
on: z3.tuple([datasetIdentifierSchema, datasetIdentifierSchema])
|
|
126
130
|
}).optional()
|
|
127
131
|
});
|
|
128
132
|
var DATASET_MAX_ROWS_DEFAULT = 500;
|
|
129
|
-
var datasetDefinitionSchema =
|
|
133
|
+
var datasetDefinitionSchema = z3.object({
|
|
130
134
|
name: datasetIdentifierSchema,
|
|
131
|
-
description:
|
|
132
|
-
columns:
|
|
133
|
-
relations:
|
|
134
|
-
maxRows:
|
|
135
|
+
description: z3.string().max(DATASET_DEFINITION_LIMITS.description),
|
|
136
|
+
columns: z3.array(datasetColumnSchema).min(1).max(DATASET_DEFINITION_LIMITS.columns),
|
|
137
|
+
relations: z3.record(datasetIdentifierSchema, datasetRelationSchema).default({}),
|
|
138
|
+
maxRows: z3.number().int().min(1).max(DATASET_DEFINITION_LIMITS.maxRows).default(DATASET_MAX_ROWS_DEFAULT)
|
|
135
139
|
});
|
|
136
|
-
var datasetManifestSchema =
|
|
137
|
-
version:
|
|
138
|
-
datasets:
|
|
140
|
+
var datasetManifestSchema = z3.object({
|
|
141
|
+
version: z3.string().min(1).max(128),
|
|
142
|
+
datasets: z3.array(datasetDefinitionSchema).max(500)
|
|
139
143
|
});
|
|
140
144
|
var DATASET_FILTER_OPS = [
|
|
141
145
|
"=",
|
|
@@ -165,91 +169,91 @@ var DATASET_FUNCTIONS = [
|
|
|
165
169
|
"coalesce"
|
|
166
170
|
];
|
|
167
171
|
var DATASET_AGGREGATES = ["count", "countDistinct", "sum", "avg", "min", "max"];
|
|
168
|
-
var filterValueSchema =
|
|
172
|
+
var filterValueSchema = z3.union([z3.string(), z3.number(), z3.boolean()]);
|
|
169
173
|
var DATASET_ARITHMETIC_OPS = ["+", "-", "*", "/"];
|
|
170
|
-
var datasetOperandSchema =
|
|
174
|
+
var datasetOperandSchema = z3.lazy(() => z3.union([
|
|
171
175
|
datasetColumnRefSchema,
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
op:
|
|
176
|
+
z3.number(),
|
|
177
|
+
z3.object({ value: z3.union([z3.string().max(500), z3.boolean()]) }),
|
|
178
|
+
z3.object({
|
|
179
|
+
op: z3.enum(DATASET_ARITHMETIC_OPS),
|
|
176
180
|
left: datasetOperandSchema,
|
|
177
181
|
right: datasetOperandSchema
|
|
178
182
|
}),
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
fn:
|
|
182
|
-
unit:
|
|
183
|
+
z3.discriminatedUnion("fn", [
|
|
184
|
+
z3.object({
|
|
185
|
+
fn: z3.literal("dateTrunc"),
|
|
186
|
+
unit: z3.enum(DATASET_BUCKETS),
|
|
183
187
|
of: datasetOperandSchema
|
|
184
188
|
}),
|
|
185
|
-
|
|
186
|
-
fn:
|
|
187
|
-
unit:
|
|
189
|
+
z3.object({
|
|
190
|
+
fn: z3.literal("datePart"),
|
|
191
|
+
unit: z3.enum(DATASET_DATE_PARTS),
|
|
188
192
|
of: datasetOperandSchema
|
|
189
193
|
}),
|
|
190
|
-
|
|
191
|
-
fn:
|
|
192
|
-
args:
|
|
194
|
+
z3.object({
|
|
195
|
+
fn: z3.enum(DATASET_FUNCTIONS),
|
|
196
|
+
args: z3.array(datasetOperandSchema).min(1).max(10)
|
|
193
197
|
})
|
|
194
198
|
]),
|
|
195
|
-
|
|
196
|
-
case:
|
|
199
|
+
z3.object({
|
|
200
|
+
case: z3.array(z3.object({ when: datasetFilterSchema, then: datasetOperandSchema })).min(1).max(20),
|
|
197
201
|
else: datasetOperandSchema.optional()
|
|
198
202
|
})
|
|
199
203
|
]));
|
|
200
|
-
var datasetNamedOperandSchema =
|
|
204
|
+
var datasetNamedOperandSchema = z3.object({
|
|
201
205
|
expr: datasetOperandSchema,
|
|
202
206
|
as: datasetIdentifierSchema
|
|
203
207
|
});
|
|
204
208
|
var datasetConditionLeftSchema = datasetOperandSchema.refine((operand) => typeof operand !== "number", "a condition starts with a column");
|
|
205
|
-
var datasetConditionSchema =
|
|
209
|
+
var datasetConditionSchema = z3.object({
|
|
206
210
|
col: datasetConditionLeftSchema,
|
|
207
|
-
op:
|
|
208
|
-
value:
|
|
211
|
+
op: z3.enum(DATASET_FILTER_OPS),
|
|
212
|
+
value: z3.union([
|
|
209
213
|
filterValueSchema,
|
|
210
|
-
|
|
211
|
-
|
|
214
|
+
z3.array(filterValueSchema).max(500),
|
|
215
|
+
z3.object({ col: datasetOperandSchema })
|
|
212
216
|
]).optional()
|
|
213
217
|
});
|
|
214
|
-
var notACondition = { col:
|
|
215
|
-
var datasetFilterSchema =
|
|
218
|
+
var notACondition = { col: z3.never().optional() };
|
|
219
|
+
var datasetFilterSchema = z3.lazy(() => z3.union([
|
|
216
220
|
datasetConditionSchema,
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
221
|
+
z3.object({ any: z3.array(datasetFilterSchema).min(1).max(20), ...notACondition }),
|
|
222
|
+
z3.object({ all: z3.array(datasetFilterSchema).min(1).max(20), ...notACondition }),
|
|
223
|
+
z3.object({ not: datasetFilterSchema, ...notACondition })
|
|
220
224
|
]));
|
|
221
|
-
var datasetGroupBySchema =
|
|
222
|
-
var datasetSortSchema =
|
|
225
|
+
var datasetGroupBySchema = z3.union([datasetColumnRefSchema, datasetNamedOperandSchema]);
|
|
226
|
+
var datasetSortSchema = z3.object({
|
|
223
227
|
col: datasetColumnRefSchema,
|
|
224
|
-
dir:
|
|
228
|
+
dir: z3.enum(["asc", "desc"])
|
|
225
229
|
});
|
|
226
|
-
var datasetAggregateSchema =
|
|
227
|
-
fn:
|
|
230
|
+
var datasetAggregateSchema = z3.object({
|
|
231
|
+
fn: z3.enum(DATASET_AGGREGATES),
|
|
228
232
|
col: datasetConditionLeftSchema.optional().describe("The column or arithmetic to aggregate; omit for count."),
|
|
229
233
|
as: datasetIdentifierSchema.describe("The key the value comes back under; also what sort may name."),
|
|
230
|
-
filter:
|
|
234
|
+
filter: z3.array(datasetFilterSchema).max(20).default([])
|
|
231
235
|
});
|
|
232
|
-
var datasetQueryObjectSchema =
|
|
236
|
+
var datasetQueryObjectSchema = z3.object({
|
|
233
237
|
from: datasetIdentifierSchema,
|
|
234
|
-
join:
|
|
235
|
-
select:
|
|
236
|
-
filter:
|
|
237
|
-
groupBy:
|
|
238
|
-
aggregate:
|
|
239
|
-
window:
|
|
240
|
-
partitionBy:
|
|
238
|
+
join: z3.array(datasetColumnRefSchema).max(8).default([]).describe("Relations to join, by name; referencing relation.column joins it too."),
|
|
239
|
+
select: z3.array(z3.union([datasetColumnRefSchema, datasetNamedOperandSchema])).max(200).optional().describe("Columns or named values to return when not grouping; aggregates go in aggregate, not here."),
|
|
240
|
+
filter: z3.array(datasetFilterSchema).max(20).default([]),
|
|
241
|
+
groupBy: z3.array(datasetGroupBySchema).max(8).default([]).describe("Group keys: a column name, or { expr, as } for a value such as a truncated date."),
|
|
242
|
+
aggregate: z3.array(datasetAggregateSchema).max(10).default([]).describe("One entry per computed value; a grouped row holds the group keys and these aliases."),
|
|
243
|
+
window: z3.array(datasetAggregateSchema.extend({
|
|
244
|
+
partitionBy: z3.array(datasetColumnRefSchema).max(4).default([])
|
|
241
245
|
})).max(10).default([]),
|
|
242
|
-
compute:
|
|
243
|
-
having:
|
|
244
|
-
qualify:
|
|
245
|
-
rank:
|
|
246
|
-
partitionBy:
|
|
247
|
-
sort:
|
|
248
|
-
limit:
|
|
246
|
+
compute: z3.array(datasetNamedOperandSchema).max(10).default([]),
|
|
247
|
+
having: z3.array(datasetFilterSchema).max(20).default([]),
|
|
248
|
+
qualify: z3.array(datasetFilterSchema).max(20).default([]),
|
|
249
|
+
rank: z3.object({
|
|
250
|
+
partitionBy: z3.array(datasetColumnRefSchema).min(1).max(4),
|
|
251
|
+
sort: z3.array(datasetSortSchema).min(1).max(5),
|
|
252
|
+
limit: z3.number().int().min(1).max(100)
|
|
249
253
|
}).optional(),
|
|
250
|
-
sort:
|
|
251
|
-
limit:
|
|
252
|
-
offset:
|
|
254
|
+
sort: z3.array(datasetSortSchema).max(5).default([]).describe("By a column or select alias, a group key, an aggregate alias or a computed alias."),
|
|
255
|
+
limit: z3.int32().min(1).optional(),
|
|
256
|
+
offset: z3.int32().min(0).optional()
|
|
253
257
|
});
|
|
254
258
|
var DATASET_QUERY_MAX_DEPTH = 32;
|
|
255
259
|
var DATASET_REQUEST_MAX_BYTES = 256 * 1024;
|
|
@@ -259,19 +263,19 @@ function nestsWithin(value, budget) {
|
|
|
259
263
|
return true;
|
|
260
264
|
return budget > 0 && Object.values(value).every((item) => nestsWithin(item, budget - 1));
|
|
261
265
|
}
|
|
262
|
-
var datasetQuerySchema =
|
|
263
|
-
var datasetRequestSchema =
|
|
266
|
+
var datasetQuerySchema = z3.custom((value) => nestsWithin(value, DATASET_QUERY_MAX_DEPTH), `A query nests at most ${DATASET_QUERY_MAX_DEPTH} levels deep; write a flatter expression`).pipe(datasetQueryObjectSchema);
|
|
267
|
+
var datasetRequestSchema = z3.object({
|
|
264
268
|
query: datasetQuerySchema,
|
|
265
|
-
context:
|
|
266
|
-
threadId:
|
|
267
|
-
requestId:
|
|
268
|
-
timeZone:
|
|
269
|
+
context: z3.object({
|
|
270
|
+
threadId: z3.string().max(128),
|
|
271
|
+
requestId: z3.string().max(128).optional(),
|
|
272
|
+
timeZone: z3.string().max(64).optional()
|
|
269
273
|
})
|
|
270
274
|
});
|
|
271
|
-
var datasetResultSchema =
|
|
272
|
-
rows:
|
|
273
|
-
rowCount:
|
|
274
|
-
truncated:
|
|
275
|
+
var datasetResultSchema = z3.object({
|
|
276
|
+
rows: z3.array(jsonObjectSchema),
|
|
277
|
+
rowCount: z3.number().int().nonnegative(),
|
|
278
|
+
truncated: z3.boolean()
|
|
275
279
|
});
|
|
276
280
|
function datasetCatalogOf(definitions) {
|
|
277
281
|
return new Map([...definitions].map((definition) => [definition.name, definition]));
|
|
@@ -929,42 +933,5 @@ function firstColumnOf(catalog, from, path) {
|
|
|
929
933
|
}
|
|
930
934
|
return dataset?.columns[0]?.name ?? "";
|
|
931
935
|
}
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
COUNT: "count",
|
|
935
|
-
SUM: "sum",
|
|
936
|
-
AVG: "avg",
|
|
937
|
-
MIN: "min",
|
|
938
|
-
MAX: "max"
|
|
939
|
-
};
|
|
940
|
-
var FUNCTION_WORDS = {
|
|
941
|
-
LOWER: "lower",
|
|
942
|
-
UPPER: "upper",
|
|
943
|
-
TRIM: "trim",
|
|
944
|
-
LENGTH: "length",
|
|
945
|
-
LEN: "length",
|
|
946
|
-
CHAR_LENGTH: "length",
|
|
947
|
-
ABS: "abs",
|
|
948
|
-
ROUND: "round",
|
|
949
|
-
COALESCE: "coalesce"
|
|
950
|
-
};
|
|
951
|
-
var DATE_PART_WORDS = {
|
|
952
|
-
YEAR: "year",
|
|
953
|
-
QUARTER: "quarter",
|
|
954
|
-
MONTH: "month",
|
|
955
|
-
WEEK: "week",
|
|
956
|
-
DAY: "day",
|
|
957
|
-
DAYOFWEEK: "dayOfWeek"
|
|
958
|
-
};
|
|
959
|
-
var FUNCTIONS = [
|
|
960
|
-
...Object.keys(AGGREGATE_WORDS),
|
|
961
|
-
"DATE_TRUNC('unit', x)",
|
|
962
|
-
"EXTRACT(part FROM x)",
|
|
963
|
-
...Object.keys(DATE_PART_WORDS),
|
|
964
|
-
...Object.keys(FUNCTION_WORDS),
|
|
965
|
-
"NOW()",
|
|
966
|
-
"RANK() OVER (...)"
|
|
967
|
-
].join(", ");
|
|
968
|
-
// ../../internal/contracts/src/datasets/dataset-sql-guide.ts
|
|
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.";
|
|
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 };
|
|
936
|
+
|
|
937
|
+
export { BACKEND_ERROR_STATUS, backendErrorSchema, errorEnvelope, jsonValueSchema, jsonObjectSchema, isRecord, readJsonPointer, CortexError2, malformedBody, envelopeOf, protocolBodyLimit, contentVersion, datasetIdentifierSchema, datasetColumnSchema, datasetDefinitionSchema, DATASET_REQUEST_MAX_BYTES, datasetRequestSchema, datasetCatalogOf, groupKeyName, filterRefs, isColumnValue, checkDatasetQuery, boundDatasetResult, FUNCTION_SIGNATURES };
|