@keemakr/ui-sdk 1.4.0-dev-20261013220814 → 1.4.0-dev-20261013225946

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.js CHANGED
@@ -66,7 +66,8 @@ function declarationValue(expression) {
66
66
  }
67
67
  /**
68
68
  * Read `export default defineDataset({ ... })` without running the file. Every
69
- * property but `query` must be a literal; `query` must be there.
69
+ * property but `query` and `create` must be a literal; `query` must be there,
70
+ * and `create` must be there exactly when the declaration has `accepts.create`.
70
71
  */
71
72
  async function readDatasetDeclaration(path, name) {
72
73
  const source = ts.createSourceFile(path, await readFile(path, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
@@ -87,6 +88,7 @@ async function readDatasetDeclaration(path, name) {
87
88
  throw new Error(`${path}: default export must be defineDataset({ ... })`);
88
89
  const raw = { name };
89
90
  let hasQuery = false;
91
+ let hasCreate = false;
90
92
  for (const property of object.properties) {
91
93
  const key = property.name;
92
94
  if (!key || (!ts.isIdentifier(key) && !ts.isStringLiteral(key))) {
@@ -96,6 +98,10 @@ async function readDatasetDeclaration(path, name) {
96
98
  hasQuery = true;
97
99
  continue;
98
100
  }
101
+ if (key.text === 'create') {
102
+ hasCreate = true;
103
+ continue;
104
+ }
99
105
  if (key.text === 'name') {
100
106
  throw new Error(`${path}: the file name is the dataset's name; remove "name"`);
101
107
  }
@@ -111,6 +117,13 @@ async function readDatasetDeclaration(path, name) {
111
117
  }
112
118
  if (!hasQuery)
113
119
  throw new Error(`${path}: a dataset needs a query function`);
120
+ const accepts = raw.accepts;
121
+ if (accepts?.create && !hasCreate) {
122
+ throw new Error(`${path}: accepts.create needs a create function`);
123
+ }
124
+ if (hasCreate && !accepts?.create) {
125
+ throw new Error(`${path}: a create function needs accepts.create`);
126
+ }
114
127
  return raw;
115
128
  }
116
129
  /** Each `ui/datasets/<name>.ts`, sorted by name. Test files are left out. */
@@ -25,7 +25,7 @@
25
25
  */
26
26
  import { z } from 'zod';
27
27
  import { type DatasetDeclaration, type DatasetField, type DatasetQueryRequestInput, type DatasetQueryResponse, type DatasetRow } from './dataset.js';
28
- export declare const DATASET_LAYOUTS: readonly ["table", "board", "list", "record"];
28
+ export declare const DATASET_LAYOUTS: readonly ["table", "board", "list", "record", "chart"];
29
29
  export type DatasetLayout = (typeof DATASET_LAYOUTS)[number];
30
30
  /** Deepest page a table reaches. Paging walks cursors from page 1. */
31
31
  export declare const DATASET_MAX_PAGE = 20;
@@ -37,6 +37,7 @@ export declare const datasetNodeSchema: z.ZodObject<{
37
37
  table: "table";
38
38
  board: "board";
39
39
  list: "list";
40
+ chart: "chart";
40
41
  }>>;
41
42
  fields: z.ZodOptional<z.ZodArray<z.ZodString>>;
42
43
  filters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
@@ -49,12 +50,20 @@ export declare const datasetNodeSchema: z.ZodObject<{
49
50
  }, z.core.$strip>>;
50
51
  limit: z.ZodDefault<z.ZodNumber>;
51
52
  groupBy: z.ZodOptional<z.ZodString>;
53
+ chart: z.ZodOptional<z.ZodObject<{
54
+ form: z.ZodDefault<z.ZodEnum<{
55
+ bars: "bars";
56
+ funnel: "funnel";
57
+ }>>;
58
+ measure: z.ZodOptional<z.ZodString>;
59
+ }, z.core.$strip>>;
52
60
  open: z.ZodOptional<z.ZodObject<{
53
61
  screen: z.ZodString;
54
62
  param: z.ZodDefault<z.ZodString>;
55
63
  }, z.core.$strip>>;
56
64
  param: z.ZodDefault<z.ZodString>;
57
65
  empty: z.ZodDefault<z.ZodString>;
66
+ create: z.ZodDefault<z.ZodBoolean>;
58
67
  }, z.core.$strip>;
59
68
  export type DatasetNode = z.infer<typeof datasetNodeSchema>;
60
69
  export type DatasetNodeInput = z.input<typeof datasetNodeSchema>;
@@ -127,4 +136,25 @@ export declare function compileDatasetNode(opts: {
127
136
  page: number;
128
137
  hasMore: boolean;
129
138
  }): Record<string, unknown>[];
139
+ /**
140
+ * The screen param that opens a dataset's create form: its value is the
141
+ * dataset's name. Reserved on every screen that shows a dataset.
142
+ */
143
+ export declare const DATASET_NEW_PARAM = "new";
144
+ /**
145
+ * The action a create form submits. Core answers it itself: it checks the input
146
+ * against the declaration and calls the module's `create`. A module never
147
+ * receives it, so no module screen may name an action this.
148
+ */
149
+ export declare const DATASET_CREATE_ACTION = "kee-dataset-create";
150
+ /**
151
+ * The create affordance for a dataset node: a button that opens the form, or,
152
+ * once the `new` param names this dataset, the form itself with Cancel. Empty
153
+ * when the dataset takes no new rows, the node turns it off, or it is a record.
154
+ */
155
+ export declare function compileDatasetCreate(opts: {
156
+ node: DatasetNode;
157
+ declaration: DatasetDeclaration;
158
+ screen: DatasetScreenContext;
159
+ }): Record<string, unknown>[];
130
160
  export {};
@@ -33,7 +33,7 @@ const fieldName = z
33
33
  .string()
34
34
  .max(64)
35
35
  .regex(/^[a-z][a-z0-9_]*$/, 'must be lowercase snake_case, starting with a letter');
36
- export const DATASET_LAYOUTS = ['table', 'board', 'list', 'record'];
36
+ export const DATASET_LAYOUTS = ['table', 'board', 'list', 'record', 'chart'];
37
37
  /** Deepest page a table reaches. Paging walks cursors from page 1. */
38
38
  export const DATASET_MAX_PAGE = 20;
39
39
  export const datasetNodeSchema = z.object({
@@ -54,8 +54,23 @@ export const datasetNodeSchema = z.object({
54
54
  .optional(),
55
55
  /** Rows per page for a table; the most cards for a board. */
56
56
  limit: z.number().int().min(1).max(100).default(25),
57
- /** The board's columns: an enum field. Defaults to the stage field, then the status field. */
57
+ /**
58
+ * The board's columns, or the chart's bars: an enum field. Defaults to the
59
+ * stage field, then the status field.
60
+ */
58
61
  groupBy: fieldName.optional(),
62
+ /**
63
+ * For a chart. `bars`: one bar per option of `groupBy`. `funnel`: how many
64
+ * reached each step, in option order; an option with a destructive tone (a
65
+ * lost deal) is an exit, not a step. `measure` sums a number field instead
66
+ * of counting rows. A chart reads up to 200 rows.
67
+ */
68
+ chart: z
69
+ .object({
70
+ form: z.enum(['bars', 'funnel']).default('bars'),
71
+ measure: fieldName.optional(),
72
+ })
73
+ .optional(),
59
74
  /**
60
75
  * Pressing a row or card opens this screen, with the row's key under `param`.
61
76
  * A list without it opens the row beside the list.
@@ -68,6 +83,11 @@ export const datasetNodeSchema = z.object({
68
83
  param: slug.default('id'),
69
84
  /** Shown when no rows match. */
70
85
  empty: z.string().min(1).max(80).default('Nothing here yet'),
86
+ /**
87
+ * Offer the dataset's create form above the rows, when the dataset declares
88
+ * `accepts.create`. False keeps this view read-only.
89
+ */
90
+ create: z.boolean().default(true),
71
91
  });
72
92
  /** Problems with a node against its dataset. Core shows these, never a broken view. */
73
93
  export function datasetNodeIssues(node, declaration) {
@@ -84,6 +104,17 @@ export function datasetNodeIssues(node, declaration) {
84
104
  else if ((group.options?.length ?? 0) > 8)
85
105
  issues.push('a board shows at most 8 columns');
86
106
  }
107
+ if (node.layout === 'chart') {
108
+ if (!boardGroupField(node, declaration)) {
109
+ issues.push('a chart needs an enum field to group by (a stage or a status)');
110
+ }
111
+ const measure = node.chart?.measure;
112
+ if (measure && byName.get(measure)?.type !== 'number') {
113
+ issues.push(`a chart can only add up a number field, and "${measure}" is not one`);
114
+ }
115
+ }
116
+ if (node.chart && node.layout !== 'chart')
117
+ issues.push('only a chart takes chart settings');
87
118
  return issues;
88
119
  }
89
120
  function boardGroupField(node, declaration) {
@@ -92,6 +123,82 @@ function boardGroupField(node, declaration) {
92
123
  return enums.find((field) => field.name === node.groupBy);
93
124
  return enums.find((f) => f.role === 'stage') ?? enums.find((f) => f.role === 'status');
94
125
  }
126
+ const NUMBER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 });
127
+ /** Bars or a funnel over the rows, with the totals above them. */
128
+ function compileDatasetChart(node, declaration, response, hasMore) {
129
+ const group = boardGroupField(node, declaration);
130
+ const measure = node.chart?.measure
131
+ ? declaration.fields.find((field) => field.name === node.chart?.measure)
132
+ : undefined;
133
+ const funnel = node.chart?.form === 'funnel';
134
+ const valueOf = (row) => {
135
+ if (!measure)
136
+ return 1;
137
+ const value = row[measure.name];
138
+ return typeof value === 'number' ? value : 0;
139
+ };
140
+ const options = (group.options ?? []).filter((option) => !funnel || option.tone !== 'destructive');
141
+ const index = new Map(options.map((option, i) => [option.value, i]));
142
+ const values = options.map(() => 0);
143
+ for (const row of response.rows) {
144
+ const at = index.get(String(row[group.name]));
145
+ if (at === undefined)
146
+ continue;
147
+ // A funnel counts a row at its own step and at every step before it: it reached them.
148
+ if (funnel)
149
+ for (let i = 0; i <= at; i += 1)
150
+ values[i] += valueOf(row);
151
+ else
152
+ values[at] += valueOf(row);
153
+ }
154
+ const rounded = values.map((value) => Math.round(value * 100) / 100);
155
+ const total = response.rows.reduce((sum, row) => sum + valueOf(row), 0);
156
+ const unit = measure ? measure.label : declaration.label;
157
+ const stats = [
158
+ {
159
+ type: 'stat',
160
+ label: declaration.label.slice(0, 80),
161
+ value: NUMBER.format(response.rows.length),
162
+ },
163
+ ...(measure
164
+ ? [
165
+ {
166
+ type: 'stat',
167
+ label: `Total ${measure.label}`.slice(0, 80),
168
+ value: NUMBER.format(total),
169
+ },
170
+ ]
171
+ : []),
172
+ ];
173
+ const out = [
174
+ { type: 'section', layout: 'row', children: stats },
175
+ {
176
+ type: 'chart',
177
+ chartType: 'bar',
178
+ title: `${unit} ${funnel ? 'reaching each' : 'by'} ${group.label.toLowerCase()}`.slice(0, 120),
179
+ orientation: funnel ? 'horizontal' : 'vertical',
180
+ showValues: true,
181
+ categories: options.map((option) => option.label.slice(0, 80)),
182
+ series: [{ name: unit.slice(0, 80), values: rounded }],
183
+ },
184
+ ];
185
+ if (funnel && options.length > 1) {
186
+ const steps = options.slice(1).map((option, i) => {
187
+ const before = rounded[i];
188
+ const share = before > 0 ? Math.round((rounded[i + 1] / before) * 100) : 0;
189
+ return `${option.label}: ${share}% of ${options[i].label}`;
190
+ });
191
+ out.push({ type: 'text', value: steps.join(' · ').slice(0, 5000), muted: true });
192
+ }
193
+ if (hasMore) {
194
+ out.push({
195
+ type: 'text',
196
+ value: `Counts the first ${response.rows.length} rows only.`,
197
+ muted: true,
198
+ });
199
+ }
200
+ return out;
201
+ }
95
202
  /** Which page of a table the params ask for, 1 when none. */
96
203
  export function datasetPage(node, params) {
97
204
  if (node.layout !== 'table' && node.layout !== 'list')
@@ -144,7 +251,11 @@ export function datasetQueryFor(node, declaration, params) {
144
251
  return {
145
252
  filters,
146
253
  ...(sort ? { sort } : {}),
147
- limit: node.layout === 'board' ? Math.min(DATASET_LIMITS.rows, node.limit * 4) : node.limit,
254
+ limit: node.layout === 'chart'
255
+ ? DATASET_LIMITS.rows
256
+ : node.layout === 'board'
257
+ ? Math.min(DATASET_LIMITS.rows, node.limit * 4)
258
+ : node.limit,
148
259
  };
149
260
  }
150
261
  /** The fields a view shows, in order. */
@@ -350,6 +461,9 @@ export function compileDatasetNode(opts) {
350
461
  : {};
351
462
  };
352
463
  const note = response.note ? [{ type: 'text', value: response.note, muted: true }] : [];
464
+ if (node.layout === 'chart') {
465
+ return [...compileDatasetChart(node, declaration, response, opts.hasMore), ...note];
466
+ }
353
467
  if (node.layout === 'board') {
354
468
  const group = boardGroupField(node, declaration);
355
469
  const subtitleField = declaration.fields.find((f) => f.role === 'subtitle') ??
@@ -488,3 +602,98 @@ export function compileDatasetNode(opts) {
488
602
  ];
489
603
  return [...chipBar, table, ...pager, ...note];
490
604
  }
605
+ /**
606
+ * The screen param that opens a dataset's create form: its value is the
607
+ * dataset's name. Reserved on every screen that shows a dataset.
608
+ */
609
+ export const DATASET_NEW_PARAM = 'new';
610
+ /**
611
+ * The action a create form submits. Core answers it itself: it checks the input
612
+ * against the declaration and calls the module's `create`. A module never
613
+ * receives it, so no module screen may name an action this.
614
+ */
615
+ export const DATASET_CREATE_ACTION = 'kee-dataset-create';
616
+ /** One form field for one dataset field. */
617
+ function formField(field, required) {
618
+ const base = { name: field.name, label: field.label, required };
619
+ switch (field.type) {
620
+ case 'enum':
621
+ return {
622
+ ...base,
623
+ kind: 'select',
624
+ options: (field.options ?? []).map((option) => ({
625
+ value: option.value,
626
+ label: option.label,
627
+ })),
628
+ };
629
+ case 'number':
630
+ return { ...base, kind: 'number' };
631
+ case 'boolean':
632
+ return { ...base, kind: 'checkbox', required: false };
633
+ case 'date':
634
+ return { ...base, kind: 'date' };
635
+ case 'datetime':
636
+ return { ...base, kind: 'datetime' };
637
+ case 'tags':
638
+ return { ...base, kind: 'list' };
639
+ case 'url':
640
+ return { ...base, kind: 'text', placeholder: 'https://' };
641
+ default:
642
+ return { ...base, kind: 'text' };
643
+ }
644
+ }
645
+ /**
646
+ * The create affordance for a dataset node: a button that opens the form, or,
647
+ * once the `new` param names this dataset, the form itself with Cancel. Empty
648
+ * when the dataset takes no new rows, the node turns it off, or it is a record.
649
+ */
650
+ export function compileDatasetCreate(opts) {
651
+ const { node, declaration, screen } = opts;
652
+ const create = declaration.accepts?.create;
653
+ if (!create || !node.create || node.layout === 'record' || node.layout === 'chart')
654
+ return [];
655
+ const here = { kind: 'navigate', screen: screen.screen };
656
+ if (screen.params[DATASET_NEW_PARAM] !== node.dataset) {
657
+ return [
658
+ {
659
+ type: 'button',
660
+ label: create.label,
661
+ variant: 'primary',
662
+ onPress: {
663
+ ...here,
664
+ params: {
665
+ ...keepParams(screen.params, ['page', node.param]),
666
+ [DATASET_NEW_PARAM]: node.dataset,
667
+ },
668
+ },
669
+ },
670
+ ];
671
+ }
672
+ const byName = new Map(declaration.fields.map((field) => [field.name, field]));
673
+ const required = new Set(create.required);
674
+ const fields = create.fields.flatMap((name) => {
675
+ const field = byName.get(name);
676
+ return field ? [formField(field, required.has(name))] : [];
677
+ });
678
+ return [
679
+ {
680
+ type: 'section',
681
+ title: create.label,
682
+ layout: 'stack',
683
+ children: [
684
+ {
685
+ type: 'form',
686
+ key: `new-${node.dataset}`.slice(0, 64),
687
+ fields,
688
+ submit: { label: 'Save', action: DATASET_CREATE_ACTION },
689
+ },
690
+ {
691
+ type: 'button',
692
+ label: 'Cancel',
693
+ variant: 'secondary',
694
+ onPress: { ...here, params: keepParams(screen.params, [DATASET_NEW_PARAM]) },
695
+ },
696
+ ],
697
+ },
698
+ ];
699
+ }
package/dist/dataset.d.ts CHANGED
@@ -13,6 +13,14 @@
13
13
  *
14
14
  * ui/datasets/<name>.ts -> export default defineDataset({ ... })
15
15
  * POST {runtime}/datasets/<name>/query -> DatasetQueryResponse
16
+ * POST {runtime}/datasets/<name>/records -> DatasetCreateResponse
17
+ *
18
+ * A dataset may also take new rows from a person. It declares `accepts.create`:
19
+ * the button label and the fields the form asks for. The platform draws the
20
+ * form wherever the dataset shows, checks what the person typed against the
21
+ * declaration, and only then calls the module's `create`. Write `create` with
22
+ * the same code your agent's tools use, so a row from the form and a row from
23
+ * the chat land in one store.
16
24
  *
17
25
  * Core checks the declaration at upload, checks each request against it
18
26
  * before it calls the module, and checks each answer against it before any
@@ -46,6 +54,7 @@ export declare const DATASET_LIMITS: {
46
54
  readonly filters: 8;
47
55
  readonly text: 500;
48
56
  readonly tags: 20;
57
+ readonly formFields: 20;
49
58
  };
50
59
  export declare const datasetFieldSchema: z.ZodObject<{
51
60
  name: z.ZodString;
@@ -130,6 +139,13 @@ export declare const datasetDeclarationSchema: z.ZodObject<{
130
139
  desc: "desc";
131
140
  }>>;
132
141
  }, z.core.$strip>>;
142
+ accepts: z.ZodOptional<z.ZodObject<{
143
+ create: z.ZodOptional<z.ZodObject<{
144
+ label: z.ZodString;
145
+ fields: z.ZodArray<z.ZodString>;
146
+ required: z.ZodDefault<z.ZodArray<z.ZodString>>;
147
+ }, z.core.$strip>>;
148
+ }, z.core.$strip>>;
133
149
  name: z.ZodString;
134
150
  }, z.core.$strip>;
135
151
  /** Every dataset a module declares. Generated into entry.json `manifest.datasets`. */
@@ -180,6 +196,13 @@ export declare const datasetManifestSchema: z.ZodArray<z.ZodObject<{
180
196
  desc: "desc";
181
197
  }>>;
182
198
  }, z.core.$strip>>;
199
+ accepts: z.ZodOptional<z.ZodObject<{
200
+ create: z.ZodOptional<z.ZodObject<{
201
+ label: z.ZodString;
202
+ fields: z.ZodArray<z.ZodString>;
203
+ required: z.ZodDefault<z.ZodArray<z.ZodString>>;
204
+ }, z.core.$strip>>;
205
+ }, z.core.$strip>>;
183
206
  name: z.ZodString;
184
207
  }, z.core.$strip>>;
185
208
  /** What a view asks for. Core checks it against the declaration before the module sees it. */
@@ -197,6 +220,12 @@ export declare const datasetQueryRequestSchema: z.ZodObject<{
197
220
  cursor: z.ZodOptional<z.ZodString>;
198
221
  keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
199
222
  }, z.core.$strip>;
223
+ /**
224
+ * One value. Primitives and a list of tags only: a nested object has no place
225
+ * in a view. Null (written with `.nullable()`, not a `z.null()` union member,
226
+ * which OpenAPI 3.0 cannot express) means the row has no value for the field.
227
+ */
228
+ declare const datasetCellSchema: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodArray<z.ZodString>]>>;
200
229
  export declare const datasetRowSchema: z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodArray<z.ZodString>]>>>;
201
230
  export declare const datasetQueryResponseSchema: z.ZodObject<{
202
231
  rows: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodArray<z.ZodString>]>>>>;
@@ -204,6 +233,15 @@ export declare const datasetQueryResponseSchema: z.ZodObject<{
204
233
  total: z.ZodOptional<z.ZodNumber>;
205
234
  note: z.ZodOptional<z.ZodString>;
206
235
  }, z.core.$strip>;
236
+ /** What core sends a module's `POST /datasets/<name>/records`: checked input only. */
237
+ export declare const datasetCreateRequestSchema: z.ZodObject<{
238
+ input: z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodArray<z.ZodString>]>>>;
239
+ idempotencyKey: z.ZodString;
240
+ }, z.core.$strip>;
241
+ export declare const datasetCreateResponseSchema: z.ZodObject<{
242
+ key: z.ZodOptional<z.ZodString>;
243
+ note: z.ZodOptional<z.ZodString>;
244
+ }, z.core.$strip>;
207
245
  export type DatasetField = z.infer<typeof datasetFieldSchema>;
