@keemakr/ui-sdk 1.4.0-dev-20261013075652 → 1.4.0-dev-20261013150327
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/build.d.ts +4 -0
- package/dist/build.js +137 -1
- package/dist/cli.js +4 -2
- package/dist/dataset.d.ts +251 -0
- package/dist/dataset.js +408 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/schema.d.ts +13 -13
- package/package.json +1 -1
package/dist/build.d.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
import { type DatasetDeclaration } from './dataset.js';
|
|
1
2
|
import { type UiManifest } from './schema.js';
|
|
2
3
|
export interface BuildModuleUiResult {
|
|
3
4
|
manifest: UiManifest;
|
|
5
|
+
/** Every dataset in ui/datasets/, as entry.json now declares them. */
|
|
6
|
+
datasets: DatasetDeclaration[];
|
|
4
7
|
registryPath: string;
|
|
8
|
+
datasetRegistryPath: string;
|
|
5
9
|
entryPath: string;
|
|
6
10
|
removedScreens: string[];
|
|
7
11
|
}
|
package/dist/build.js
CHANGED
|
@@ -2,10 +2,13 @@ import { readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises
|
|
|
2
2
|
import { basename, dirname, join, relative, sep } from 'node:path';
|
|
3
3
|
import { isDeepStrictEqual } from 'node:util';
|
|
4
4
|
import ts from 'typescript';
|
|
5
|
+
import { datasetManifestSchema } from './dataset.js';
|
|
5
6
|
import { surfaceDefinitionSchema, uiManifestSchema, } from './schema.js';
|
|
6
7
|
const SLUG = /^[a-z][a-z0-9_-]*$/;
|
|
7
8
|
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
8
9
|
const REMOVED_SCREENS_META_KEY = 'uiSdkRemovedScreens';
|
|
10
|
+
/** `ui/datasets/` holds datasets, so no surface may take that name. */
|
|
11
|
+
const DATASETS_DIRECTORY = 'datasets';
|
|
9
12
|
function unwrap(expression) {
|
|
10
13
|
if (ts.isParenthesizedExpression(expression) ||
|
|
11
14
|
ts.isAsExpression(expression) ||
|
|
@@ -26,6 +29,112 @@ function literalValue(expression) {
|
|
|
26
29
|
return value.elements.map(literalValue);
|
|
27
30
|
throw new Error('surface.ts values must be string or array literals');
|
|
28
31
|
}
|
|
32
|
+
/** A dataset declaration also takes numbers and objects. Still literal only. */
|
|
33
|
+
function declarationValue(expression) {
|
|
34
|
+
const value = unwrap(expression);
|
|
35
|
+
if (ts.isStringLiteralLike(value))
|
|
36
|
+
return value.text;
|
|
37
|
+
if (ts.isNumericLiteral(value))
|
|
38
|
+
return Number(value.text);
|
|
39
|
+
if (ts.isPrefixUnaryExpression(value) &&
|
|
40
|
+
value.operator === ts.SyntaxKind.MinusToken &&
|
|
41
|
+
ts.isNumericLiteral(value.operand)) {
|
|
42
|
+
return -Number(value.operand.text);
|
|
43
|
+
}
|
|
44
|
+
if (value.kind === ts.SyntaxKind.TrueKeyword)
|
|
45
|
+
return true;
|
|
46
|
+
if (value.kind === ts.SyntaxKind.FalseKeyword)
|
|
47
|
+
return false;
|
|
48
|
+
if (value.kind === ts.SyntaxKind.NullKeyword)
|
|
49
|
+
return null;
|
|
50
|
+
if (ts.isArrayLiteralExpression(value))
|
|
51
|
+
return value.elements.map(declarationValue);
|
|
52
|
+
if (ts.isObjectLiteralExpression(value)) {
|
|
53
|
+
const out = {};
|
|
54
|
+
for (const property of value.properties) {
|
|
55
|
+
if (!ts.isPropertyAssignment(property))
|
|
56
|
+
throw new Error('use key: value syntax');
|
|
57
|
+
const name = property.name;
|
|
58
|
+
if (!ts.isIdentifier(name) && !ts.isStringLiteral(name)) {
|
|
59
|
+
throw new Error('property names must be static');
|
|
60
|
+
}
|
|
61
|
+
out[name.text] = declarationValue(property.initializer);
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
throw new Error('declaration values must be literals (string, number, boolean, array, object)');
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Read `export default defineDataset({ ... })` without running the file. Every
|
|
69
|
+
* property but `query` must be a literal; `query` must be there.
|
|
70
|
+
*/
|
|
71
|
+
async function readDatasetDeclaration(path, name) {
|
|
72
|
+
const source = ts.createSourceFile(path, await readFile(path, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
73
|
+
let object;
|
|
74
|
+
for (const statement of source.statements) {
|
|
75
|
+
if (!ts.isExportAssignment(statement))
|
|
76
|
+
continue;
|
|
77
|
+
const exported = unwrap(statement.expression);
|
|
78
|
+
if (!ts.isCallExpression(exported) || exported.arguments.length !== 1)
|
|
79
|
+
continue;
|
|
80
|
+
if (!ts.isIdentifier(exported.expression) || exported.expression.text !== 'defineDataset')
|
|
81
|
+
continue;
|
|
82
|
+
const argument = unwrap(exported.arguments[0]);
|
|
83
|
+
if (ts.isObjectLiteralExpression(argument))
|
|
84
|
+
object = argument;
|
|
85
|
+
}
|
|
86
|
+
if (!object)
|
|
87
|
+
throw new Error(`${path}: default export must be defineDataset({ ... })`);
|
|
88
|
+
const raw = { name };
|
|
89
|
+
let hasQuery = false;
|
|
90
|
+
for (const property of object.properties) {
|
|
91
|
+
const key = property.name;
|
|
92
|
+
if (!key || (!ts.isIdentifier(key) && !ts.isStringLiteral(key))) {
|
|
93
|
+
throw new Error(`${path}: dataset property names must be static`);
|
|
94
|
+
}
|
|
95
|
+
if (key.text === 'query') {
|
|
96
|
+
hasQuery = true;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (key.text === 'name') {
|
|
100
|
+
throw new Error(`${path}: the file name is the dataset's name; remove "name"`);
|
|
101
|
+
}
|
|
102
|
+
if (!ts.isPropertyAssignment(property)) {
|
|
103
|
+
throw new Error(`${path}: "${key.text}" must use key: value syntax`);
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
raw[key.text] = declarationValue(property.initializer);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
throw new Error(`${path}: "${key.text}": ${error.message}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!hasQuery)
|
|
113
|
+
throw new Error(`${path}: a dataset needs a query function`);
|
|
114
|
+
return raw;
|
|
115
|
+
}
|
|
116
|
+
/** Each `ui/datasets/<name>.ts`, sorted by name. Test files are left out. */
|
|
117
|
+
async function collectDatasetFiles(uiRoot) {
|
|
118
|
+
const directory = join(uiRoot, DATASETS_DIRECTORY);
|
|
119
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch((error) => {
|
|
120
|
+
if (error.code === 'ENOENT')
|
|
121
|
+
return [];
|
|
122
|
+
throw error;
|
|
123
|
+
});
|
|
124
|
+
const out = [];
|
|
125
|
+
for (const entry of entries) {
|
|
126
|
+
if (!entry.isFile() || !entry.name.endsWith('.ts'))
|
|
127
|
+
continue;
|
|
128
|
+
if (/\.(test|spec|d)\.ts$/.test(entry.name) || entry.name.startsWith('_'))
|
|
129
|
+
continue;
|
|
130
|
+
const name = entry.name.slice(0, -'.ts'.length);
|
|
131
|
+
if (!SLUG.test(name)) {
|
|
132
|
+
throw new Error(`${join(directory, entry.name)}: dataset file name "${name}" is not a slug`);
|
|
133
|
+
}
|
|
134
|
+
out.push({ name, file: join(directory, entry.name) });
|
|
135
|
+
}
|
|
136
|
+
return out.sort((a, b) => a.name.localeCompare(b.name));
|
|
137
|
+
}
|
|
29
138
|
async function readSurfaceDefinition(path) {
|
|
30
139
|
const source = ts.createSourceFile(path, await readFile(path, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
31
140
|
let object;
|
|
@@ -175,6 +284,8 @@ export async function buildModuleUi(projectRoot = process.cwd()) {
|
|
|
175
284
|
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
176
285
|
if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_'))
|
|
177
286
|
continue;
|
|
287
|
+
if (entry.name === DATASETS_DIRECTORY)
|
|
288
|
+
continue;
|
|
178
289
|
if (!SLUG.test(entry.name))
|
|
179
290
|
throw new Error(`surface directory "${entry.name}" is not a slug`);
|
|
180
291
|
const surfaceDirectory = join(uiRoot, entry.name);
|
|
@@ -204,6 +315,18 @@ export async function buildModuleUi(projectRoot = process.cwd()) {
|
|
|
204
315
|
const manifest = surfaces.length === 0
|
|
205
316
|
? { surfaces, screenRegistry }
|
|
206
317
|
: uiManifestSchema.parse({ surfaces, screenRegistry });
|
|
318
|
+
const datasetFiles = await collectDatasetFiles(uiRoot);
|
|
319
|
+
const declared = [];
|
|
320
|
+
for (const { name, file } of datasetFiles)
|
|
321
|
+
declared.push(await readDatasetDeclaration(file, name));
|
|
322
|
+
const parsedDatasets = datasetManifestSchema.safeParse(declared);
|
|
323
|
+
if (!parsedDatasets.success) {
|
|
324
|
+
const issue = parsedDatasets.error.issues[0];
|
|
325
|
+
const index = typeof issue?.path[0] === 'number' ? issue.path[0] : -1;
|
|
326
|
+
const where = datasetFiles[index]?.file ?? join(uiRoot, DATASETS_DIRECTORY);
|
|
327
|
+
throw new Error(`${where}: ${issue?.path.slice(1).join('.') || 'dataset'} ${issue?.message ?? 'is invalid'}`);
|
|
328
|
+
}
|
|
329
|
+
const datasets = parsedDatasets.data;
|
|
207
330
|
const entrySource = await readFile(entryPath, 'utf8');
|
|
208
331
|
const originalEntryManifest = JSON.parse(entrySource);
|
|
209
332
|
const entryManifest = JSON.parse(entrySource);
|
|
@@ -211,6 +334,14 @@ export async function buildModuleUi(projectRoot = process.cwd()) {
|
|
|
211
334
|
throw new Error(`${entryPath}: manifest object is required`);
|
|
212
335
|
}
|
|
213
336
|
const registryPath = join(uiRoot, 'screen-registry.ts');
|
|
337
|
+
const datasetRegistryPath = join(uiRoot, 'dataset-registry.ts');
|
|
338
|
+
const datasetRegistryContents = datasetFiles.length === 0
|
|
339
|
+
? undefined
|
|
340
|
+
: `// Generated by @keemakr/ui-sdk. Do not edit.\n${datasetFiles
|
|
341
|
+
.map((item, index) => `import dataset${index} from '${moduleSpecifier(uiRoot, item.file)}';`)
|
|
342
|
+
.join('\n')}\n\nexport const DATASETS = {\n${datasetFiles
|
|
343
|
+
.map((item, index) => ` ${propertyKey(item.name)}: dataset${index},`)
|
|
344
|
+
.join('\n')}\n} as const;\n`;
|
|
214
345
|
const imports = registryImports
|
|
215
346
|
.map((item, index) => `import screen${index} from '${moduleSpecifier(uiRoot, item.file)}';`)
|
|
216
347
|
.join('\n');
|
|
@@ -245,6 +376,10 @@ export async function buildModuleUi(projectRoot = process.cwd()) {
|
|
|
245
376
|
entryManifest.manifest.surfaces = manifest.surfaces;
|
|
246
377
|
entryManifest.manifest.screenRegistry = manifest.screenRegistry;
|
|
247
378
|
}
|
|
379
|
+
if (datasets.length === 0)
|
|
380
|
+
delete entryManifest.manifest.datasets;
|
|
381
|
+
else
|
|
382
|
+
entryManifest.manifest.datasets = datasets;
|
|
248
383
|
if (removedScreens.length > 0) {
|
|
249
384
|
entryManifest.manifest.meta = { ...meta, [REMOVED_SCREENS_META_KEY]: removedScreens };
|
|
250
385
|
}
|
|
@@ -258,7 +393,8 @@ export async function buildModuleUi(projectRoot = process.cwd()) {
|
|
|
258
393
|
: `${JSON.stringify(entryManifest, null, 2)}\n`;
|
|
259
394
|
await replaceGeneratedOutputs([
|
|
260
395
|
{ path: registryPath, contents: registryContents },
|
|
396
|
+
{ path: datasetRegistryPath, contents: datasetRegistryContents },
|
|
261
397
|
{ path: entryPath, contents: entryContents },
|
|
262
398
|
]);
|
|
263
|
-
return { manifest, registryPath, entryPath, removedScreens };
|
|
399
|
+
return { manifest, datasets, registryPath, datasetRegistryPath, entryPath, removedScreens };
|
|
264
400
|
}
|
package/dist/cli.js
CHANGED
|
@@ -8,7 +8,7 @@ async function build() {
|
|
|
8
8
|
if (result.removedScreens.length > 0) {
|
|
9
9
|
console.warn(`Warning: removed screen identities: ${result.removedScreens.join(', ')}. Treat path renames as breaking changes.`);
|
|
10
10
|
}
|
|
11
|
-
console.log(`Built ${result.manifest.surfaces.length} UI surface(s)
|
|
11
|
+
console.log(`Built ${result.manifest.surfaces.length} UI surface(s), ${result.manifest.screenRegistry.length} screen(s) and ${result.datasets.length} dataset(s).`);
|
|
12
12
|
}
|
|
13
13
|
function createRebuildScheduler() {
|
|
14
14
|
let buildInFlight;
|
|
@@ -38,7 +38,9 @@ function createUiWatcher(onChange) {
|
|
|
38
38
|
const directory = join(process.cwd(), 'ui');
|
|
39
39
|
try {
|
|
40
40
|
return watch(directory, { recursive: true }, (_event, filename) => {
|
|
41
|
-
if (!filename ||
|
|
41
|
+
if (!filename ||
|
|
42
|
+
filename.endsWith('screen-registry.ts') ||
|
|
43
|
+
filename.endsWith('dataset-registry.ts'))
|
|
42
44
|
return;
|
|
43
45
|
onChange();
|
|
44
46
|
});
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Datasets — the data half of the UI SDK.
|
|
3
|
+
*
|
|
4
|
+
* A screen is drawn by the module: it returns a tree of blocks. A dataset is
|
|
5
|
+
* data the platform draws: the module declares its fields once, answers a
|
|
6
|
+
* query with rows, and the platform turns the rows into views (a table, a
|
|
7
|
+
* board, a list, a record) built from the same blocks every app already draws.
|
|
8
|
+
*
|
|
9
|
+
* Each field has a type, and may have a role. The type says what a value is
|
|
10
|
+
* (text, a number, a time). The role says what the value means to a view
|
|
11
|
+
* (the title of a row, its status, its owner, when it is due), so a view kind
|
|
12
|
+
* knows where to place it without the module laying anything out.
|
|
13
|
+
*
|
|
14
|
+
* ui/datasets/<name>.ts -> export default defineDataset({ ... })
|
|
15
|
+
* POST {runtime}/datasets/<name>/query -> DatasetQueryResponse
|
|
16
|
+
*
|
|
17
|
+
* Core checks the declaration at upload, checks each request against it
|
|
18
|
+
* before it calls the module, and checks each answer against it before any
|
|
19
|
+
* view uses the rows. Module output is data, never code.
|
|
20
|
+
*/
|
|
21
|
+
import { z } from 'zod';
|
|
22
|
+
/** What a value is. */
|
|
23
|
+
export declare const DATASET_FIELD_TYPES: readonly ["text", "number", "boolean", "datetime", "enum", "url", "tags"];
|
|
24
|
+
/**
|
|
25
|
+
* What a value means to a view. Each role is used at most once in a dataset,
|
|
26
|
+
* and every dataset has a `title`. A role allows only the types that can carry
|
|
27
|
+
* its meaning: a due date is a time, an owner is a name.
|
|
28
|
+
*/
|
|
29
|
+
export declare const DATASET_FIELD_ROLES: {
|
|
30
|
+
readonly title: readonly ["text"];
|
|
31
|
+
readonly subtitle: readonly ["text"];
|
|
32
|
+
readonly status: readonly ["enum"];
|
|
33
|
+
readonly stage: readonly ["enum"];
|
|
34
|
+
readonly owner: readonly ["text"];
|
|
35
|
+
readonly due: readonly ["datetime"];
|
|
36
|
+
readonly amount: readonly ["number"];
|
|
37
|
+
};
|
|
38
|
+
export type DatasetFieldType = (typeof DATASET_FIELD_TYPES)[number];
|
|
39
|
+
export type DatasetFieldRole = keyof typeof DATASET_FIELD_ROLES;
|
|
40
|
+
export declare const DATASET_LIMITS: {
|
|
41
|
+
readonly fields: 32;
|
|
42
|
+
readonly datasets: 16;
|
|
43
|
+
readonly options: 50;
|
|
44
|
+
readonly rows: 200;
|
|
45
|
+
readonly defaultRows: 50;
|
|
46
|
+
readonly filters: 8;
|
|
47
|
+
readonly text: 500;
|
|
48
|
+
readonly tags: 20;
|
|
49
|
+
};
|
|
50
|
+
export declare const datasetFieldSchema: z.ZodObject<{
|
|
51
|
+
name: z.ZodString;
|
|
52
|
+
label: z.ZodString;
|
|
53
|
+
type: z.ZodEnum<{
|
|
54
|
+
number: "number";
|
|
55
|
+
boolean: "boolean";
|
|
56
|
+
text: "text";
|
|
57
|
+
datetime: "datetime";
|
|
58
|
+
enum: "enum";
|
|
59
|
+
url: "url";
|
|
60
|
+
tags: "tags";
|
|
61
|
+
}>;
|
|
62
|
+
role: z.ZodOptional<z.ZodEnum<{
|
|
63
|
+
title: "title";
|
|
64
|
+
subtitle: "subtitle";
|
|
65
|
+
status: "status";
|
|
66
|
+
stage: "stage";
|
|
67
|
+
owner: "owner";
|
|
68
|
+
due: "due";
|
|
69
|
+
amount: "amount";
|
|
70
|
+
}>>;
|
|
71
|
+
options: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
72
|
+
value: z.ZodString;
|
|
73
|
+
label: z.ZodString;
|
|
74
|
+
tone: z.ZodDefault<z.ZodEnum<{
|
|
75
|
+
default: "default";
|
|
76
|
+
success: "success";
|
|
77
|
+
warning: "warning";
|
|
78
|
+
destructive: "destructive";
|
|
79
|
+
}>>;
|
|
80
|
+
}, z.core.$strip>>>;
|
|
81
|
+
filterable: z.ZodDefault<z.ZodBoolean>;
|
|
82
|
+
sortable: z.ZodDefault<z.ZodBoolean>;
|
|
83
|
+
}, z.core.$strip>;
|
|
84
|
+
/** One dataset as the manifest carries it: the declaration plus its name. */
|
|
85
|
+
export declare const datasetDeclarationSchema: z.ZodObject<{
|
|
86
|
+
label: z.ZodString;
|
|
87
|
+
description: z.ZodOptional<z.ZodString>;
|
|
88
|
+
key: z.ZodString;
|
|
89
|
+
fields: z.ZodArray<z.ZodObject<{
|
|
90
|
+
name: z.ZodString;
|
|
91
|
+
label: z.ZodString;
|
|
92
|
+
type: z.ZodEnum<{
|
|
93
|
+
number: "number";
|
|
94
|
+
boolean: "boolean";
|
|
95
|
+
text: "text";
|
|
96
|
+
datetime: "datetime";
|
|
97
|
+
enum: "enum";
|
|
98
|
+
url: "url";
|
|
99
|
+
tags: "tags";
|
|
100
|
+
}>;
|
|
101
|
+
role: z.ZodOptional<z.ZodEnum<{
|
|
102
|
+
title: "title";
|
|
103
|
+
subtitle: "subtitle";
|
|
104
|
+
status: "status";
|
|
105
|
+
stage: "stage";
|
|
106
|
+
owner: "owner";
|
|
107
|
+
due: "due";
|
|
108
|
+
amount: "amount";
|
|
109
|
+
}>>;
|
|
110
|
+
options: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
111
|
+
value: z.ZodString;
|
|
112
|
+
label: z.ZodString;
|
|
113
|
+
tone: z.ZodDefault<z.ZodEnum<{
|
|
114
|
+
default: "default";
|
|
115
|
+
success: "success";
|
|
116
|
+
warning: "warning";
|
|
117
|
+
destructive: "destructive";
|
|
118
|
+
}>>;
|
|
119
|
+
}, z.core.$strip>>>;
|
|
120
|
+
filterable: z.ZodDefault<z.ZodBoolean>;
|
|
121
|
+
sortable: z.ZodDefault<z.ZodBoolean>;
|
|
122
|
+
}, z.core.$strip>>;
|
|
123
|
+
search: z.ZodDefault<z.ZodBoolean>;
|
|
124
|
+
defaultSort: z.ZodOptional<z.ZodObject<{
|
|
125
|
+
field: z.ZodString;
|
|
126
|
+
direction: z.ZodDefault<z.ZodEnum<{
|
|
127
|
+
asc: "asc";
|
|
128
|
+
desc: "desc";
|
|
129
|
+
}>>;
|
|
130
|
+
}, z.core.$strip>>;
|
|
131
|
+
name: z.ZodString;
|
|
132
|
+
}, z.core.$strip>;
|
|
133
|
+
/** Every dataset a module declares. Generated into entry.json `manifest.datasets`. */
|
|
134
|
+
export declare const datasetManifestSchema: z.ZodArray<z.ZodObject<{
|
|
135
|
+
label: z.ZodString;
|
|
136
|
+
description: z.ZodOptional<z.ZodString>;
|
|
137
|
+
key: z.ZodString;
|
|
138
|
+
fields: z.ZodArray<z.ZodObject<{
|
|
139
|
+
name: z.ZodString;
|
|
140
|
+
label: z.ZodString;
|
|
141
|
+
type: z.ZodEnum<{
|
|
142
|
+
number: "number";
|
|
143
|
+
boolean: "boolean";
|
|
144
|
+
text: "text";
|
|
145
|
+
datetime: "datetime";
|
|
146
|
+
enum: "enum";
|
|
147
|
+
url: "url";
|
|
148
|
+
tags: "tags";
|
|
149
|
+
}>;
|
|
150
|
+
role: z.ZodOptional<z.ZodEnum<{
|
|
151
|
+
title: "title";
|
|
152
|
+
subtitle: "subtitle";
|
|
153
|
+
status: "status";
|
|
154
|
+
stage: "stage";
|
|
155
|
+
owner: "owner";
|
|
156
|
+
due: "due";
|
|
157
|
+
amount: "amount";
|
|
158
|
+
}>>;
|
|
159
|
+
options: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
160
|
+
value: z.ZodString;
|
|
161
|
+
label: z.ZodString;
|
|
162
|
+
tone: z.ZodDefault<z.ZodEnum<{
|
|
163
|
+
default: "default";
|
|
164
|
+
success: "success";
|
|
165
|
+
warning: "warning";
|
|
166
|
+
destructive: "destructive";
|
|
167
|
+
}>>;
|
|
168
|
+
}, z.core.$strip>>>;
|
|
169
|
+
filterable: z.ZodDefault<z.ZodBoolean>;
|
|
170
|
+
sortable: z.ZodDefault<z.ZodBoolean>;
|
|
171
|
+
}, z.core.$strip>>;
|
|
172
|
+
search: z.ZodDefault<z.ZodBoolean>;
|
|
173
|
+
defaultSort: z.ZodOptional<z.ZodObject<{
|
|
174
|
+
field: z.ZodString;
|
|
175
|
+
direction: z.ZodDefault<z.ZodEnum<{
|
|
176
|
+
asc: "asc";
|
|
177
|
+
desc: "desc";
|
|
178
|
+
}>>;
|
|
179
|
+
}, z.core.$strip>>;
|
|
180
|
+
name: z.ZodString;
|
|
181
|
+
}, z.core.$strip>>;
|
|
182
|
+
/** What a view asks for. Core checks it against the declaration before the module sees it. */
|
|
183
|
+
export declare const datasetQueryRequestSchema: z.ZodObject<{
|
|
184
|
+
filters: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
185
|
+
search: z.ZodOptional<z.ZodString>;
|
|
186
|
+
sort: z.ZodOptional<z.ZodObject<{
|
|
187
|
+
field: z.ZodString;
|
|
188
|
+
direction: z.ZodDefault<z.ZodEnum<{
|
|
189
|
+
asc: "asc";
|
|
190
|
+
desc: "desc";
|
|
191
|
+
}>>;
|
|
192
|
+
}, z.core.$strip>>;
|
|
193
|
+
limit: z.ZodDefault<z.ZodNumber>;
|
|
194
|
+
cursor: z.ZodOptional<z.ZodString>;
|
|
195
|
+
}, z.core.$strip>;
|
|
196
|
+
export declare const datasetRowSchema: z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodArray<z.ZodString>]>>>;
|
|
197
|
+
export declare const datasetQueryResponseSchema: z.ZodObject<{
|
|
198
|
+
rows: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodArray<z.ZodString>]>>>>;
|
|
199
|
+
nextCursor: z.ZodOptional<z.ZodString>;
|
|
200
|
+
total: z.ZodOptional<z.ZodNumber>;
|
|
201
|
+
note: z.ZodOptional<z.ZodString>;
|
|
202
|
+
}, z.core.$strip>;
|
|
203
|
+
export type DatasetField = z.infer<typeof datasetFieldSchema>;
|
|
204
|
+
export type DatasetDeclaration = z.infer<typeof datasetDeclarationSchema>;
|
|
205
|
+
export type DatasetDeclarationInput = z.input<typeof datasetDeclarationSchema>;
|
|
206
|
+
export type DatasetQueryRequest = z.infer<typeof datasetQueryRequestSchema>;
|
|
207
|
+
export type DatasetQueryRequestInput = z.input<typeof datasetQueryRequestSchema>;
|
|
208
|
+
export type DatasetRow = z.infer<typeof datasetRowSchema>;
|
|
209
|
+
export type DatasetQueryResponse = z.infer<typeof datasetQueryResponseSchema>;
|
|
210
|
+
export type DatasetQueryResponseInput = z.input<typeof datasetQueryResponseSchema>;
|
|
211
|
+
/**
|
|
212
|
+
* Problems with a request, against the dataset it names. Empty means the
|
|
213
|
+
* module may run it. Core runs this before it calls the module, and
|
|
214
|
+
* `answerDatasetQuery` runs it again on the module side.
|
|
215
|
+
*/
|
|
216
|
+
export declare function datasetRequestIssues(declaration: DatasetDeclaration, request: DatasetQueryRequest): string[];
|
|
217
|
+
/**
|
|
218
|
+
* Problems with an answer, against the dataset that gave it. Empty means a
|
|
219
|
+
* view may use the rows. Every row needs its key; every value must match its
|
|
220
|
+
* field's type; a value for an undeclared field is refused.
|
|
221
|
+
*/
|
|
222
|
+
export declare function datasetResponseIssues(declaration: DatasetDeclaration, response: DatasetQueryResponse, request?: Pick<DatasetQueryRequest, 'limit'>): string[];
|
|
223
|
+
/** The rows of one page, as a module's `query` returns them. */
|
|
224
|
+
export type DatasetQueryHandler<Ctx> = (ctx: Ctx, request: DatasetQueryRequest) => DatasetQueryResponseInput | Promise<DatasetQueryResponseInput>;
|
|
225
|
+
/** What `ui/datasets/<name>.ts` exports. The file name is the dataset's name. */
|
|
226
|
+
export type DatasetDefinition<Ctx = unknown> = Omit<DatasetDeclarationInput, 'name'> & {
|
|
227
|
+
query: DatasetQueryHandler<Ctx>;
|
|
228
|
+
};
|
|
229
|
+
/**
|
|
230
|
+
* Declare a dataset. The declaration is checked at once, so a mistake fails
|
|
231
|
+
* where it is written, not at upload. Keep the declaration literal (strings,
|
|
232
|
+
* numbers, booleans, arrays, objects): the build reads it without running the
|
|
233
|
+
* file, the way it reads `defineSurface`.
|
|
234
|
+
*/
|
|
235
|
+
export declare function defineDataset<Ctx = unknown>(definition: DatasetDefinition<Ctx>): DatasetDefinition<Ctx>;
|
|
236
|
+
/**
|
|
237
|
+
* Serve one query, for a module's `POST /datasets/:name/query` route: parse the
|
|
238
|
+
* body, check it, run `query`, and check the answer. Returns the status and the
|
|
239
|
+
* body to send. A bad answer is logged with its exact problem here, in the
|
|
240
|
+
* module's own log, because core answers it with a bare 502.
|
|
241
|
+
*/
|
|
242
|
+
export declare function answerDatasetQuery<Ctx>(opts: {
|
|
243
|
+
name: string;
|
|
244
|
+
definition: DatasetDefinition<Ctx>;
|
|
245
|
+
ctx: Ctx;
|
|
246
|
+
body: unknown;
|
|
247
|
+
log?: (message: string) => void;
|
|
248
|
+
}): Promise<{
|
|
249
|
+
status: number;
|
|
250
|
+
body: unknown;
|
|
251
|
+
}>;
|
package/dist/dataset.js
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Datasets — the data half of the UI SDK.
|
|
3
|
+
*
|
|
4
|
+
* A screen is drawn by the module: it returns a tree of blocks. A dataset is
|
|
5
|
+
* data the platform draws: the module declares its fields once, answers a
|
|
6
|
+
* query with rows, and the platform turns the rows into views (a table, a
|
|
7
|
+
* board, a list, a record) built from the same blocks every app already draws.
|
|
8
|
+
*
|
|
9
|
+
* Each field has a type, and may have a role. The type says what a value is
|
|
10
|
+
* (text, a number, a time). The role says what the value means to a view
|
|
11
|
+
* (the title of a row, its status, its owner, when it is due), so a view kind
|
|
12
|
+
* knows where to place it without the module laying anything out.
|
|
13
|
+
*
|
|
14
|
+
* ui/datasets/<name>.ts -> export default defineDataset({ ... })
|
|
15
|
+
* POST {runtime}/datasets/<name>/query -> DatasetQueryResponse
|
|
16
|
+
*
|
|
17
|
+
* Core checks the declaration at upload, checks each request against it
|
|
18
|
+
* before it calls the module, and checks each answer against it before any
|
|
19
|
+
* view uses the rows. Module output is data, never code.
|
|
20
|
+
*/
|
|
21
|
+
import { z } from 'zod';
|
|
22
|
+
const fieldName = z
|
|
23
|
+
.string()
|
|
24
|
+
.max(64)
|
|
25
|
+
.regex(/^[a-z][a-z0-9_]*$/, 'must be lowercase snake_case, starting with a letter');
|
|
26
|
+
const datasetName = z
|
|
27
|
+
.string()
|
|
28
|
+
.max(64)
|
|
29
|
+
.regex(/^[a-z][a-z0-9_-]*$/, 'must be a lowercase slug');
|
|
30
|
+
const tone = z.enum(['default', 'success', 'warning', 'destructive']);
|
|
31
|
+
/** What a value is. */
|
|
32
|
+
export const DATASET_FIELD_TYPES = [
|
|
33
|
+
'text',
|
|
34
|
+
'number',
|
|
35
|
+
'boolean',
|
|
36
|
+
'datetime',
|
|
37
|
+
'enum',
|
|
38
|
+
'url',
|
|
39
|
+
'tags',
|
|
40
|
+
];
|
|
41
|
+
/**
|
|
42
|
+
* What a value means to a view. Each role is used at most once in a dataset,
|
|
43
|
+
* and every dataset has a `title`. A role allows only the types that can carry
|
|
44
|
+
* its meaning: a due date is a time, an owner is a name.
|
|
45
|
+
*/
|
|
46
|
+
export const DATASET_FIELD_ROLES = {
|
|
47
|
+
title: ['text'],
|
|
48
|
+
subtitle: ['text'],
|
|
49
|
+
status: ['enum'],
|
|
50
|
+
stage: ['enum'],
|
|
51
|
+
owner: ['text'],
|
|
52
|
+
due: ['datetime'],
|
|
53
|
+
amount: ['number'],
|
|
54
|
+
};
|
|
55
|
+
const ROLE_NAMES = Object.keys(DATASET_FIELD_ROLES);
|
|
56
|
+
/** Types a person can filter on by picking a value. */
|
|
57
|
+
const FILTERABLE_TYPES = ['enum', 'boolean', 'text'];
|
|
58
|
+
/** Types with an order. */
|
|
59
|
+
const SORTABLE_TYPES = ['text', 'number', 'datetime', 'enum'];
|
|
60
|
+
export const DATASET_LIMITS = {
|
|
61
|
+
fields: 32,
|
|
62
|
+
datasets: 16,
|
|
63
|
+
options: 50,
|
|
64
|
+
rows: 200,
|
|
65
|
+
defaultRows: 50,
|
|
66
|
+
filters: 8,
|
|
67
|
+
text: 500,
|
|
68
|
+
tags: 20,
|
|
69
|
+
};
|
|
70
|
+
export const datasetFieldSchema = z
|
|
71
|
+
.object({
|
|
72
|
+
name: fieldName,
|
|
73
|
+
label: z.string().min(1).max(60),
|
|
74
|
+
type: z.enum(DATASET_FIELD_TYPES),
|
|
75
|
+
role: z.enum(ROLE_NAMES).optional(),
|
|
76
|
+
/** Required for an `enum`, and only allowed there: every value the field can hold. */
|
|
77
|
+
options: z
|
|
78
|
+
.array(z.object({
|
|
79
|
+
value: z.string().min(1).max(64),
|
|
80
|
+
label: z.string().min(1).max(60),
|
|
81
|
+
tone: tone.default('default'),
|
|
82
|
+
}))
|
|
83
|
+
.min(1)
|
|
84
|
+
.max(DATASET_LIMITS.options)
|
|
85
|
+
.optional(),
|
|
86
|
+
/** A view may offer a filter on this field. The module applies it. */
|
|
87
|
+
filterable: z.boolean().default(false),
|
|
88
|
+
/** A view may offer to sort by this field. The module applies it. */
|
|
89
|
+
sortable: z.boolean().default(false),
|
|
90
|
+
})
|
|
91
|
+
.superRefine((field, ctx) => {
|
|
92
|
+
if (field.type === 'enum' && !field.options) {
|
|
93
|
+
ctx.addIssue({ code: 'custom', path: ['options'], message: 'an enum field needs options' });
|
|
94
|
+
}
|
|
95
|
+
if (field.type !== 'enum' && field.options) {
|
|
96
|
+
ctx.addIssue({
|
|
97
|
+
code: 'custom',
|
|
98
|
+
path: ['options'],
|
|
99
|
+
message: 'only an enum field takes options',
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (field.options) {
|
|
103
|
+
const seen = new Set();
|
|
104
|
+
for (const [index, option] of field.options.entries()) {
|
|
105
|
+
if (seen.has(option.value)) {
|
|
106
|
+
ctx.addIssue({
|
|
107
|
+
code: 'custom',
|
|
108
|
+
path: ['options', index, 'value'],
|
|
109
|
+
message: `option "${option.value}" is declared twice`,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
seen.add(option.value);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (field.role) {
|
|
116
|
+
const allowed = DATASET_FIELD_ROLES[field.role];
|
|
117
|
+
if (!allowed.includes(field.type)) {
|
|
118
|
+
ctx.addIssue({
|
|
119
|
+
code: 'custom',
|
|
120
|
+
path: ['role'],
|
|
121
|
+
message: `role "${field.role}" needs a field of type ${allowed.join(' or ')}`,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (field.filterable && !FILTERABLE_TYPES.includes(field.type)) {
|
|
126
|
+
ctx.addIssue({
|
|
127
|
+
code: 'custom',
|
|
128
|
+
path: ['filterable'],
|
|
129
|
+
message: `a ${field.type} field cannot be filtered`,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
if (field.sortable && !SORTABLE_TYPES.includes(field.type)) {
|
|
133
|
+
ctx.addIssue({
|
|
134
|
+
code: 'custom',
|
|
135
|
+
path: ['sortable'],
|
|
136
|
+
message: `a ${field.type} field cannot be sorted`,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
const sortSchema = z.object({
|
|
141
|
+
field: fieldName,
|
|
142
|
+
direction: z.enum(['asc', 'desc']).default('asc'),
|
|
143
|
+
});
|
|
144
|
+
const declarationShape = {
|
|
145
|
+
label: z.string().min(1).max(60),
|
|
146
|
+
description: z.string().max(300).optional(),
|
|
147
|
+
/** The field that identifies a row. A view uses it to open the row as a record. */
|
|
148
|
+
key: fieldName,
|
|
149
|
+
fields: z.array(datasetFieldSchema).min(1).max(DATASET_LIMITS.fields),
|
|
150
|
+
/** True when the module answers a free-text `search`. */
|
|
151
|
+
search: z.boolean().default(false),
|
|
152
|
+
/** The order rows come in when a request names none. Must be a sortable field. */
|
|
153
|
+
defaultSort: sortSchema.optional(),
|
|
154
|
+
};
|
|
155
|
+
function checkDeclaration(declaration, ctx) {
|
|
156
|
+
const byName = new Map();
|
|
157
|
+
for (const [index, field] of declaration.fields.entries()) {
|
|
158
|
+
if (byName.has(field.name)) {
|
|
159
|
+
ctx.addIssue({
|
|
160
|
+
code: 'custom',
|
|
161
|
+
path: ['fields', index, 'name'],
|
|
162
|
+
message: `field "${field.name}" is declared twice`,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
byName.set(field.name, field);
|
|
166
|
+
}
|
|
167
|
+
const key = byName.get(declaration.key);
|
|
168
|
+
if (!key) {
|
|
169
|
+
ctx.addIssue({ code: 'custom', path: ['key'], message: `"${declaration.key}" is not a field` });
|
|
170
|
+
}
|
|
171
|
+
else if (key.type !== 'text' && key.type !== 'number') {
|
|
172
|
+
ctx.addIssue({
|
|
173
|
+
code: 'custom',
|
|
174
|
+
path: ['key'],
|
|
175
|
+
message: 'the key must be a text or number field',
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
const roles = new Map();
|
|
179
|
+
for (const [index, field] of declaration.fields.entries()) {
|
|
180
|
+
if (!field.role)
|
|
181
|
+
continue;
|
|
182
|
+
const previous = roles.get(field.role);
|
|
183
|
+
if (previous) {
|
|
184
|
+
ctx.addIssue({
|
|
185
|
+
code: 'custom',
|
|
186
|
+
path: ['fields', index, 'role'],
|
|
187
|
+
message: `role "${field.role}" is already on field "${previous}"`,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
roles.set(field.role, field.name);
|
|
191
|
+
}
|
|
192
|
+
if (!roles.has('title')) {
|
|
193
|
+
ctx.addIssue({
|
|
194
|
+
code: 'custom',
|
|
195
|
+
path: ['fields'],
|
|
196
|
+
message: 'one text field needs role "title": every view leads a row with it',
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
if (declaration.defaultSort) {
|
|
200
|
+
const field = byName.get(declaration.defaultSort.field);
|
|
201
|
+
if (!field?.sortable) {
|
|
202
|
+
ctx.addIssue({
|
|
203
|
+
code: 'custom',
|
|
204
|
+
path: ['defaultSort', 'field'],
|
|
205
|
+
message: `"${declaration.defaultSort.field}" is not a sortable field`,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/** One dataset as the manifest carries it: the declaration plus its name. */
|
|
211
|
+
export const datasetDeclarationSchema = z
|
|
212
|
+
.object({ name: datasetName, ...declarationShape })
|
|
213
|
+
.superRefine(checkDeclaration);
|
|
214
|
+
/** Every dataset a module declares. Generated into entry.json `manifest.datasets`. */
|
|
215
|
+
export const datasetManifestSchema = z
|
|
216
|
+
.array(datasetDeclarationSchema)
|
|
217
|
+
.max(DATASET_LIMITS.datasets)
|
|
218
|
+
.superRefine((datasets, ctx) => {
|
|
219
|
+
const names = new Set();
|
|
220
|
+
for (const [index, dataset] of datasets.entries()) {
|
|
221
|
+
if (names.has(dataset.name)) {
|
|
222
|
+
ctx.addIssue({
|
|
223
|
+
code: 'custom',
|
|
224
|
+
path: [index, 'name'],
|
|
225
|
+
message: `dataset "${dataset.name}" is declared twice`,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
names.add(dataset.name);
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
/** What a view asks for. Core checks it against the declaration before the module sees it. */
|
|
232
|
+
export const datasetQueryRequestSchema = z.object({
|
|
233
|
+
/** Equality filters, keyed by a filterable field. Booleans are "true" or "false". */
|
|
234
|
+
filters: z.record(fieldName, z.string().max(200)).default({}),
|
|
235
|
+
search: z.string().max(200).optional(),
|
|
236
|
+
sort: sortSchema.optional(),
|
|
237
|
+
limit: z.number().int().min(1).max(DATASET_LIMITS.rows).default(DATASET_LIMITS.defaultRows),
|
|
238
|
+
/** Opaque: whatever `nextCursor` the module returned for the previous page. */
|
|
239
|
+
cursor: z.string().max(500).optional(),
|
|
240
|
+
});
|
|
241
|
+
/**
|
|
242
|
+
* One value. Primitives and a list of tags only: a nested object has no place
|
|
243
|
+
* in a view. Null (written with `.nullable()`, not a `z.null()` union member,
|
|
244
|
+
* which OpenAPI 3.0 cannot express) means the row has no value for the field.
|
|
245
|
+
*/
|
|
246
|
+
const datasetCellSchema = z
|
|
247
|
+
.union([
|
|
248
|
+
z.string().max(DATASET_LIMITS.text),
|
|
249
|
+
z.number().finite(),
|
|
250
|
+
z.boolean(),
|
|
251
|
+
z.array(z.string().min(1).max(40)).max(DATASET_LIMITS.tags),
|
|
252
|
+
])
|
|
253
|
+
.nullable();
|
|
254
|
+
export const datasetRowSchema = z.record(fieldName, datasetCellSchema);
|
|
255
|
+
export const datasetQueryResponseSchema = z.object({
|
|
256
|
+
rows: z.array(datasetRowSchema).max(DATASET_LIMITS.rows),
|
|
257
|
+
/** Set when more rows follow. The view sends it back as `cursor`. */
|
|
258
|
+
nextCursor: z.string().max(500).optional(),
|
|
259
|
+
/** How many rows match in all, when the module knows cheaply. */
|
|
260
|
+
total: z.number().int().min(0).optional(),
|
|
261
|
+
/** Shown as is, for an answer that is partial ("last 90 days only"). */
|
|
262
|
+
note: z.string().max(300).optional(),
|
|
263
|
+
});
|
|
264
|
+
/**
|
|
265
|
+
* Problems with a request, against the dataset it names. Empty means the
|
|
266
|
+
* module may run it. Core runs this before it calls the module, and
|
|
267
|
+
* `answerDatasetQuery` runs it again on the module side.
|
|
268
|
+
*/
|
|
269
|
+
export function datasetRequestIssues(declaration, request) {
|
|
270
|
+
const issues = [];
|
|
271
|
+
const byName = new Map(declaration.fields.map((field) => [field.name, field]));
|
|
272
|
+
const filters = Object.entries(request.filters);
|
|
273
|
+
if (filters.length > DATASET_LIMITS.filters) {
|
|
274
|
+
issues.push(`at most ${DATASET_LIMITS.filters} filters`);
|
|
275
|
+
}
|
|
276
|
+
for (const [name, value] of filters) {
|
|
277
|
+
const field = byName.get(name);
|
|
278
|
+
if (!field?.filterable) {
|
|
279
|
+
issues.push(`"${name}" is not a filterable field`);
|
|
280
|
+
}
|
|
281
|
+
else if (field.type === 'enum' && !field.options?.some((option) => option.value === value)) {
|
|
282
|
+
issues.push(`"${value}" is not an option of "${name}"`);
|
|
283
|
+
}
|
|
284
|
+
else if (field.type === 'boolean' && value !== 'true' && value !== 'false') {
|
|
285
|
+
issues.push(`"${name}" takes "true" or "false"`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (request.sort && !byName.get(request.sort.field)?.sortable) {
|
|
289
|
+
issues.push(`"${request.sort.field}" is not a sortable field`);
|
|
290
|
+
}
|
|
291
|
+
if (request.search !== undefined && !declaration.search) {
|
|
292
|
+
issues.push('this dataset does not take a search');
|
|
293
|
+
}
|
|
294
|
+
return issues;
|
|
295
|
+
}
|
|
296
|
+
function cellIssue(field, value) {
|
|
297
|
+
if (value === null)
|
|
298
|
+
return null;
|
|
299
|
+
switch (field.type) {
|
|
300
|
+
case 'text':
|
|
301
|
+
case 'url':
|
|
302
|
+
return typeof value === 'string' ? null : 'must be a string';
|
|
303
|
+
case 'number':
|
|
304
|
+
return typeof value === 'number' ? null : 'must be a number';
|
|
305
|
+
case 'boolean':
|
|
306
|
+
return typeof value === 'boolean' ? null : 'must be a boolean';
|
|
307
|
+
case 'datetime':
|
|
308
|
+
return typeof value === 'string' && !Number.isNaN(Date.parse(value))
|
|
309
|
+
? null
|
|
310
|
+
: 'must be an ISO 8601 date and time';
|
|
311
|
+
case 'enum':
|
|
312
|
+
return typeof value === 'string' && field.options?.some((option) => option.value === value)
|
|
313
|
+
? null
|
|
314
|
+
: 'must be one of the declared options';
|
|
315
|
+
case 'tags':
|
|
316
|
+
return Array.isArray(value) ? null : 'must be a list of tags';
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Problems with an answer, against the dataset that gave it. Empty means a
|
|
321
|
+
* view may use the rows. Every row needs its key; every value must match its
|
|
322
|
+
* field's type; a value for an undeclared field is refused.
|
|
323
|
+
*/
|
|
324
|
+
export function datasetResponseIssues(declaration, response, request) {
|
|
325
|
+
const issues = [];
|
|
326
|
+
const byName = new Map(declaration.fields.map((field) => [field.name, field]));
|
|
327
|
+
if (request && response.rows.length > request.limit) {
|
|
328
|
+
issues.push(`${response.rows.length} rows for a limit of ${request.limit}`);
|
|
329
|
+
}
|
|
330
|
+
const keys = new Set();
|
|
331
|
+
for (const [index, row] of response.rows.entries()) {
|
|
332
|
+
const key = row[declaration.key];
|
|
333
|
+
if (key === undefined || key === null || key === '') {
|
|
334
|
+
issues.push(`rows[${index}]: no value for the key "${declaration.key}"`);
|
|
335
|
+
}
|
|
336
|
+
else if (keys.has(String(key))) {
|
|
337
|
+
issues.push(`rows[${index}]: key "${String(key)}" is repeated`);
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
keys.add(String(key));
|
|
341
|
+
}
|
|
342
|
+
for (const [name, value] of Object.entries(row)) {
|
|
343
|
+
const field = byName.get(name);
|
|
344
|
+
if (!field) {
|
|
345
|
+
issues.push(`rows[${index}].${name}: not a declared field`);
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
const problem = cellIssue(field, value);
|
|
349
|
+
if (problem)
|
|
350
|
+
issues.push(`rows[${index}].${name}: ${problem}`);
|
|
351
|
+
}
|
|
352
|
+
if (issues.length >= 10)
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
return issues;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Declare a dataset. The declaration is checked at once, so a mistake fails
|
|
359
|
+
* where it is written, not at upload. Keep the declaration literal (strings,
|
|
360
|
+
* numbers, booleans, arrays, objects): the build reads it without running the
|
|
361
|
+
* file, the way it reads `defineSurface`.
|
|
362
|
+
*/
|
|
363
|
+
export function defineDataset(definition) {
|
|
364
|
+
const { query, ...declaration } = definition;
|
|
365
|
+
if (typeof query !== 'function')
|
|
366
|
+
throw new Error('defineDataset: query must be a function');
|
|
367
|
+
const parsed = datasetDeclarationSchema.safeParse({ name: 'dataset', ...declaration });
|
|
368
|
+
if (!parsed.success) {
|
|
369
|
+
const issue = parsed.error.issues[0];
|
|
370
|
+
throw new Error(`defineDataset: ${issue?.path.join('.') || 'declaration'} ${issue?.message ?? 'is invalid'}`);
|
|
371
|
+
}
|
|
372
|
+
return definition;
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Serve one query, for a module's `POST /datasets/:name/query` route: parse the
|
|
376
|
+
* body, check it, run `query`, and check the answer. Returns the status and the
|
|
377
|
+
* body to send. A bad answer is logged with its exact problem here, in the
|
|
378
|
+
* module's own log, because core answers it with a bare 502.
|
|
379
|
+
*/
|
|
380
|
+
export async function answerDatasetQuery(opts) {
|
|
381
|
+
const log = opts.log ?? ((message) => console.error(message));
|
|
382
|
+
const { query, ...rest } = opts.definition;
|
|
383
|
+
const declaration = datasetDeclarationSchema.parse({ name: opts.name, ...rest });
|
|
384
|
+
const request = datasetQueryRequestSchema.safeParse(opts.body ?? {});
|
|
385
|
+
if (!request.success) {
|
|
386
|
+
return { status: 400, body: { error: 'invalid dataset query' } };
|
|
387
|
+
}
|
|
388
|
+
const refused = datasetRequestIssues(declaration, request.data);
|
|
389
|
+
if (refused.length > 0)
|
|
390
|
+
return { status: 400, body: { error: refused[0] } };
|
|
391
|
+
let answer;
|
|
392
|
+
try {
|
|
393
|
+
answer = await query(opts.ctx, request.data);
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
log(`[datasets] ${opts.name}.query threw: ${error instanceof Error ? error.message : error}`);
|
|
397
|
+
return { status: 500, body: { error: 'query failed' } };
|
|
398
|
+
}
|
|
399
|
+
const parsed = datasetQueryResponseSchema.safeParse(answer);
|
|
400
|
+
const issues = parsed.success
|
|
401
|
+
? datasetResponseIssues(declaration, parsed.data, request.data)
|
|
402
|
+
: parsed.error.issues.slice(0, 3).map((issue) => `${issue.path.join('.')}: ${issue.message}`);
|
|
403
|
+
if (!parsed.success || issues.length > 0) {
|
|
404
|
+
log(`[datasets] ${opts.name}.query gave an invalid answer: ${issues.join('; ')}`);
|
|
405
|
+
return { status: 500, body: { error: 'the dataset produced an invalid answer' } };
|
|
406
|
+
}
|
|
407
|
+
return { status: 200, body: parsed.data };
|
|
408
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export { composerPress, composerShortcut } from './composer.js';
|
|
|
10
10
|
export type { ComposerKey, ComposerShortcut } from './composer.js';
|
|
11
11
|
export { addDays, calendarDays, dayStartMs, entriesOnDay, placeEntries, shiftCalendarDate, slotIsFree, slotTimes, todayIn, } from './calendar.js';
|
|
12
12
|
export type { CalendarEntryLike, CalendarView, PlacedEntry } from './calendar.js';
|
|
13
|
+
export { DATASET_FIELD_ROLES, DATASET_FIELD_TYPES, DATASET_LIMITS, answerDatasetQuery, datasetDeclarationSchema, datasetFieldSchema, datasetManifestSchema, datasetQueryRequestSchema, datasetQueryResponseSchema, datasetRequestIssues, datasetResponseIssues, datasetRowSchema, defineDataset, } from './dataset.js';
|
|
14
|
+
export type { DatasetDeclaration, DatasetDeclarationInput, DatasetDefinition, DatasetField, DatasetFieldRole, DatasetFieldType, DatasetQueryHandler, DatasetQueryRequest, DatasetQueryRequestInput, DatasetQueryResponse, DatasetQueryResponseInput, DatasetRow, } from './dataset.js';
|
|
13
15
|
export { defineScreen, defineSurface } from './define.js';
|
|
14
16
|
export type { ScreenDefinition, ScreenParams, LoadHandler, ActionHandler, JobHandler, } from './define.js';
|
|
15
17
|
export { loadWebsiteChat, websiteChatSnippet } from './website-chat.js';
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,7 @@ export { MEDIA_CONTENT_TYPES, mediaContentType, mediaPathOf } from './media.js';
|
|
|
13
13
|
export { initialDraft, isoToLocalInput, localInputToIso, postedValue } from './form.js';
|
|
14
14
|
export { composerPress, composerShortcut } from './composer.js';
|
|
15
15
|
export { addDays, calendarDays, dayStartMs, entriesOnDay, placeEntries, shiftCalendarDate, slotIsFree, slotTimes, todayIn, } from './calendar.js';
|
|
16
|
+
export { DATASET_FIELD_ROLES, DATASET_FIELD_TYPES, DATASET_LIMITS, answerDatasetQuery, datasetDeclarationSchema, datasetFieldSchema, datasetManifestSchema, datasetQueryRequestSchema, datasetQueryResponseSchema, datasetRequestIssues, datasetResponseIssues, datasetRowSchema, defineDataset, } from './dataset.js';
|
|
16
17
|
export { defineScreen, defineSurface } from './define.js';
|
|
17
18
|
export { loadWebsiteChat, websiteChatSnippet } from './website-chat.js';
|
|
18
19
|
export { createWidgetClient } from './widget.js';
|
package/dist/schema.d.ts
CHANGED
|
@@ -53,8 +53,8 @@ export declare const cellSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
53
53
|
kind: z.ZodLiteral<"badge">;
|
|
54
54
|
value: z.ZodString;
|
|
55
55
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
56
|
-
success: "success";
|
|
57
56
|
default: "default";
|
|
57
|
+
success: "success";
|
|
58
58
|
warning: "warning";
|
|
59
59
|
destructive: "destructive";
|
|
60
60
|
}>>;
|
|
@@ -113,10 +113,10 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
113
113
|
fields: z.ZodArray<z.ZodObject<{
|
|
114
114
|
kind: z.ZodEnum<{
|
|
115
115
|
number: "number";
|
|
116
|
-
date: "date";
|
|
117
116
|
text: "text";
|
|
118
|
-
select: "select";
|
|
119
117
|
datetime: "datetime";
|
|
118
|
+
date: "date";
|
|
119
|
+
select: "select";
|
|
120
120
|
textarea: "textarea";
|
|
121
121
|
checkbox: "checkbox";
|
|
122
122
|
multiselect: "multiselect";
|
|
@@ -195,8 +195,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
195
195
|
kind: z.ZodLiteral<"badge">;
|
|
196
196
|
value: z.ZodString;
|
|
197
197
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
198
|
-
success: "success";
|
|
199
198
|
default: "default";
|
|
199
|
+
success: "success";
|
|
200
200
|
warning: "warning";
|
|
201
201
|
destructive: "destructive";
|
|
202
202
|
}>>;
|
|
@@ -450,8 +450,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
450
450
|
kind: z.ZodLiteral<"badge">;
|
|
451
451
|
value: z.ZodString;
|
|
452
452
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
453
|
-
success: "success";
|
|
454
453
|
default: "default";
|
|
454
|
+
success: "success";
|
|
455
455
|
warning: "warning";
|
|
456
456
|
destructive: "destructive";
|
|
457
457
|
}>>;
|
|
@@ -464,8 +464,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
464
464
|
type: z.ZodLiteral<"timestamp">;
|
|
465
465
|
value: z.ZodISODateTime;
|
|
466
466
|
style: z.ZodDefault<z.ZodEnum<{
|
|
467
|
-
date: "date";
|
|
468
467
|
datetime: "datetime";
|
|
468
|
+
date: "date";
|
|
469
469
|
relative: "relative";
|
|
470
470
|
}>>;
|
|
471
471
|
label: z.ZodOptional<z.ZodString>;
|
|
@@ -477,8 +477,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
477
477
|
key: z.ZodString;
|
|
478
478
|
label: z.ZodString;
|
|
479
479
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
480
|
-
success: "success";
|
|
481
480
|
default: "default";
|
|
481
|
+
success: "success";
|
|
482
482
|
warning: "warning";
|
|
483
483
|
destructive: "destructive";
|
|
484
484
|
}>>;
|
|
@@ -493,8 +493,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
493
493
|
kind: z.ZodLiteral<"badge">;
|
|
494
494
|
value: z.ZodString;
|
|
495
495
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
496
|
-
success: "success";
|
|
497
496
|
default: "default";
|
|
497
|
+
success: "success";
|
|
498
498
|
warning: "warning";
|
|
499
499
|
destructive: "destructive";
|
|
500
500
|
}>>;
|
|
@@ -527,8 +527,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
527
527
|
items: z.ZodArray<z.ZodObject<{
|
|
528
528
|
label: z.ZodString;
|
|
529
529
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
530
|
-
success: "success";
|
|
531
530
|
default: "default";
|
|
531
|
+
success: "success";
|
|
532
532
|
warning: "warning";
|
|
533
533
|
destructive: "destructive";
|
|
534
534
|
}>>;
|
|
@@ -577,8 +577,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
577
577
|
value: z.ZodNumber;
|
|
578
578
|
max: z.ZodDefault<z.ZodNumber>;
|
|
579
579
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
580
|
-
success: "success";
|
|
581
580
|
default: "default";
|
|
581
|
+
success: "success";
|
|
582
582
|
warning: "warning";
|
|
583
583
|
destructive: "destructive";
|
|
584
584
|
}>>;
|
|
@@ -602,8 +602,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
602
602
|
channel: z.ZodOptional<z.ZodString>;
|
|
603
603
|
status: z.ZodOptional<z.ZodString>;
|
|
604
604
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
605
|
-
success: "success";
|
|
606
605
|
default: "default";
|
|
606
|
+
success: "success";
|
|
607
607
|
warning: "warning";
|
|
608
608
|
destructive: "destructive";
|
|
609
609
|
}>>;
|
|
@@ -688,8 +688,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
688
688
|
end: z.ZodISODateTime;
|
|
689
689
|
resource: z.ZodOptional<z.ZodString>;
|
|
690
690
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
691
|
-
success: "success";
|
|
692
691
|
default: "default";
|
|
692
|
+
success: "success";
|
|
693
693
|
warning: "warning";
|
|
694
694
|
destructive: "destructive";
|
|
695
695
|
}>>;
|
|
@@ -703,8 +703,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
703
703
|
kind: z.ZodLiteral<"badge">;
|
|
704
704
|
value: z.ZodString;
|
|
705
705
|
tone: z.ZodDefault<z.ZodEnum<{
|
|
706
|
-
success: "success";
|
|
707
706
|
default: "default";
|
|
707
|
+
success: "success";
|
|
708
708
|
warning: "warning";
|
|
709
709
|
destructive: "destructive";
|
|
710
710
|
}>>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@keemakr/ui-sdk",
|
|
3
|
-
"version": "1.4.0-dev-
|
|
3
|
+
"version": "1.4.0-dev-20261013150327",
|
|
4
4
|
"description": "Product screens for keemakr marketplace modules: a versioned, server-driven UI tree schema plus defineScreen() handlers. Module code never ships to the browser — keemakr-core validates the tree and renders it with platform components.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|