@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/data-api.js DELETED
@@ -1,147 +0,0 @@
1
- // The general read of data sources (D-0199): one API for every caller of every module's data
2
- // sources. It checks the caller's permission and scope, the query against the declaration, calls
3
- // the module's reader for one page plus one row, checks what the reader returned and answers the
4
- // chosen fields with the next cursor.
5
- import { DokebiError } from '@dokebi/core';
6
- import { checkQuery, encodeCursor, rowProblem, } from './data-source.js';
7
- const STATUS = {
8
- DATA_SOURCE_NOT_FOUND: 404,
9
- FORBIDDEN: 403,
10
- INVALID_QUERY: 400,
11
- INVALID_CURSOR: 400,
12
- DATA_SOURCE_FAILED: 500,
13
- };
14
- const FIX = {
15
- DATA_SOURCE_NOT_FOUND: 'Read a data source that npx dokebi describe --json lists under app.modules[].dataSources with readable: true, as <module>.<name>.',
16
- FORBIDDEN: 'Sign in with an account that holds the data source permission (its scope must not be empty), or read another data source.',
17
- INVALID_QUERY: 'Ask only for what the data source declares (describe): fields=<declared, not hidden>, sort=<a sort offered to the caller>, filter.<name>=<value>, filter.<name>.from/.to for ranges, q=<text> where search is declared, limit=<1..max>. data.reason and data.name say what was refused.',
18
- INVALID_CURSOR: 'Pass back the next cursor of the previous page with the same sort, filters, search and scope, or leave cursor out to start from the first page.',
19
- DATA_SOURCE_FAILED: "Correct the data source's reader (or its scope function) as the message says: at most limit rows in the sort order, every sort field present and of its kind, dates as text, a scope among the declared scopes.",
20
- };
21
- const HINT = {
22
- DATA_SOURCE_NOT_FOUND: 'This data does not exist.',
23
- FORBIDDEN: 'You do not have access to this data.',
24
- INVALID_CURSOR: 'Start again from the first page.',
25
- };
26
- export function dataError(code, message, data, cause) {
27
- return new DokebiError(code, message, {
28
- plugin: 'dokebi-module',
29
- status: STATUS[code],
30
- fix: FIX[code],
31
- ...(HINT[code] === undefined ? {} : { hint: HINT[code] }),
32
- ...(data === undefined ? {} : { data }),
33
- ...(cause === undefined ? {} : { cause }),
34
- });
35
- }
36
- const PATH = /^(?:\/[a-z0-9][a-z0-9._-]{0,63}){1,4}$/;
37
- export function createDataApi(sources, logger) {
38
- const ids = Object.freeze([...sources].filter(([, source]) => source.declaration.read).map(([id]) => id));
39
- const read = async (request, id, query) => {
40
- const begin = performance.now();
41
- const source = typeof id === 'string' ? sources.get(id) : undefined;
42
- const declaration = source?.declaration;
43
- if (!source || !declaration?.read || !declaration.fields || !declaration.sorts)
44
- throw dataError('DATA_SOURCE_NOT_FOUND', source
45
- ? `The data source ${id} is declared by name only`
46
- : `There is no data source ${String(id)}`, { source: String(id) });
47
- const asked = request;
48
- // A reader declares permission or public: true (readDataSource); without permission it is public.
49
- if (declaration.permission !== undefined) {
50
- const allowed = asked.auth ? await asked.auth.can(declaration.permission) : false;
51
- if (!allowed)
52
- throw dataError('FORBIDDEN', `Reading ${id} needs ${declaration.permission}`, {
53
- source: id,
54
- });
55
- }
56
- const module = source.context();
57
- let scope = null;
58
- if (declaration.scope) {
59
- const answer = await declaration.scope({ request, module });
60
- if (answer === null || answer === undefined)
61
- throw dataError('FORBIDDEN', `The caller has no scope on ${id}`, { source: id });
62
- if (typeof answer !== 'string' || !declaration.scopes?.includes(answer))
63
- throw dataError('DATA_SOURCE_FAILED', `The scope function of ${id} answered something other than one of its scopes (${declaration.scopes?.join(', ')})`, { source: id });
64
- scope = answer;
65
- }
66
- const checked = checkQuery({
67
- fields: declaration.fields,
68
- sorts: declaration.sorts,
69
- filters: declaration.filters ?? {},
70
- limit: declaration.limit ?? { default: 20, max: 100 },
71
- ...(declaration.search === undefined ? {} : { search: declaration.search }),
72
- }, query, scope);
73
- if ('code' in checked)
74
- throw dataError(checked.code, checked.message, {
75
- source: id,
76
- reason: checked.reason,
77
- ...(checked.name === undefined ? {} : { name: checked.name }),
78
- });
79
- const limit = checked.pageSize + 1;
80
- const rows = await declaration.read({
81
- source: id,
82
- fields: checked.fields,
83
- select: checked.select,
84
- sort: checked.sort,
85
- after: checked.after,
86
- filters: checked.filters,
87
- search: checked.search,
88
- scope,
89
- limit,
90
- request,
91
- module,
92
- });
93
- const problem = rowProblem(rows, checked, declaration.fields, limit);
94
- if (problem) {
95
- const error = dataError('DATA_SOURCE_FAILED', `The reader of ${id} broke the rules: ${problem}`, {
96
- source: id,
97
- });
98
- logger.log('error', 'Data source reader broke the rules', {
99
- code: 'DATA_SOURCE_FAILED',
100
- source: id,
101
- error,
102
- });
103
- throw error;
104
- }
105
- const list = rows;
106
- const page = list.slice(0, checked.pageSize);
107
- const last = page.at(-1);
108
- const next = list.length > checked.pageSize && last
109
- ? encodeCursor(checked.sort.name, checked.fingerprint, checked.sort.by.map(({ field }) => last[field]))
110
- : null;
111
- const answer = {
112
- source: id,
113
- sort: checked.sort.name,
114
- rows: page.map((row) => Object.fromEntries(checked.fields.map((field) => [field, row[field] ?? null]))),
115
- next,
116
- };
117
- if (logger.isEnabled('debug'))
118
- logger.log('debug', 'Data source page read', {
119
- source: id,
120
- sort: checked.sort.name,
121
- scope,
122
- filters: checked.filters.map((filter) => filter.name),
123
- search: checked.search !== null,
124
- cursor: checked.after !== null,
125
- rows: page.length,
126
- more: next !== null,
127
- ms: Math.round((performance.now() - begin) * 10) / 10,
128
- });
129
- return answer;
130
- };
131
- return Object.freeze({
132
- ids,
133
- read,
134
- routes(route, options = {}) {
135
- const path = options.path ?? '/data';
136
- if (!PATH.test(path))
137
- throw dataError('DATA_SOURCE_FAILED', `The data route path ${path} must be /a/lower-case/path`);
138
- const handler = (async (request) => {
139
- const asked = request;
140
- const params = asked.params ?? {};
141
- const query = (asked.query ?? {});
142
- return read(request, `${String(params.module)}.${String(params.source)}`, query);
143
- });
144
- route.get(`${path}/:module/:source`, handler, { config: { id: 'module.data' } });
145
- },
146
- });
147
- }
@@ -1,238 +0,0 @@
1
- /** A label: one text, or a text per locale. */
2
- type Text = string | Readonly<Record<string, string>>;
3
- /**
4
- * The one list of field kinds a data source, a data grid, a form and an MCP tool share (the
5
- * product's shared kinds: text, number, money, date, datetime, status, boolean, person, image, file,
6
- * rich text, category, choice; plus id). A list returns a rich text as text (an excerpt): the whole
7
- * document is a record's.
8
- */
9
- export declare const FIELD_TYPES: readonly ['id', 'text', 'number', 'money', 'date', 'datetime', 'status', 'boolean', 'person', 'image', 'file', 'richtext', 'category', 'choice'];
10
- export type DataFieldType = (typeof FIELD_TYPES)[number];
11
- /** The colours a choice may be drawn in (the ui kit's status colours). */
12
- export declare const CHOICE_TONES: readonly ['primary', 'secondary', 'success', 'warning', 'info', 'destructive'];
13
- export type ChoiceTone = (typeof CHOICE_TONES)[number];
14
- /** One field of a data source. */
15
- export interface DataField {
16
- readonly type: DataFieldType;
17
- readonly label: Text;
18
- /** How a data grid shows it (`badge`, `avatar`, `relative` …): a hint, lower-case. */
19
- readonly display?: string;
20
- /**
21
- * The values it may take, with their labels (`status`): what a choice filter offers. `tone` is
22
- * the colour a grid draws the value in (a status dot or badge), one of CHOICE_TONES.
23
- */
24
- readonly choices?: Readonly<Record<string, {
25
- readonly label: Text;
26
- readonly tone?: ChoiceTone;
27
- }>>;
28
- /** A key the data source pages or filters by, never selected nor returned (`path`). */
29
- readonly hidden?: boolean;
30
- /** Its values are unique (an `id` field is): a sort may end with it. */
31
- readonly unique?: boolean;
32
- }
33
- /** A sort: the fields of one index, in its order; the last is unique. */
34
- export interface DataSort {
35
- readonly label: Text;
36
- /** `[field, direction]` pairs. */
37
- readonly by: readonly (readonly [string, 'asc' | 'desc'])[];
38
- /** The scopes that may use it (default every scope). */
39
- readonly scopes?: readonly string[];
40
- }
41
- export interface DataSearch {
42
- readonly label: Text;
43
- /** The fields the reader searches (declared, not hidden). */
44
- readonly fields: readonly string[];
45
- readonly minLength?: number;
46
- readonly maxLength?: number;
47
- /** The sorts a search may use (the order its index gives): default every sort. */
48
- readonly sorts?: readonly string[];
49
- readonly scopes?: readonly string[];
50
- }
51
- export type DataFilterKind = 'choice' | 'equal' | 'range';
52
- export interface DataFilter {
53
- readonly label: Text;
54
- readonly field: string;
55
- /** choice: values among the field's choices; equal: one value; range: from and/or to. */
56
- readonly kind: DataFilterKind;
57
- /**
58
- * choice: several values at once (`IN`). Off by default: an index gives one value's rows in the
59
- * sort order, but several values' rows must all be read and sorted, unless the reader bounds it.
60
- */
61
- readonly multiple?: boolean;
62
- readonly sorts?: readonly string[];
63
- readonly scopes?: readonly string[];
64
- }
65
- /** A row action: a link (`href` with `{field}` places) or a module action by name. */
66
- export interface DataAction {
67
- readonly label: Text;
68
- readonly href?: string;
69
- /**
70
- * A module action: `update` (this module's) or `<module>.<name>` (`members.update`). Only the name
71
- * is checked here; the action contract checks that it exists and what it takes.
72
- */
73
- readonly action?: string;
74
- /** The permission key the action needs (the caller hides it without). */
75
- readonly permission?: string;
76
- }
77
- /** What a reader receives: the request checked against the declaration. */
78
- export interface DataSourceRead {
79
- /** The data source id (`members.list`). */
80
- readonly source: string;
81
- /** The fields the caller chose (returned). */
82
- readonly fields: readonly string[];
83
- /** What every row must hold: the chosen fields and the sort fields (for the cursor). */
84
- readonly select: readonly string[];
85
- readonly sort: {
86
- readonly name: string;
87
- readonly by: readonly {
88
- readonly field: string;
89
- readonly direction: 'asc' | 'desc';
90
- }[];
91
- };
92
- /** The values of the sort fields of the last row of the previous page, or null (first page). */
93
- readonly after: readonly DataValue[] | null;
94
- readonly filters: readonly DataFilterValue[];
95
- readonly search: {
96
- readonly text: string;
97
- readonly fields: readonly string[];
98
- } | null;
99
- /** The caller's scope (from the data source's `scope`), or null when it declares no scopes. */
100
- readonly scope: string | null;
101
- /** Rows to read at most: the page size plus one (to know whether more exist). */
102
- readonly limit: number;
103
- readonly request: unknown;
104
- /** The module context (`ModuleContext`). */
105
- readonly module: unknown;
106
- }
107
- export type DataValue = string | number | boolean;
108
- export type DataFilterValue = {
109
- readonly name: string;
110
- readonly field: string;
111
- readonly kind: 'choice';
112
- readonly values: readonly DataValue[];
113
- } | {
114
- readonly name: string;
115
- readonly field: string;
116
- readonly kind: 'equal';
117
- readonly value: DataValue;
118
- } | {
119
- readonly name: string;
120
- readonly field: string;
121
- readonly kind: 'range';
122
- readonly from: DataValue | null;
123
- readonly to: DataValue | null;
124
- };
125
- export type DataRow = Readonly<Record<string, unknown>>;
126
- /** The declaration of one data source in `defineModule({ dataSources })`. */
127
- export interface ModuleDataSource {
128
- readonly title: Text;
129
- readonly description?: Text;
130
- readonly fields?: Readonly<Record<string, DataField>>;
131
- /** The first sort a scope may use is its default. */
132
- readonly sorts?: Readonly<Record<string, DataSort>>;
133
- readonly search?: DataSearch;
134
- readonly filters?: Readonly<Record<string, DataFilter>>;
135
- readonly actions?: Readonly<Record<string, DataAction>>;
136
- /** The permission key a caller must hold (`request.auth.can`); a reader needs it or `public`. */
137
- readonly permission?: string;
138
- /**
139
- * `true`: anyone may read, signed in or not. A data source with a reader declares `permission`
140
- * or `public: true` (one of them), so none is open by a forgotten line (D-0199 review).
141
- */
142
- readonly public?: true;
143
- /** The scope names the reader knows (`all`, `subtree`, `direct`, `own`). */
144
- readonly scopes?: readonly string[];
145
- /** The caller's scope, one of `scopes`, or null (403). Needed when `scopes` is declared. */
146
- readonly scope?: (input: {
147
- readonly request: unknown;
148
- readonly module: unknown;
149
- }) => unknown;
150
- /** Page size: `default` and `max` (at most DATA_LIMITS.pageMax). */
151
- readonly limit?: {
152
- readonly default?: number;
153
- readonly max?: number;
154
- };
155
- /** Reads one page: at most `limit` rows in the sort order, after `after`, in `scope`. */
156
- readonly read?: (input: DataSourceRead) => unknown;
157
- }
158
- /** Limits of one data source (D-0199). */
159
- export declare const DATA_LIMITS: Readonly<{
160
- fields: 64;
161
- sorts: 16;
162
- sortColumns: 4;
163
- filters: 32;
164
- actions: 16;
165
- scopes: 8;
166
- choices: 64;
167
- /** Values one choice filter may ask for. */
168
- choiceValues: 32;
169
- pageMax: 500;
170
- pageDefault: 20;
171
- /** Characters of one value in a query (a filter value, a search text). */
172
- valueChars: 200;
173
- cursorChars: 1024;
174
- }>;
175
- /** Thrown for a declaration that breaks a rule (contract.ts makes it INVALID_CONTRACT). */
176
- export declare class DataSourceIssue extends Error {
177
- }
178
- /**
179
- * Checks the D-0199 part of a data source declaration (`title` and `description` are checked by
180
- * the caller). A declaration with only a title (D-0197) stays valid: it names a data source to
181
- * come, and reading it answers DATA_SOURCE_FAILED until it has fields, sorts and a reader.
182
- */
183
- export declare function readDataSource(input: Record<string, unknown>, where: string, label: (value: unknown, at: string) => Text, permissionOf: (key: string, at: string) => void): Omit<ModuleDataSource, 'title' | 'description'>;
184
- /** Why a request was refused, as the 400 tells it (`data`). */
185
- export interface QueryProblem {
186
- readonly code: 'INVALID_QUERY' | 'INVALID_CURSOR';
187
- readonly reason: string;
188
- readonly name?: string;
189
- readonly message: string;
190
- }
191
- /** A value of `field` read from the query (text) — or undefined when it does not fit the kind. */
192
- export declare function parseValue(field: DataField, text: string): DataValue | undefined;
193
- /** One request checked against the declaration (what the reader gets, minus request and module). */
194
- export type CheckedQuery = Omit<DataSourceRead, 'request' | 'module' | 'source' | 'scope' | 'limit'> & {
195
- readonly pageSize: number;
196
- readonly fingerprint: string;
197
- };
198
- /**
199
- * Checks a query (`fields`, `sort`, `limit`, `cursor`, `q`, `filter.<name>`, `filter.<name>.from`,
200
- * `filter.<name>.to`) against a data source for a caller in `scope`. Anything not declared, not
201
- * offered to the scope or not combinable with the sort is a problem, never ignored.
202
- */
203
- export declare function checkQuery(source: Required<Pick<ModuleDataSource, 'fields' | 'sorts' | 'filters' | 'limit'>> & Pick<ModuleDataSource, 'search'>, query: Readonly<Record<string, unknown>>, scope: string | null): CheckedQuery | QueryProblem;
204
- /** The cursor: `[1, sort, fingerprint, values]` as base64url JSON (opaque to callers). */
205
- export declare function encodeCursor(sort: string, fingerprint: string, values: readonly DataValue[]): string;
206
- export declare function decodeCursor(text: string): {
207
- sort: string;
208
- fingerprint: string;
209
- values: readonly unknown[];
210
- } | undefined;
211
- /** Why a reader's answer breaks the rules (DATA_SOURCE_FAILED), or undefined. */
212
- export declare function rowProblem(rows: unknown, checked: CheckedQuery, fields: Readonly<Record<string, DataField>>, limit: number): string | undefined;
213
- /** The SQL parts of one read (D-0199): `WHERE` conditions, `ORDER BY`, `LIMIT` and parameters. */
214
- export interface ReadSql {
215
- /** Conditions to join with AND (filters, then the cursor); empty when there are none. */
216
- readonly conditions: readonly string[];
217
- readonly params: readonly unknown[];
218
- /** `created_at DESC, id DESC`: the sort's columns in its order (the index's order). */
219
- readonly orderBy: string;
220
- /** Rows to read: `read.limit` (one page plus one). */
221
- readonly limit: number;
222
- /** The next parameter number (PostgreSQL) for conditions the caller adds after these. */
223
- readonly next: number;
224
- }
225
- /**
226
- * Builds the filter, cursor and order parts of a read for a SQL table (`columns` maps each field to
227
- * its column, `m.created_at`). The cursor is a row comparison `(a, b) < ($1, $2)` on PostgreSQL when
228
- * every sort column goes the same way, and the expanded form `a < ? OR (a = ? AND b < ?)` otherwise
229
- * and always on MySQL and MariaDB, which use no row comparison as an index range (@dokebi/db AI.md
230
- * §7.4). Placeholders are `$n` from `start` (PostgreSQL) or `?`. Scope and search stay the
231
- * reader's: add their conditions (and parameters, from `next`) yourself.
232
- */
233
- export declare function readSql(read: Pick<DataSourceRead, 'sort' | 'after' | 'filters' | 'limit'>, options: {
234
- readonly columns: Readonly<Record<string, string>>;
235
- readonly dialect: 'postgres' | 'mysql' | 'mariadb';
236
- readonly start?: number;
237
- }): ReadSql;
238
- export {};