208
246
  export type DatasetDeclaration = z.infer<typeof datasetDeclarationSchema>;
209
247
  export type DatasetDeclarationInput = z.input<typeof datasetDeclarationSchema>;
@@ -212,6 +250,10 @@ export type DatasetQueryRequestInput = z.input<typeof datasetQueryRequestSchema>
212
250
  export type DatasetRow = z.infer<typeof datasetRowSchema>;
213
251
  export type DatasetQueryResponse = z.infer<typeof datasetQueryResponseSchema>;
214
252
  export type DatasetQueryResponseInput = z.input<typeof datasetQueryResponseSchema>;
253
+ export type DatasetCell = z.infer<typeof datasetCellSchema>;
254
+ export type DatasetCreateRequest = z.infer<typeof datasetCreateRequestSchema>;
255
+ export type DatasetCreateResponse = z.infer<typeof datasetCreateResponseSchema>;
256
+ export type DatasetCreateResponseInput = z.input<typeof datasetCreateResponseSchema>;
215
257
  /**
216
258
  * Problems with a request, against the dataset it names. Empty means the
217
259
  * module may run it. Core runs this before it calls the module, and
@@ -224,11 +266,29 @@ export declare function datasetRequestIssues(declaration: DatasetDeclaration, re
224
266
  * field's type; a value for an undeclared field is refused.
225
267
  */
