@dokebi/module 0.4.2 → 0.4.4

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/action.d.ts DELETED
@@ -1,152 +0,0 @@
1
- import { type DataFieldType } from './data-source.js';
2
- /** A label: one text, or a text per locale. */
3
- type Text = string | Readonly<Record<string, string>>;
4
- /** Formats a text field may require. */
5
- export declare const TEXT_FORMATS: readonly ['email'];
6
- export type ActionTextFormat = (typeof TEXT_FORMATS)[number];
7
- /** One input field of an action (the kinds of FIELD_TYPES, DEC-06). */
8
- export interface ActionField {
9
- readonly type: DataFieldType;
10
- readonly label: Text;
11
- /** Must be given and not empty (null, '' and [] count as missing). */
12
- readonly required?: boolean;
13
- /**
14
- * `false`: may be left out (not changed), but never cleared — null, '' and [] are refused like a
15
- * missing required value (a name that must stay). Default true for a field that is not required.
16
- */
17
- readonly nullable?: boolean;
18
- /** text: characters (code points), default 0 to ACTION_LIMITS.textChars. */
19
- readonly minLength?: number;
20
- readonly maxLength?: number;
21
- /** text: `email`. */
22
- readonly format?: ActionTextFormat;
23
- /** number and money: the smallest and largest value. */
24
- readonly min?: number;
25
- readonly max?: number;
26
- /** number: whole numbers only. */
27
- readonly integer?: boolean;
28
- /** money: digits after the point (0 to 4, default 2). */
29
- readonly scale?: number;
30
- /** status, choice and category: the values it may take, with their labels (status and choice need them). */
31
- readonly choices?: Readonly<Record<string, {
32
- readonly label: Text;
33
- }>>;
34
- /** choice: a list of values (1 to ACTION_LIMITS.choiceValues, distinct). */
35
- readonly multiple?: boolean;
36
- /** richtext: bytes of the document's JSON (default ACTION_LIMITS.richtextBytes). */
37
- readonly maxBytes?: number;
38
- }
39
- /** Who runs an action: a person, or an AI client acting for a person through an OAuth grant. */
40
- export interface ActionActor {
41
- readonly type: 'user' | 'ai';
42
- /** The user id (for an AI client, the user it acts for); absent when nobody is signed in. */
43
- readonly id?: string;
44
- /** The AI client's name (`type: 'ai'`). */
45
- readonly client?: string;
46
- }
47
- /** What `run` and `preview` receive: the checked input and who asks. */
48
- export interface ActionRun {
49
- /** `<module>.<name>`. */
50
- readonly action: string;
51
- /**
52
- * The checked input: only the fields the caller gave (an absent field is not changed), each of
53
- * its kind; null clears a field that is not required.
54
- */
55
- readonly input: Readonly<Record<string, unknown>>;
56
- /** The caller's scope (from the action's `scope`), or null when it declares no scopes. */
57
- readonly scope: string | null;
58
- /** Who asks: for the audit row (`@dokebi/audit` `record` in the service's transaction). */
59
- readonly actor: ActionActor;
60
- readonly request: unknown;
61
- /** The module context (`ModuleContext`). */
62
- readonly module: unknown;
63
- }
64
- /** The declaration of one action in `defineModule({ actions })`. */
65
- export interface ModuleAction {
66
- readonly title: Text;
67
- readonly description?: Text;
68
- /** The input fields (0 to ACTION_LIMITS.fields). `confirm` is not a field name. */
69
- readonly input?: Readonly<Record<string, ActionField>>;
70
- /** The input field that names the row the action changes (an `id` field): a form reads the row by it. */
71
- readonly key?: string;
72
- /**
73
- * The input field that carries the version of the row the caller saw (required, number or
74
- * text). The run compares it with the stored one and throws `actionConflict()` when they differ.
75
- */
76
- readonly version?: string;
77
- /** The permission key the caller must hold (`request.auth.can`): every action has one. */
78
- readonly permission: string;
79
- /** The scope names the run knows (`all`, `subtree`, `direct`, `own`). */
80
- readonly scopes?: readonly string[];
81
- /** The caller's scope, one of `scopes`, or null (403). Needed when `scopes` is declared. */
82
- readonly scope?: (input: {
83
- readonly request: unknown;
84
- readonly module: unknown;
85
- }) => unknown;
86
- /** A dangerous action runs in two steps: `preview` first, then the same input with `confirm`. */
87
- readonly danger?: true;
88
- /** What would change (JSON, at most ACTION_LIMITS.previewBytes): needed when `danger` is set. */
89
- readonly preview?: (run: ActionRun) => unknown;
90
- /** Runs the action through the module's services and returns its result (JSON: ids, counts). */
91
- readonly run: (run: ActionRun) => unknown;
92
- }
93
- /** Limits of one action (D-0202). */
94
- export declare const ACTION_LIMITS: Readonly<{
95
- fields: 64;
96
- scopes: 8;
97
- choices: 64;
98
- choiceValues: 32;
99
- textChars: 1000;
100
- textMaxChars: 100000;
101
- richtextBytes: 65536;
102
- richtextMaxBytes: 1048576;
103
- idChars: 128;
104
- previewBytes: 16384;
105
- resultBytes: 65536;
106
- }>;
107
- /** Thrown for a declaration that breaks a rule (contract.ts makes it INVALID_CONTRACT). */
108
- export declare class ActionIssue extends Error {
109
- }
110
- /**
111
- * Checks one action declaration (the caller checks `title` and `description` and gives the label
112
- * and permission checks of the contract).
113
- */
114
- export declare function readAction(input: Record<string, unknown>, where: string, label: (value: unknown, at: string) => Text, permissionOf: (key: string, at: string) => void): Omit<ModuleAction, 'title' | 'description'>;
115
- /** One refused field of an input (422): a fixed English message and the rule it broke. */
116
- export interface ActionFieldProblem {
117
- readonly field: string;
118
- readonly message: string;
119
- /** `required`, `type`, `minLength`, `maxLength`, `format`, `min`, `max`, `integer`, `scale`, `choice`, `size`. */
120
- readonly rule: string;
121
- }
122
- /** The input check: a refusal before the fields (400) or the field problems (422). */
123
- export type InputCheck = {
124
- readonly ok: true;
125
- readonly input: Readonly<Record<string, unknown>>;
126
- } | {
127
- readonly ok: false;
128
- readonly reason: 'body' | 'field';
129
- readonly name?: string;
130
- readonly message: string;
131
- } | {
132
- readonly ok: false;
133
- readonly reason: 'fields';
134
- readonly problems: readonly ActionFieldProblem[];
135
- };
136
- /**
137
- * Checks an input object against the action's fields: an unknown field is refused as a whole
138
- * (400), each wrong value is a field problem (422). Required fields are checked even when absent.
139
- */
140
- export declare function checkInput(fields: Readonly<Record<string, ActionField>>, input: unknown): InputCheck;
141
- /**
142
- * The confirm token of a dangerous action: a hash of the action, the actor, the checked input and
143
- * the preview. The confirm call runs the preview again: the same token means the caller confirms
144
- * what it was shown; a changed row gives another preview and another token (CONFIRM_STALE).
145
- */
146
- export declare function confirmToken(action: string, actor: ActionActor, input: Readonly<Record<string, unknown>>, preview: unknown): string;
147
- /**
148
- * The JSON Schema of an action's input (draft 2020-12, the keywords @dokebi/mcp accepts): what
149
- * describe shows and what an MCP tool publishes. `confirm` is added for a dangerous action.
150
- */
151
- export declare function inputSchema(action: Pick<ModuleAction, 'input' | 'danger'>): Record<string, unknown>;
152
- export {};
package/dist/action.js DELETED
@@ -1,498 +0,0 @@
1
- // Actions (D-0202, F-08): the write side of data sources. A module declares an action — its input
2
- // fields (the shared field kinds of D-0199), the permission key, the scopes, whether it is
3
- // dangerous (a preview, then a confirm) — and the function that runs it through the module's
4
- // services. One general write runs every action for every caller (a form, another program, an AI
5
- // through MCP): only declared input, field errors as 422, a version conflict as 409.
6
- import { createHash } from 'node:crypto';
7
- import { types } from 'node:util';
8
- import { FIELD_TYPES } from './data-source.js';
9
- /** Formats a text field may require. */
10
- export const TEXT_FORMATS = ['email'];
11
- /** Limits of one action (D-0202). */
12
- export const ACTION_LIMITS = Object.freeze({
13
- fields: 64,
14
- scopes: 8,
15
- choices: 64,
16
- choiceValues: 32,
17
- textChars: 1000,
18
- textMaxChars: 100_000,
19
- richtextBytes: 65_536,
20
- richtextMaxBytes: 1_048_576,
21
- idChars: 128,
22
- previewBytes: 16_384,
23
- resultBytes: 65_536,
24
- });
25
- const NAME = /^[a-z][a-z0-9_]{0,63}$/;
26
- const CHOICE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
27
- const PERMISSION = /^[a-z0-9][a-z0-9_-]*(?:\.[a-z0-9][a-z0-9_-]*)+$/;
28
- /** Kinds whose values are ids of something (a row, a person, an uploaded file). */
29
- const ID_KINDS = new Set(['id', 'person', 'image', 'file']);
30
- const CHOSEN = new Set(['status', 'choice', 'category']);
31
- /** Field names the general write keeps for itself. */
32
- const RESERVED = new Set(['confirm']);
33
- /** Thrown for a declaration that breaks a rule (contract.ts makes it INVALID_CONTRACT). */
34
- export class ActionIssue extends Error {
35
- }
36
- const plain = (value) => value !== null &&
37
- typeof value === 'object' &&
38
- !Array.isArray(value) &&
39
- !types.isProxy(value) &&
40
- [Object.prototype, null].includes(Object.getPrototypeOf(value));
41
- function only(input, keys, where) {
42
- const extra = Object.keys(input).find((name) => !keys.includes(name));
43
- if (extra)
44
- throw new ActionIssue(`${where} has an unknown field: ${extra}`);
45
- }
46
- const whole = (value, low, high) => Number.isInteger(value) && value >= low && value <= high;
47
- /** The fields each kind accepts besides type, label and required. */
48
- const OPTIONS = {
49
- id: [],
50
- person: [],
51
- image: [],
52
- file: [],
53
- text: ['minLength', 'maxLength', 'format'],
54
- richtext: ['maxBytes'],
55
- number: ['min', 'max', 'integer'],
56
- money: ['min', 'max', 'scale'],
57
- date: [],
58
- datetime: [],
59
- boolean: [],
60
- status: ['choices'],
61
- choice: ['choices', 'multiple'],
62
- category: ['choices'],
63
- };
64
- /**
65
- * Checks one action declaration (the caller checks `title` and `description` and gives the label
66
- * and permission checks of the contract).
67
- */
68
- export function readAction(input, where, label, permissionOf) {
69
- only(input, [
70
- 'title',
71
- 'description',
72
- 'input',
73
- 'key',
74
- 'version',
75
- 'permission',
76
- 'scopes',
77
- 'scope',
78
- 'danger',
79
- 'preview',
80
- 'run',
81
- ], where);
82
- if (typeof input.run !== 'function')
83
- throw new ActionIssue(`${where}.run must be a function`);
84
- const fields = {};
85
- if (input.input !== undefined) {
86
- if (!plain(input.input))
87
- throw new ActionIssue(`${where}.input must be an object`);
88
- const list = Object.entries(input.input);
89
- if (list.length > ACTION_LIMITS.fields)
90
- throw new ActionIssue(`${where}.input has more than ${ACTION_LIMITS.fields} fields`);
91
- for (const [name, item] of list) {
92
- const at = `${where}.input.${name}`;
93
- if (!NAME.test(name))
94
- throw new ActionIssue(`${where}.input has an invalid name: ${name}`);
95
- if (RESERVED.has(name))
96
- throw new ActionIssue(`${at}: ${name} is kept by the general write (the confirm token)`);
97
- if (!plain(item))
98
- throw new ActionIssue(`${at} must be an object`);
99
- fields[name] = readField(item, at, label);
100
- }
101
- }
102
- for (const key of ['key', 'version']) {
103
- const name = input[key];
104
- if (name === undefined)
105
- continue;
106
- if (typeof name !== 'string' || !Object.hasOwn(fields, name))
107
- throw new ActionIssue(`${where}.${key} must name an input field`);
108
- }
109
- if (input.key !== undefined && fields[input.key]?.type !== 'id')
110
- throw new ActionIssue(`${where}.key must name an input field of type id`);
111
- if (input.version !== undefined) {
112
- const field = fields[input.version];
113
- if (!field?.required || (field.type !== 'number' && field.type !== 'text'))
114
- throw new ActionIssue(`${where}.version must name a required number or text input field`);
115
- }
116
- if (typeof input.permission !== 'string' || !PERMISSION.test(input.permission))
117
- throw new ActionIssue(`${where}.permission must be a permission key: every action needs one (writes are never public)`);
118
- permissionOf(input.permission, `${where}.permission`);
119
- let scopes;
120
- if (input.scopes !== undefined) {
121
- const value = input.scopes;
122
- if (!Array.isArray(value) ||
123
- types.isProxy(value) ||
124
- value.length === 0 ||
125
- value.length > ACTION_LIMITS.scopes ||
126
- value.some((item) => typeof item !== 'string' || !NAME.test(item)) ||
127
- new Set(value).size !== value.length)
128
- throw new ActionIssue(`${where}.scopes must be 1 to ${ACTION_LIMITS.scopes} distinct names`);
129
- scopes = Object.freeze([...value]);
130
- }
131
- if ((scopes === undefined) !== (input.scope === undefined))
132
- throw new ActionIssue(`${where}: scopes and scope go together (the names and the function)`);
133
- if (input.scope !== undefined && typeof input.scope !== 'function')
134
- throw new ActionIssue(`${where}.scope must be a function`);
135
- if (input.danger !== undefined && input.danger !== true)
136
- throw new ActionIssue(`${where}.danger is true or left out`);
137
- if ((input.danger === true) !== (input.preview !== undefined))
138
- throw new ActionIssue(`${where}: danger and preview go together (a dangerous action shows what it would change first)`);
139
- if (input.preview !== undefined && typeof input.preview !== 'function')
140
- throw new ActionIssue(`${where}.preview must be a function`);
141
- return {
142
- input: Object.freeze(fields),
143
- ...(input.key === undefined ? {} : { key: input.key }),
144
- ...(input.version === undefined ? {} : { version: input.version }),
145
- permission: input.permission,
146
- ...(scopes === undefined ? {} : { scopes }),
147
- ...(input.scope === undefined
148
- ? {}
149
- : { scope: input.scope }),
150
- ...(input.danger === true ? { danger: true } : {}),
151
- ...(input.preview === undefined
152
- ? {}
153
- : { preview: input.preview }),
154
- run: input.run,
155
- };
156
- }
157
- function readField(item, at, label) {
158
- if (!FIELD_TYPES.includes(item.type))
159
- throw new ActionIssue(`${at}.type must be one of ${FIELD_TYPES.join(', ')}`);
160
- const type = item.type;
161
- only(item, ['type', 'label', 'required', 'nullable', ...OPTIONS[type]], at);
162
- for (const flag of ['required', 'nullable'])
163
- if (item[flag] !== undefined && typeof item[flag] !== 'boolean')
164
- throw new ActionIssue(`${at}.${flag} must be true or false`);
165
- if (item.required && item.nullable !== undefined)
166
- throw new ActionIssue(`${at}.nullable is for a field that is not required`);
167
- const field = { type, label: label(item.label, `${at}.label`) };
168
- if (item.required)
169
- field.required = true;
170
- if (item.nullable === false)
171
- field.nullable = false;
172
- if (type === 'text') {
173
- const min = item.minLength ?? 0;
174
- const max = item.maxLength ?? ACTION_LIMITS.textChars;
175
- if (!whole(min, 0, ACTION_LIMITS.textMaxChars) || !whole(max, 1, ACTION_LIMITS.textMaxChars))
176
- throw new ActionIssue(`${at}: minLength and maxLength are whole numbers up to ${ACTION_LIMITS.textMaxChars}`);
177
- if (min > max)
178
- throw new ActionIssue(`${at}.minLength is larger than maxLength`);
179
- if (item.minLength !== undefined)
180
- field.minLength = min;
181
- field.maxLength = max;
182
- if (item.format !== undefined) {
183
- if (!TEXT_FORMATS.includes(item.format))
184
- throw new ActionIssue(`${at}.format must be one of ${TEXT_FORMATS.join(', ')}`);
185
- field.format = item.format;
186
- }
187
- }
188
- if (type === 'richtext') {
189
- const max = item.maxBytes ?? ACTION_LIMITS.richtextBytes;
190
- if (!whole(max, 2, ACTION_LIMITS.richtextMaxBytes))
191
- throw new ActionIssue(`${at}.maxBytes must be 2 to ${ACTION_LIMITS.richtextMaxBytes}`);
192
- field.maxBytes = max;
193
- }
194
- if (type === 'number' || type === 'money') {
195
- for (const bound of ['min', 'max'])
196
- if (item[bound] !== undefined &&
197
- (typeof item[bound] !== 'number' || !Number.isFinite(item[bound])))
198
- throw new ActionIssue(`${at}.${bound} must be a number`);
199
- if (item.min !== undefined &&
200
- item.max !== undefined &&
201
- item.min > item.max)
202
- throw new ActionIssue(`${at}.min is larger than max`);
203
- if (item.min !== undefined)
204
- field.min = item.min;
205
- if (item.max !== undefined)
206
- field.max = item.max;
207
- }
208
- if (type === 'number' && item.integer !== undefined) {
209
- if (typeof item.integer !== 'boolean')
210
- throw new ActionIssue(`${at}.integer must be true or false`);
211
- if (item.integer)
212
- field.integer = true;
213
- }
214
- if (type === 'money') {
215
- const scale = item.scale ?? 2;
216
- if (!whole(scale, 0, 4))
217
- throw new ActionIssue(`${at}.scale must be 0 to 4`);
218
- field.scale = scale;
219
- }
220
- if (CHOSEN.has(type)) {
221
- if (item.choices === undefined) {
222
- if (type !== 'category')
223
- throw new ActionIssue(`${at}.choices is required for a ${type} field`);
224
- }
225
- else {
226
- if (!plain(item.choices))
227
- throw new ActionIssue(`${at}.choices must be an object`);
228
- const list = Object.entries(item.choices);
229
- if (list.length === 0 || list.length > ACTION_LIMITS.choices)
230
- throw new ActionIssue(`${at}.choices must have 1 to ${ACTION_LIMITS.choices} entries`);
231
- const choices = {};
232
- for (const [value, choice] of list) {
233
- if (!CHOICE.test(value))
234
- throw new ActionIssue(`${at}.choices has an invalid value: ${value}`);
235
- if (!plain(choice))
236
- throw new ActionIssue(`${at}.choices.${value} must be { label }`);
237
- only(choice, ['label'], `${at}.choices.${value}`);
238
- choices[value] = Object.freeze({
239
- label: label(choice.label, `${at}.choices.${value}.label`),
240
- });
241
- }
242
- field.choices = Object.freeze(choices);
243
- }
244
- }
245
- if (type === 'choice' && item.multiple !== undefined) {
246
- if (typeof item.multiple !== 'boolean')
247
- throw new ActionIssue(`${at}.multiple must be true or false`);
248
- if (item.multiple)
249
- field.multiple = true;
250
- }
251
- return Object.freeze(field);
252
- }
253
- const EMAIL = /^[^\s@]{1,64}@[^\s@.]+(?:\.[^\s@.]+)+$/;
254
- const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
255
- const DATETIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(?:Z|[+-](\d{2}):(\d{2}))$/;
256
- const CONTROL = /\p{Cc}/u;
257
- const realDate = (year, month, day) => {
258
- const date = new Date(Date.UTC(year, month - 1, day));
259
- return (date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day);
260
- };
261
- const empty = (value) => value === null ||
262
- value === undefined ||
263
- value === '' ||
264
- (Array.isArray(value) && value.length === 0);
265
- /** Checks one given value against its field: undefined when it is fine, else the problem. */
266
- function fieldProblem(name, field, value, present) {
267
- const problem = (rule, message) => ({ field: name, rule, message });
268
- if (empty(value)) {
269
- if (field.required)
270
- return problem('required', 'is required');
271
- return present && field.nullable === false ? problem('required', 'cannot be empty') : undefined;
272
- }
273
- switch (field.type) {
274
- case 'id':
275
- case 'person':
276
- case 'image':
277
- case 'file':
278
- if ((typeof value === 'string' &&
279
- value.length <= ACTION_LIMITS.idChars &&
280
- value.trim() === value &&
281
- !CONTROL.test(value)) ||
282
- (Number.isSafeInteger(value) && value > 0))
283
- return undefined;
284
- return problem('type', 'must be an id');
285
- case 'text': {
286
- if (typeof value !== 'string')
287
- return problem('type', 'must be text');
288
- const length = [...value].length;
289
- if (field.minLength !== undefined && length < field.minLength)
290
- return problem('minLength', `must be at least ${field.minLength} characters`);
291
- if (length > (field.maxLength ?? ACTION_LIMITS.textChars))
292
- return problem('maxLength', `must be at most ${field.maxLength} characters`);
293
- if (field.format === 'email' && (value.length > 254 || !EMAIL.test(value)))
294
- return problem('format', 'must be an email address');
295
- return undefined;
296
- }
297
- case 'richtext': {
298
- if (!plain(value))
299
- return problem('type', 'must be a rich text document (a JSON object)');
300
- let bytes;
301
- try {
302
- bytes = Buffer.byteLength(JSON.stringify(value));
303
- }
304
- catch {
305
- return problem('type', 'must be a rich text document (a JSON object)');
306
- }
307
- if (bytes > (field.maxBytes ?? ACTION_LIMITS.richtextBytes))
308
- return problem('size', `must be at most ${field.maxBytes} bytes`);
309
- return undefined;
310
- }
311
- case 'number':
312
- if (typeof value !== 'number' || !Number.isFinite(value))
313
- return problem('type', 'must be a number');
314
- if (field.integer && !Number.isInteger(value))
315
- return problem('integer', 'must be a whole number');
316
- return bounds(field, value, problem);
317
- case 'money': {
318
- const scale = field.scale ?? 2;
319
- const pattern = new RegExp(`^-?\\d{1,15}(?:\\.\\d{1,${scale}})?$`);
320
- if (typeof value !== 'string' || !pattern.test(value))
321
- return problem('type', scale === 0
322
- ? 'must be an amount in whole units, such as 1200'
323
- : `must be an amount with at most ${scale} digits after the point, such as 12.50`);
324
- return bounds(field, Number(value), problem);
325
- }
326
- case 'date': {
327
- const match = typeof value === 'string' ? DATE.exec(value) : null;
328
- if (!match || !realDate(Number(match[1]), Number(match[2]), Number(match[3])))
329
- return problem('type', 'must be a date such as 2026-11-12');
330
- return undefined;
331
- }
332
- case 'datetime': {
333
- const match = typeof value === 'string' ? DATETIME.exec(value) : null;
334
- if (!match ||
335
- !realDate(Number(match[1]), Number(match[2]), Number(match[3])) ||
336
- Number(match[4]) > 23 ||
337
- Number(match[5]) > 59 ||
338
- Number(match[6] ?? 0) > 59 ||
339
- Number(match[7] ?? 0) > 23 ||
340
- Number(match[8] ?? 0) > 59)
341
- return problem('type', 'must be a date and time with its offset, such as 2026-11-12T09:30:00Z');
342
- return undefined;
343
- }
344
- case 'boolean':
345
- return typeof value === 'boolean' ? undefined : problem('type', 'must be true or false');
346
- case 'status':
347
- case 'choice':
348
- case 'category': {
349
- const one = (item) => typeof item === 'string' &&
350
- (field.choices ? Object.hasOwn(field.choices, item) : CHOICE.test(item));
351
- const offered = field.choices ? Object.keys(field.choices).join(', ') : '';
352
- const message = field.choices ? `must be one of: ${offered}` : 'must be a category value';
353
- if (field.multiple) {
354
- if (!Array.isArray(value) ||
355
- value.length > ACTION_LIMITS.choiceValues ||
356
- new Set(value).size !== value.length)
357
- return problem('type', `must be a list of 1 to ${ACTION_LIMITS.choiceValues} distinct values`);
358
- return value.every(one) ? undefined : problem('choice', message);
359
- }
360
- return one(value) ? undefined : problem('choice', message);
361
- }
362
- }
363
- }
364
- function bounds(field, value, problem) {
365
- if (field.min !== undefined && value < field.min)
366
- return problem('min', `must be at least ${field.min}`);
367
- if (field.max !== undefined && value > field.max)
368
- return problem('max', `must be at most ${field.max}`);
369
- return undefined;
370
- }
371
- /**
372
- * Checks an input object against the action's fields: an unknown field is refused as a whole
373
- * (400), each wrong value is a field problem (422). Required fields are checked even when absent.
374
- */
375
- export function checkInput(fields, input) {
376
- if (!plain(input))
377
- return { ok: false, reason: 'body', message: 'input must be an object of field values' };
378
- const unknown = Object.keys(input).find((name) => !Object.hasOwn(fields, name));
379
- if (unknown !== undefined)
380
- return {
381
- ok: false,
382
- reason: 'field',
383
- name: unknown.slice(0, 64),
384
- message: `The input field ${unknown.slice(0, 64)} is not declared by the action`,
385
- };
386
- const problems = [];
387
- const given = {};
388
- for (const [name, field] of Object.entries(fields)) {
389
- const present = Object.hasOwn(input, name);
390
- const value = present ? input[name] : undefined;
391
- const problem = fieldProblem(name, field, value, present);
392
- if (problem)
393
- problems.push(problem);
394
- else if (present)
395
- given[name] = empty(value) ? null : value;
396
- }
397
- if (problems.length)
398
- return { ok: false, reason: 'fields', problems };
399
- return { ok: true, input: Object.freeze(given) };
400
- }
401
- /** JSON text with object keys sorted, for the confirm token. */
402
- function canonical(value) {
403
- if (Array.isArray(value))
404
- return `[${value.map(canonical).join(',')}]`;
405
- if (value !== null && typeof value === 'object')
406
- return `{${Object.keys(value)
407
- .sort()
408
- .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
409
- .join(',')}}`;
410
- return JSON.stringify(value) ?? 'null';
411
- }
412
- /**
413
- * The confirm token of a dangerous action: a hash of the action, the actor, the checked input and
414
- * the preview. The confirm call runs the preview again: the same token means the caller confirms
415
- * what it was shown; a changed row gives another preview and another token (CONFIRM_STALE).
416
- */
417
- export function confirmToken(action, actor, input, preview) {
418
- return createHash('sha256')
419
- .update(canonical([1, action, actor.type, actor.id ?? null, actor.client ?? null, input, preview]))
420
- .digest('base64url')
421
- .slice(0, 32);
422
- }
423
- const label = (text) => typeof text === 'string' ? text : (text.en ?? Object.values(text)[0] ?? '');
424
- /**
425
- * The JSON Schema of an action's input (draft 2020-12, the keywords @dokebi/mcp accepts): what
426
- * describe shows and what an MCP tool publishes. `confirm` is added for a dangerous action.
427
- */
428
- export function inputSchema(action) {
429
- const properties = {};
430
- const required = [];
431
- for (const [name, field] of Object.entries(action.input ?? {})) {
432
- const description = `${label(field.label)} (${field.type})`;
433
- const nullable = (schema) => field.required || field.nullable === false
434
- ? schema
435
- : { anyOf: [schema, { type: 'null' }], description };
436
- let schema;
437
- if (ID_KINDS.has(field.type))
438
- schema = {
439
- anyOf: [
440
- { type: 'string', minLength: 1, maxLength: ACTION_LIMITS.idChars },
441
- { type: 'integer', minimum: 1 },
442
- ],
443
- };
444
- else if (field.type === 'text')
445
- schema = {
446
- type: 'string',
447
- ...(field.minLength === undefined ? {} : { minLength: field.minLength }),
448
- maxLength: field.maxLength ?? ACTION_LIMITS.textChars,
449
- ...(field.format === undefined ? {} : { format: field.format }),
450
- };
451
- else if (field.type === 'richtext')
452
- schema = { type: 'object' };
453
- else if (field.type === 'number')
454
- schema = {
455
- type: field.integer ? 'integer' : 'number',
456
- ...(field.min === undefined ? {} : { minimum: field.min }),
457
- ...(field.max === undefined ? {} : { maximum: field.max }),
458
- };
459
- else if (field.type === 'money')
460
- schema = {
461
- type: 'string',
462
- pattern: `^-?[0-9]{1,15}(\\.[0-9]{1,${field.scale ?? 2}})?$`,
463
- };
464
- else if (field.type === 'date')
465
- schema = { type: 'string', format: 'date' };
466
- else if (field.type === 'datetime')
467
- schema = { type: 'string', format: 'date-time' };
468
- else if (field.type === 'boolean')
469
- schema = { type: 'boolean' };
470
- else {
471
- const one = field.choices ? { enum: Object.keys(field.choices) } : { type: 'string' };
472
- schema = field.multiple
473
- ? {
474
- type: 'array',
475
- items: one,
476
- minItems: 1,
477
- maxItems: ACTION_LIMITS.choiceValues,
478
- uniqueItems: true,
479
- }
480
- : one;
481
- }
482
- properties[name] = { ...nullable(schema), description };
483
- if (field.required)
484
- required.push(name);
485
- }
486
- if (action.danger)
487
- properties.confirm = {
488
- type: 'string',
489
- maxLength: 64,
490
- description: 'The confirm token of the preview: leave it out first, show the preview to the user, then call again with the same input and this token',
491
- };
492
- return {
493
- type: 'object',
494
- properties,
495
- ...(required.length ? { required } : {}),
496
- additionalProperties: false,
497
- };
498
- }