226
268
  export declare function datasetResponseIssues(declaration: DatasetDeclaration, response: DatasetQueryResponse, request?: Pick<DatasetQueryRequest, 'limit' | 'keys'>): string[];
269
+ export type DatasetCreateCheck = {
270
+ ok: true;
271
+ input: Record<string, DatasetCell>;
272
+ } | {
273
+ ok: false;
274
+ issue: string;
275
+ };
276
+ /**
277
+ * What a person typed into a dataset's create form, checked against the
278
+ * declaration: only the form's fields, each value fit for its type, every
279
+ * required field filled. A blank optional field is left out. Core runs this
280
+ * before it calls the module, and `answerDatasetCreate` runs it again.
281
+ */
282
+ export declare function datasetCreateInput(declaration: DatasetDeclaration, raw: unknown): DatasetCreateCheck;
227
283
  /** The rows of one page, as a module's `query` returns them. */
228
284
  export type DatasetQueryHandler<Ctx> = (ctx: Ctx, request: DatasetQueryRequest) => DatasetQueryResponseInput | Promise<DatasetQueryResponseInput>;
285
+ /** Write one new row from checked input. Return its key so a view can open it. */
286
+ export type DatasetCreateHandler<Ctx> = (ctx: Ctx, input: Record<string, DatasetCell>) => DatasetCreateResponseInput | Promise<DatasetCreateResponseInput>;
229
287
  /** What `ui/datasets/<name>.ts` exports. The file name is the dataset's name. */
230
288
  export type DatasetDefinition<Ctx = unknown> = Omit<DatasetDeclarationInput, 'name'> & {
231
289
  query: DatasetQueryHandler<Ctx>;
290
+ /** Required when the declaration has `accepts.create`, and only then. */
291
+ create?: DatasetCreateHandler<Ctx>;
232
292
  };
233
293
  /**
234
294
  * Declare a dataset. The declaration is checked at once, so a mistake fails
@@ -253,3 +313,19 @@ export declare function answerDatasetQuery<Ctx>(opts: {
253
313
  status: number;
254
314
  body: unknown;
255
315
  }>;
316
+ /**
317
+ * Serve one create, for a module's `POST /datasets/:name/records` route: parse
318
+ * the body, check the input against the declaration again, run `create`, and
319
+ * check the answer. Returns the status and the body to send.
320
+ */
321
+ export declare function answerDatasetCreate<Ctx>(opts: {
322
+ name: string;
323
+ definition: DatasetDefinition<Ctx>;
324
+ ctx: Ctx;
325
+ body: unknown;
326
+ log?: (message: string) => void;
327
+ }): Promise<{
328
+ status: number;
329
+ body: unknown;
330
+ }>;
331
+ export {};
package/dist/dataset.js CHANGED
@@ -13,6 +13,14 @@
13
13
  *
14
14
  * ui/datasets/<name>.ts -> export default defineDataset({ ... })
15
15
  * POST {runtime}/datasets/<name>/query -> DatasetQueryResponse
16
+ * POST {runtime}/datasets/<name>/records -> DatasetCreateResponse
17
+ *
18
+ * A dataset may also take new rows from a person. It declares `accepts.create`:
19
+ * the button label and the fields the form asks for. The platform draws the
20
+ * form wherever the dataset shows, checks what the person typed against the
21
+ * declaration, and only then calls the module's `create`. Write `create` with
22
+ * the same code your agent's tools use, so a row from the form and a row from
23
+ * the chat land in one store.
16
24
  *
17
25
  * Core checks the declaration at upload, checks each request against it
18
26
  * before it calls the module, and checks each answer against it before any
@@ -67,6 +75,7 @@ export const DATASET_LIMITS = {
67
75
  filters: 8,
68
76
  text: 500,
69
77
  tags: 20,
78
+ formFields: 20,
70
79
  };
71
80
  export const datasetFieldSchema = z
72
81
  .object({
@@ -152,6 +161,22 @@ const declarationShape = {
152
161
  search: z.boolean().default(false),
153
162
  /** The order rows come in when a request names none. Must be a sortable field. */
154
163
  defaultSort: sortSchema.optional(),
164
+ /** What a person may do to the rows from a view, besides read them. */
165
+ accepts: z
166
+ .object({
167
+ /** A person may add a row with a form. The module's `create` writes it. */
168
+ create: z
169
+ .object({
170
+ /** The button that opens the form: "Log a deal". */
171
+ label: z.string().min(1).max(40),
172
+ /** The fields the form asks for, in order. */
173
+ fields: z.array(fieldName).min(1).max(DATASET_LIMITS.formFields),
174
+ /** The fields a person must fill. Each must be one of `fields`. */
175
+ required: z.array(fieldName).max(DATASET_LIMITS.formFields).default([]),
176
+ })
177
+ .optional(),
178
+ })
179
+ .optional(),
155
180
  };
156
181
  function checkDeclaration(declaration, ctx) {
157
182
  const byName = new Map();
@@ -197,6 +222,29 @@ function checkDeclaration(declaration, ctx) {
197
222
  message: 'one text field needs role "title": every view leads a row with it',
198
223
  });
199
224
  }
225
+ const create = declaration.accepts?.create;
226
+ if (create) {
227
+ const asked = new Set();
228
+ for (const [index, name] of create.fields.entries()) {
229
+ const at = ['accepts', 'create', 'fields', index];
230
+ if (!byName.has(name)) {
231
+ ctx.addIssue({ code: 'custom', path: at, message: `"${name}" is not a field` });
232
+ }
233
+ if (asked.has(name)) {
234
+ ctx.addIssue({ code: 'custom', path: at, message: `"${name}" is asked twice` });
235
+ }
236
+ asked.add(name);
237
+ }
238
+ for (const [index, name] of create.required.entries()) {
239
+ if (!asked.has(name)) {
240
+ ctx.addIssue({
241
+ code: 'custom',
242
+ path: ['accepts', 'create', 'required', index],
243
+ message: `"${name}" is required but the form does not ask for it`,
244
+ });
245
+ }
246
+ }
247
+ }
200
248
  if (declaration.defaultSort) {
201
249
  const field = byName.get(declaration.defaultSort.field);
202
250
  if (!field?.sortable) {
@@ -268,6 +316,19 @@ export const datasetQueryResponseSchema = z.object({
268
316
  /** Shown as is, for an answer that is partial ("last 90 days only"). */
269
317
  note: z.string().max(300).optional(),
270
318
  });
319
+ /** What core sends a module's `POST /datasets/<name>/records`: checked input only. */
320
+ export const datasetCreateRequestSchema = z.object({
321
+ /** The person's values, keyed by field. Only the form's fields, each checked and normalized. */
322
+ input: z.record(fieldName, datasetCellSchema),
323
+ /** The same for a retry of the same submit. A module may use it to drop a duplicate. */
324
+ idempotencyKey: z.string().min(1).max(200),
325
+ });
326
+ export const datasetCreateResponseSchema = z.object({
327
+ /** The new row's key, so a view can open it. */
328
+ key: z.string().min(1).max(128).optional(),
329
+ /** Shown to the person as is: "Logged. Ben owns it." */
330
+ note: z.string().max(300).optional(),
331
+ });
271
332
  /**
272
333
  * Problems with a request, against the dataset it names. Empty means the
273
334
  * module may run it. Core runs this before it calls the module, and
@@ -371,6 +432,106 @@ export function datasetResponseIssues(declaration, response, request) {
371
432
  }
372
433
  return issues;
373
434
  }
435
+ const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
436
+ /** One value a person typed, against its field. The normalized value, or what is wrong with it. */
437
+ function createValue(field, raw) {
438
+ switch (field.type) {
439
+ case 'number': {
440
+ const value = typeof raw === 'string' ? Number(raw.trim()) : raw;
441
+ return typeof value === 'number' && Number.isFinite(value)
442
+ ? { value }
443
+ : { issue: 'must be a number' };
444
+ }
445
+ case 'boolean':
446
+ if (typeof raw === 'boolean')
447
+ return { value: raw };
448
+ if (raw === 'true' || raw === 'false')
449
+ return { value: raw === 'true' };
450
+ return { issue: 'must be yes or no' };
451
+ case 'tags': {
452
+ const list = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(',') : null;
453
+ if (!list || list.some((item) => typeof item !== 'string'))
454
+ return { issue: 'must be a list' };
455
+ const tags = [...new Set(list.map((item) => item.trim()).filter(Boolean))];
456
+ if (tags.length > DATASET_LIMITS.tags)
457
+ return { issue: `takes at most ${DATASET_LIMITS.tags}` };
458
+ if (tags.some((tag) => tag.length > 40))
459
+ return { issue: 'each item takes at most 40 characters' };
460
+ return { value: tags };
461
+ }
462
+ default:
463
+ break;
464
+ }
465
+ if (typeof raw !== 'string')
466
+ return { issue: 'must be text' };
467
+ const text = raw.trim();
468
+ if (text.length > DATASET_LIMITS.text) {
469
+ return { issue: `takes at most ${DATASET_LIMITS.text} characters` };
470
+ }
471
+ if (field.type === 'enum') {
472
+ const option = field.options?.find((item) => item.value === text || item.value.toLowerCase() === text.toLowerCase());
473
+ return option
474
+ ? { value: option.value }
475
+ : { issue: `must be one of ${field.options?.map((item) => item.label).join(', ')}` };
476
+ }
477
+ if (field.type === 'url') {
478
+ try {
479
+ const url = new URL(text);
480
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
481
+ throw new Error('scheme');
482
+ }
483
+ catch {
484
+ return { issue: 'must be a web address (https://…)' };
485
+ }
486
+ }
487
+ if (field.type === 'date' && (!DATE_ONLY.test(text) || Number.isNaN(Date.parse(text)))) {
488
+ return { issue: 'must be a date (YYYY-MM-DD)' };
489
+ }
490
+ if (field.type === 'datetime' && Number.isNaN(Date.parse(text))) {
491
+ return { issue: 'must be a date and time' };
492
+ }
493
+ return { value: text };
494
+ }
495
+ function blank(raw) {
496
+ return (raw === undefined ||
497
+ raw === null ||
498
+ (typeof raw === 'string' && raw.trim() === '') ||
499
+ (Array.isArray(raw) && raw.length === 0));
500
+ }
501
+ /**
502
+ * What a person typed into a dataset's create form, checked against the
503
+ * declaration: only the form's fields, each value fit for its type, every
504
+ * required field filled. A blank optional field is left out. Core runs this
505
+ * before it calls the module, and `answerDatasetCreate` runs it again.
506
+ */
507
+ export function datasetCreateInput(declaration, raw) {
508
+ const create = declaration.accepts?.create;
509
+ if (!create)
510
+ return { ok: false, issue: `${declaration.label} does not take new rows` };
511
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
512
+ return { ok: false, issue: 'the input must be an object' };
513
+ }
514
+ const byName = new Map(declaration.fields.map((field) => [field.name, field]));
515
+ const asked = new Set(create.fields);
516
+ const input = {};
517
+ for (const [name, value] of Object.entries(raw)) {
518
+ const field = byName.get(name);
519
+ if (!field || !asked.has(name))
520
+ return { ok: false, issue: `the form has no field "${name}"` };
521
+ if (blank(value))
522
+ continue;
523
+ const checked = createValue(field, value);
524
+ if ('issue' in checked)
525
+ return { ok: false, issue: `${field.label} ${checked.issue}` };
526
+ input[name] = checked.value;
527
+ }
528
+ for (const name of create.required) {
529
+ if (input[name] === undefined) {
530
+ return { ok: false, issue: `${byName.get(name)?.label ?? name} is required` };
531
+ }
532
+ }
533
+ return { ok: true, input };
534
+ }
374
535
  /**
375
536
  * Declare a dataset. The declaration is checked at once, so a mistake fails
376
537
  * where it is written, not at upload. Keep the declaration literal (strings,
@@ -378,9 +539,15 @@ export function datasetResponseIssues(declaration, response, request) {
378
539
  * file, the way it reads `defineSurface`.
379
540
  */
380
541
  export function defineDataset(definition) {
381
- const { query, ...declaration } = definition;
542
+ const { query, create, ...declaration } = definition;
382
543
  if (typeof query !== 'function')
383
544
  throw new Error('defineDataset: query must be a function');
545
+ if (declaration.accepts?.create && typeof create !== 'function') {
546
+ throw new Error('defineDataset: accepts.create needs a create function');
547
+ }
548
+ if (create !== undefined && !declaration.accepts?.create) {
549
+ throw new Error('defineDataset: a create function needs accepts.create');
550
+ }
384
551
  const parsed = datasetDeclarationSchema.safeParse({ name: 'dataset', ...declaration });
385
552
  if (!parsed.success) {
386
553
  const issue = parsed.error.issues[0];
@@ -396,7 +563,7 @@ export function defineDataset(definition) {
396
563
  */
397
564
  export async function answerDatasetQuery(opts) {
398
565
  const log = opts.log ?? ((message) => console.error(message));
399
- const { query, ...rest } = opts.definition;
566
+ const { query, create: _create, ...rest } = opts.definition;
400
567
  const declaration = datasetDeclarationSchema.parse({ name: opts.name, ...rest });
401
568
  const request = datasetQueryRequestSchema.safeParse(opts.body ?? {});
402
569
  if (!request.success) {
@@ -423,3 +590,36 @@ export async function answerDatasetQuery(opts) {
423
590
  }
424
591
  return { status: 200, body: parsed.data };
425
592
  }
593
+ /**
594
+ * Serve one create, for a module's `POST /datasets/:name/records` route: parse
595
+ * the body, check the input against the declaration again, run `create`, and
596
+ * check the answer. Returns the status and the body to send.
597
+ */
598
+ export async function answerDatasetCreate(opts) {
599
+ const log = opts.log ?? ((message) => console.error(message));
600
+ const { query: _query, create, ...rest } = opts.definition;
601
+ const declaration = datasetDeclarationSchema.parse({ name: opts.name, ...rest });
602
+ if (!create || !declaration.accepts?.create) {
603
+ return { status: 404, body: { error: `dataset "${opts.name}" does not take new rows` } };
604
+ }
605
+ const request = datasetCreateRequestSchema.safeParse(opts.body ?? {});
606
+ if (!request.success)
607
+ return { status: 400, body: { error: 'invalid dataset create' } };
608
+ const checked = datasetCreateInput(declaration, request.data.input);
609
+ if (!checked.ok)
610
+ return { status: 400, body: { error: checked.issue } };
611
+ let answer;
612
+ try {
613
+ answer = await create(opts.ctx, checked.input);
614
+ }
615
+ catch (error) {
616
+ log(`[datasets] ${opts.name}.create threw: ${error instanceof Error ? error.message : error}`);
617
+ return { status: 500, body: { error: 'create failed' } };
618
+ }
619
+ const parsed = datasetCreateResponseSchema.safeParse(answer ?? {});
620
+ if (!parsed.success) {
621
+ log(`[datasets] ${opts.name}.create gave an invalid answer`);
622
+ return { status: 500, body: { error: 'the dataset produced an invalid answer' } };
623
+ }
624
+ return { status: 200, body: parsed.data };
625
+ }
package/dist/index.d.ts CHANGED
@@ -10,9 +10,9 @@ 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';
15
- export { DATASET_LAYOUTS, DATASET_MAX_PAGE, DATASET_RECORD_SECTION, compileDatasetNode, compileDatasetRecord, compileDatasetRecordPanel, datasetCell, datasetNodeIssues, datasetNodeSchema, datasetPage, datasetQueryFor, datasetRecordKey, datasetRecordQuery, } from './dataset-view.js';
13
+ export { DATASET_FIELD_ROLES, DATASET_FIELD_TYPES, DATASET_LIMITS, answerDatasetCreate, answerDatasetQuery, datasetCreateInput, datasetCreateRequestSchema, datasetCreateResponseSchema, datasetDeclarationSchema, datasetFieldSchema, datasetManifestSchema, datasetQueryRequestSchema, datasetQueryResponseSchema, datasetRequestIssues, datasetResponseIssues, datasetRowSchema, defineDataset, } from './dataset.js';
14
+ export type { DatasetCell, DatasetCreateCheck, DatasetCreateHandler, DatasetCreateRequest, DatasetCreateResponse, DatasetCreateResponseInput, DatasetDeclaration, DatasetDeclarationInput, DatasetDefinition, DatasetField, DatasetFieldRole, DatasetFieldType, DatasetQueryHandler, DatasetQueryRequest, DatasetQueryRequestInput, DatasetQueryResponse, DatasetQueryResponseInput, DatasetRow, } from './dataset.js';
15
+ export { DATASET_CREATE_ACTION, DATASET_LAYOUTS, DATASET_MAX_PAGE, DATASET_NEW_PARAM, DATASET_RECORD_SECTION, compileDatasetCreate, compileDatasetNode, compileDatasetRecord, compileDatasetRecordPanel, datasetCell, datasetNodeIssues, datasetNodeSchema, datasetPage, datasetQueryFor, datasetRecordKey, datasetRecordQuery, } from './dataset-view.js';
16
16
  export type { DatasetLayout, DatasetNode, DatasetNodeInput, DatasetScreenContext, } from './dataset-view.js';
17
17
  export { defineScreen, defineSurface } from './define.js';
18
18
  export type { ScreenDefinition, ScreenParams, LoadHandler, ActionHandler, JobHandler, } from './define.js';
package/dist/index.js CHANGED
@@ -13,8 +13,8 @@ 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';
17
- export { DATASET_LAYOUTS, DATASET_MAX_PAGE, DATASET_RECORD_SECTION, compileDatasetNode, compileDatasetRecord, compileDatasetRecordPanel, datasetCell, datasetNodeIssues, datasetNodeSchema, datasetPage, datasetQueryFor, datasetRecordKey, datasetRecordQuery, } from './dataset-view.js';
16
+ export { DATASET_FIELD_ROLES, DATASET_FIELD_TYPES, DATASET_LIMITS, answerDatasetCreate, answerDatasetQuery, datasetCreateInput, datasetCreateRequestSchema, datasetCreateResponseSchema, datasetDeclarationSchema, datasetFieldSchema, datasetManifestSchema, datasetQueryRequestSchema, datasetQueryResponseSchema, datasetRequestIssues, datasetResponseIssues, datasetRowSchema, defineDataset, } from './dataset.js';
17
+ export { DATASET_CREATE_ACTION, DATASET_LAYOUTS, DATASET_MAX_PAGE, DATASET_NEW_PARAM, DATASET_RECORD_SECTION, compileDatasetCreate, compileDatasetNode, compileDatasetRecord, compileDatasetRecordPanel, datasetCell, datasetNodeIssues, datasetNodeSchema, datasetPage, datasetQueryFor, datasetRecordKey, datasetRecordQuery, } from './dataset-view.js';
18
18
  export { defineScreen, defineSurface } from './define.js';
19
19
  export { loadWebsiteChat, websiteChatSnippet } from './website-chat.js';
20
20
  export { createWidgetClient } from './widget.js';
package/dist/schema.d.ts CHANGED
@@ -118,8 +118,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
118
118
  date: "date";
119
119
  list: "list";
120
120
  select: "select";
121
- textarea: "textarea";
122
121
  checkbox: "checkbox";
122
+ textarea: "textarea";
123
123
  multiselect: "multiselect";
124
124
  combobox: "combobox";
125
125
  }>;
@@ -348,8 +348,8 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
348
348
  }>;
349
349
  title: z.ZodOptional<z.ZodString>;
350
350
  orientation: z.ZodDefault<z.ZodEnum<{
351
- vertical: "vertical";
352
351
  horizontal: "horizontal";
352
+ vertical: "vertical";
353
353
  }>>;
354
354
  barWeight: z.ZodDefault<z.ZodEnum<{
355
355
  regular: "regular";
@@ -809,6 +809,7 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
809
809
  table: "table";
810
810
  board: "board";
811
811
  list: "list";
812
+ chart: "chart";
812
813
  }>>;
813
814
  fields: z.ZodOptional<z.ZodArray<z.ZodString>>;
814
815
  filters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
@@ -821,12 +822,20 @@ declare const leafNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
821
822
  }, z.core.$strip>>;
822
823
  limit: z.ZodDefault<z.ZodNumber>;
823
824
  groupBy: z.ZodOptional<z.ZodString>;
825
+ chart: z.ZodOptional<z.ZodObject<{
826
+ form: z.ZodDefault<z.ZodEnum<{
827
+ bars: "bars";
828
+ funnel: "funnel";
829
+ }>>;
830
+ measure: z.ZodOptional<z.ZodString>;
831
+ }, z.core.$strip>>;
824
832
  open: z.ZodOptional<z.ZodObject<{
825
833
  screen: z.ZodString;
826
834
  param: z.ZodDefault<z.ZodString>;
827
835
  }, z.core.$strip>>;
828
836
  param: z.ZodDefault<z.ZodString>;
829
837
  empty: z.ZodDefault<z.ZodString>;
838
+ create: z.ZodDefault<z.ZodBoolean>;
830
839
  }, z.core.$strip>], "type">;
831
840
  type LeafScreenNode = z.infer<typeof leafNodeSchema>;
832
841
  type LeafScreenNodeInput = z.input<typeof leafNodeSchema>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keemakr/ui-sdk",
3
- "version": "1.4.0-dev-20261013220814",
3
+ "version": "1.4.0-dev-20261013225946",
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",