@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/AI.md +3 -244
- package/README.md +1 -5
- package/dist/index.d.ts +2 -27
- package/dist/index.js +13 -159
- package/package.json +3 -13
- package/dist/action-api.d.ts +0 -73
- package/dist/action-api.js +0 -249
- package/dist/action.d.ts +0 -152
- package/dist/action.js +0 -498
- package/dist/contract.d.ts +0 -305
- package/dist/contract.js +0 -524
- package/dist/data-api.d.ts +0 -49
- package/dist/data-api.js +0 -147
- package/dist/data-source.d.ts +0 -238
- package/dist/data-source.js +0 -742
- package/dist/dependency.d.ts +0 -3
- package/dist/dependency.js +0 -10
- package/dist/parts.d.ts +0 -75
- package/dist/parts.js +0 -231
- package/dist/preset.d.ts +0 -25
- package/dist/preset.js +0 -165
package/AI.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# AI guide — @dokebi/module
|
|
2
2
|
|
|
3
|
-
A module is **one feature as a unit of business code** (D-0032). It keeps controllers, services, models, views, routes and sockets in one folder, and apps mount it under a prefix.
|
|
3
|
+
A module is **one feature as a unit of business code** (D-0032). It keeps controllers, services, models, views, routes and sockets in one folder, and apps mount it under a prefix. Business code without a web side (job handlers, event subscriptions, shared APIs) is a module too. Node >=24.0.0, core ^0.4.0. Details are in the [README](README.md).
|
|
4
4
|
|
|
5
5
|
## 1. Creating modules
|
|
6
6
|
|
|
@@ -61,226 +61,6 @@ export default defineModule({
|
|
|
61
61
|
- Route options are `WebRoute` options without `handler` and `constraints` (`ModuleRouteOptions`, so `seal` works).
|
|
62
62
|
- `contributes`: the points of other plugins this module contributes to (§3a). Without it `module.contribute` is `UNDECLARED_POINT`.
|
|
63
63
|
|
|
64
|
-
## 2a. The module contract (0.4.2)
|
|
65
|
-
|
|
66
|
-
A module also declares **what it is made of**, in the same `defineModule` call, so the framework, an editor and an AI read it without running it ([D-0197](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0197-module-contract.md)). Every field is optional; `examples/81-module-contract` uses them all.
|
|
67
|
-
|
|
68
|
-
```ts snippet
|
|
69
|
-
import { defineOptions, option as o } from '@dokebi/core';
|
|
70
|
-
import { defineModule } from '@dokebi/module';
|
|
71
|
-
import memberSettings from '../../settings/members.ts'; // defineSettings({ section: 'members', options })
|
|
72
|
-
|
|
73
|
-
const here = (path: string) => new URL(path, import.meta.url);
|
|
74
|
-
|
|
75
|
-
export default defineModule({
|
|
76
|
-
name: 'members',
|
|
77
|
-
version: '0.1.0',
|
|
78
|
-
title: { en: 'Members', ko: '...' }, // a text, or a text per locale
|
|
79
|
-
description: 'Member accounts and their lists',
|
|
80
|
-
modules: { auth: '^0.1.0' }, // other modules by name and version range
|
|
81
|
-
db: here('./db/'), // db/migrations/<connection>/, db/seeds/<connection>/
|
|
82
|
-
tables: ['members'],
|
|
83
|
-
permissions: { 'members.read': { title: 'Read members' }, 'members.write': { title: 'Change members' } },
|
|
84
|
-
dataSources: { list: { title: 'Member list' } }, // id members.list
|
|
85
|
-
widgets: {
|
|
86
|
-
detail: {
|
|
87
|
-
title: 'Member detail',
|
|
88
|
-
settings: defineOptions({ showJoined: o.boolean({ default: true }) }), // the editor's fields
|
|
89
|
-
template: here('./widgets/detail.html'), // the first HTML, at most 64 KB of UTF-8
|
|
90
|
-
},
|
|
91
|
-
},
|
|
92
|
-
menu: [
|
|
93
|
-
{ id: 'members', title: 'Members', path: '', icon: 'users', permission: 'members.read' },
|
|
94
|
-
{ id: 'new', title: 'New member', path: '/new', parent: 'members', permission: 'members.write' },
|
|
95
|
-
],
|
|
96
|
-
settings: memberSettings, // options.members of dokebi.yaml, checked at start
|
|
97
|
-
locales: here('./locales/'), // locales/<language>/<namespace>.json
|
|
98
|
-
});
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
| Field | Rule |
|
|
102
|
-
|---|---|
|
|
103
|
-
| `title`, `description` | 1–200 characters, or `{ <locale>: text }` (at most 32 locales such as `en`, `ko`, `pt-BR`) |
|
|
104
|
-
| `modules` | `{ <module name>: <version range> }`, at most 64, never the module itself. Each becomes the plugin dependency `dokebi-module.<name>` with that range: core orders the modules and refuses the start without it (`MISSING_DEPENDENCY`) or with another version (`INCOMPATIBLE_VERSION`). The group plugin refuses earlier, naming both modules: `MODULE_MISSING` (the cause of `INVALID_PLUGIN_INPUT` at registration). The group looks only in its own entry, so a module named in `modules` must be in the same group; a module registered alone with `app.register` is not seen there (name it with `requires`, importing it, or put both in the group). Use `requires` for plugins and module instances you import; `modules` names a module without importing it |
|
|
105
|
-
| `db`, `tables` | `db` is the folder URL (ending in `/`) with `migrations/<connection>/` and `seeds/<connection>/`, named as `dokebi-migrate make` names them. **dokebi-migrate runs them**: its option `directories` (default `src/shared/modules/*/db`) adds every module's `db/` to the project's folder, in one name order ([@dokebi/migrate AI.md](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-migrate/AI.md)). Create one with `npx dokebi-migrate make <name> --connection main --directory src/shared/modules/<module>/db`. `tables`: the tables or collections the module owns, at most 64 |
|
|
106
|
-
| `permissions` | `{ '<module>.<action>': { title, description? } }`, at most 256; keys start with the module name (`members.read`) |
|
|
107
|
-
| `dataSources` | `{ <name>: { title, description?, fields, sorts, search?, filters?, actions?, permission \| public, scopes?, scope?, limit?, read } }`, at most 64, lower-case names; the id is `<module>.<name>`. §2b. A data source with only `title` and `description` is named but not readable yet (`readable: false` in describe) |
|
|
108
|
-
| `actions` | `{ <name>: { title, description?, input?, key?, version?, permission, scopes?, scope?, danger?, preview?, run } }`, at most 64, lower-case names; the id is `<module>.<name>`. The writes of the module, §2c ([D-0202](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0202-actions.md)). A data source row action that names one of this module's actions (`update` or `<module>.update`) must name a declared one (`INVALID_CONTRACT` at definition); another module's action is checked when the group sets up |
|
|
109
|
-
| `widgets` | `{ <name>: { title, description?, settings?, template, load?, island? } }`, at most 64. `settings` is a `defineOptions` declaration: the editor draws a widget's fields from its schema and checks entered values with `contract.widgets.<name>.settings.check(values)`. `template` is the file URL of a `.html` file: the start fails (`INVALID_CONTRACT`, the file error as cause) when it is missing, larger than 64 KB or not UTF-8. `load({ settings, request, module, modules, app, form? })` (D-0198; `app`: the title and the visitor's menu of the app that draws it, `ModuleMenuEntry[]`; `form`: only for the widget an app names to draw `<x-form>` — the x-form's class and its `<x-field>` children and the HTML between them, @dokebi/pages D-0204) gives the data the template draws next to its settings, on the server for every placed widget (@dokebi/pages `<x-widget module name>`); `modules` is the module group (D-0200: `data.read` of a data source with the visitor's request); describe never shows it. `island` (D-0200) is the file URL of `islands/<Name>.vue` of the module (PascalCase): the page runs that Vue component in the browser in place of the drawn template, with `{ settings, data }` as props (`{ settings, data, form }` for a form widget); describe gives it as `<module>/<Name>` |
|
|
110
|
-
| `menu` | At most 64 items `{ id, title, path, icon?, permission?, parent?, order? }`: `id` unique in the module; `path` is `''` or `/a/path` below the prefix the app mounts the module at; `permission` a key (one of this module's own keys must be declared in `permissions`); `parent` another item's id (no cycle); `order` −1000 to 1000 (default 0). The app decides where the items go |
|
|
111
|
-
| `settings` | A `defineSettings` result of @dokebi/core. The module checks `options.<section>` at start (`INVALID_PLUGIN_OPTIONS`, paths only); read it with `memberSettings.read(module.app.config)`. Keep the file in `src/shared/settings/` so `npx dokebi settings add`, `config set` and doctor know the section |
|
|
112
|
-
| `locales` | The folder URL of `locales/<language>/<namespace>.json`; @dokebi/i18n reads a module's `locales/` itself (its layers) |
|
|
113
|
-
| `presets` | `{ <name>: { title, kind, folder } }`, at most 16, lower-case names; the id is `<module>.<name>` (dokebi-platform DEC-12, DEC-16). A preset is what an editor copies into a new app: `kind` is `admin` or `front` (the app kinds it is for), `folder` the folder URL (ending in `/`) of a folder shaped like an app's definition folder — `app.yaml`, `theme.css`, `layouts/<name>.html`, `components/<name>.html`, `pages/<path>.html` (D-0198, D-0205); hidden files such as `.DS_Store` are left out. Its `app.yaml` holds only what the preset fills: `layout`, `modules` and `menu` (`{ title, path, icon?, permission?, children? }`); the new-app window gives the rest. **The start refuses** a folder that is missing, holds another file, a file larger than 200 KB, more than 200 files, or an `app.yaml` that is not YAML, has another key or an alias, or breaks @dokebi/pages' app.yaml rules (a layout name of 40 characters at most, menu paths of `[A-Za-z0-9/_.-]`, permissions of 128 characters at most) (`INVALID_CONTRACT`, the file named; [D-0206](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0206-module-presets.md)). What the files hold is @dokebi/pages' check (`checkSiteFiles` of `@dokebi/pages/html`); `isSiteFile` and `checkPresetApp` are exported |
|
|
114
|
-
|
|
115
|
-
- A field that breaks a rule throws `INVALID_CONTRACT` from `defineModule`, naming the field, never a value.
|
|
116
|
-
- The module context (`ModuleContext`) has `contract`: the checked contract of the module (what `@dokebi/mcp/actions` reads its actions from).
|
|
117
|
-
- The group API (`ModuleGroupApi`) has `module(name)`: the mount of a module of the group by its name, or undefined (D-0198; what @dokebi/pages reads to draw widgets).
|
|
118
|
-
- `moduleMount(plugin).contract` is the checked contract (frozen; widget `settings` keep their declaration); `moduleMount(plugin).describe()` returns the JSON `dokebi describe` shows (`DescribedModule`).
|
|
119
|
-
- **`npx dokebi describe --json` lists the modules as `app.modules`**: per module `name`, `version`, `title`, `description`, `requires` (plugins), `modules`, `tables`, `db` (`folder`, `migrations` and `seeds` file names per connection), `permissions[{ key, title, description? }]`, `dataSources[{ id, name, title, description?, readable, fields, sorts, search, filters, actions, permission, scopes, limit }]` (no functions, no hidden fields), `actions[{ id, name, title, description?, input, schema, key?, version?, permission, scopes?, danger }]` (`input` the fields with their rules, `schema` the same as a JSON Schema; no functions), `widgets[{ id, name, title, description?, settings (JSON Schema or null), template (the HTML) }]`, `menu`, `settings` (`{ section, schema }` or null, never a value), `locales` (`folder`, `languages: { <language>: [namespaces] }`), `presets[{ id, name, title, kind, folder, files }]` (`folder` relative to the project, `files` the sorted paths inside it), `contributes`, `views`, `routes`, `sockets`, `events`. The group plugin `dokebi-module` contributes this section only in describe mode; a module registered alone with `app.register` is not listed.
|
|
120
|
-
|
|
121
|
-
## 2b. Data sources and the general read (0.4.2)
|
|
122
|
-
|
|
123
|
-
A data source is a window on the module's data that every caller pages through one general read: a data grid, a screen, another program, an AI ([D-0199](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0199-data-sources.md)). Callers only pick from what the module declared; the module's reader turns a checked request into one SQL page. `examples/83-data-sources` measures every declared combination on PostgreSQL.
|
|
124
|
-
|
|
125
|
-
```ts snippet
|
|
126
|
-
import { type DataSourceRead, defineModule, readSql } from '@dokebi/module';
|
|
127
|
-
|
|
128
|
-
export default defineModule({
|
|
129
|
-
name: 'members',
|
|
130
|
-
permissions: { 'members.read': { title: 'Read members' } },
|
|
131
|
-
dataSources: {
|
|
132
|
-
list: {
|
|
133
|
-
title: { en: 'Member list' },
|
|
134
|
-
fields: {
|
|
135
|
-
id: { type: 'id', label: 'No.' }, // an id is unique
|
|
136
|
-
username: { type: 'text', label: 'Username', unique: true },
|
|
137
|
-
status: { type: 'status', label: 'Status', display: 'badge',
|
|
138
|
-
choices: { active: { label: 'Active' }, blocked: { label: 'Blocked' } } },
|
|
139
|
-
joined: { type: 'datetime', label: 'Joined' },
|
|
140
|
-
path: { type: 'text', label: 'Place', hidden: true, unique: true }, // pages, never returned
|
|
141
|
-
},
|
|
142
|
-
sorts: { // each one index's order
|
|
143
|
-
newest: { label: 'Newest', by: [['joined', 'desc'], ['id', 'desc']], scopes: ['all', 'direct', 'own'] },
|
|
144
|
-
tree: { label: 'Tree', by: [['path', 'asc']] },
|
|
145
|
-
},
|
|
146
|
-
search: { label: 'Username starts with', fields: ['username'], sorts: ['username'], scopes: ['all'] },
|
|
147
|
-
filters: { status: { label: 'Status', field: 'status', kind: 'choice', sorts: ['newest'], scopes: ['all'] } },
|
|
148
|
-
actions: { open: { label: 'Open', href: '/members/{id}' } },
|
|
149
|
-
permission: 'members.read',
|
|
150
|
-
scopes: ['all', 'subtree', 'direct', 'own'],
|
|
151
|
-
scope: ({ request }) => scopeOfCaller(request), // one of scopes, or null (403)
|
|
152
|
-
limit: { default: 20, max: 100 },
|
|
153
|
-
read: (read: DataSourceRead) => members.page(read), // at most read.limit rows
|
|
154
|
-
},
|
|
155
|
-
},
|
|
156
|
-
});
|
|
157
|
-
declare function scopeOfCaller(request: unknown): string | null;
|
|
158
|
-
declare const members: { page(read: DataSourceRead): Promise<object[]> };
|
|
159
|
-
```
|
|
160
|
-
|
|
161
|
-
| Field | Rule |
|
|
162
|
-
|---|---|
|
|
163
|
-
| `fields` | 1–64 `{ type, label, display?, choices?, hidden?, unique? }`. `type`: `id` (unique), `text`, `number`, `money` (a decimal text), `date` (`YYYY-MM-DD`), `datetime`, `status`, `boolean`, `person`, `image`, `file`, `richtext` (a list returns text, an excerpt), `category`, `choice`: one list for data sources, data grids, forms and MCP tools. `boolean`, `image`, `file` and `richtext` cannot be sorted by; `image`, `file` and `richtext` cannot be filtered. `choices` `{ <value>: { label, tone? } }` (at most 64) is what a choice filter offers; `tone` (one of `CHOICE_TONES`: `primary`, `secondary`, `success`, `warning`, `info`, `destructive`) is the colour a grid's dot or badge draws the value in, another word is `INVALID_CONTRACT`; a `status`, `choice` or `category` field with choices takes only those values. `hidden` fields page or filter but are never chosen nor returned |
|
|
164
|
-
| `sorts` | 1–16 `{ label, by, scopes? }`. `by` is 1–4 `[field, 'asc' \| 'desc']` pairs: **the columns of one index, in its order, ending with a unique field** (the cursor's tiebreaker). The first sort a scope may use is its default |
|
|
165
|
-
| `search` | `{ label, fields, minLength? (1), maxLength? (100), sorts?, scopes? }`: what the reader searches; `sorts` are the sorts a search may use (the order its index gives) |
|
|
166
|
-
| `filters` | 0–32 `{ label, field, kind, multiple?, sorts?, scopes? }`. `kind`: `choice` (values among the field's choices; one value unless `multiple: true`, because several values' rows must all be read and sorted), `equal` (one value of the field's kind), `range` (`from` and/or `to` of a number, money, date or datetime field). `sorts`: the sorts it goes with (the index that starts with its field) |
|
|
167
|
-
| `actions` | 0–16 `{ label, href \| action, permission? }`: a link with `{field}` places (declared, not hidden), or a module action by name — `update` or `<module>.<name>` (`members.update`); only the name is checked here, the action contract checks the rest. The caller shows it |
|
|
168
|
-
| `permission` | A key `request.auth.can` must grant (a key of this module must be in `permissions`). A data source with a reader declares `permission` or `public: true`, one of them (`INVALID_CONTRACT` otherwise): none is open by a forgotten line |
|
|
169
|
-
| `public` | `true`: anyone may read, signed in or not (instead of `permission`) |
|
|
170
|
-
| `scopes`, `scope` | Together: the scope names the reader knows, and `scope({ request, module })` giving the caller's (`@dokebi/permissions` `scopeOf` in an app with member types), or null for 403. `sorts`, `search` and `filters` name the scopes they are offered to (default every scope): **offer a scope only what its index pages** — a subtree is one range of an ordered path, so it pages by that path; a parent's members page by `(parent_id, created_at, id)` |
|
|
171
|
-
| `limit` | `{ default?, max? }`: page size, 1 ≤ default ≤ max ≤ 500 (default 20 and 100) |
|
|
172
|
-
| `read` | `read(read: DataSourceRead)` → the rows of one page: at most `read.limit` (page size + 1), in `read.sort` order, after `read.after`, inside `read.scope`, each with every field of `read.select` (the chosen fields and the sort fields). Values are text, number, boolean or null: **dates as text with full precision** (`to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`), never a `Date` |
|
|
173
|
-
|
|
174
|
-
**The general read.** The group API (`ModuleGroupApi.data`) reads any data source of its modules; an app mounts the route in its `routes`:
|
|
175
|
-
|
|
176
|
-
```ts snippet
|
|
177
|
-
import { dependency as modules } from '@dokebi/module/dependency';
|
|
178
|
-
import type { AppContext, AppRouter } from '@dokebi/app';
|
|
179
|
-
|
|
180
|
-
export async function routes(route: AppRouter, app: AppContext): Promise<void> {
|
|
181
|
-
app.getDependency(modules).data.routes(route); // GET /data/:module/:source (route id module.data)
|
|
182
|
-
}
|
|
183
|
-
```
|
|
184
|
-
|
|
185
|
-
`GET /data/members/list?fields=id,username&sort=newest&filter.status=blocked&q=m0&limit=20&cursor=…` answers `{ source, sort, rows, next }`: only the chosen fields, the next page's cursor or null, never a total count. In code: `data.read(request, 'members.list', query)`; `data.ids` lists the readable ones. Parameters: `fields` (required, comma-separated), `sort`, `limit`, `cursor`, `q`, `filter.<name>` (a choice: comma-separated when `multiple`), `filter.<name>.from` and `.to`. In the browser call it with `sealedFetch` (POL-02 of a project: data inside a page by REST, only the fields it shows).
|
|
186
|
-
|
|
187
|
-
- **Refusals**, never ignored: anything not declared, hidden, not offered to the caller's scope or not combinable with the sort is `INVALID_QUERY` (400, `data.reason`: `fields`, `field`, `sort`, `limit`, `parameter`, `search`, `filter`, `value`, `combination`; `data.name` names it). A parameter given twice is `parameter`. A cursor of another sort, filter, search or scope, or one nobody gave, is `INVALID_CURSOR` (400: start again). No permission, no auth or a null scope is `FORBIDDEN` (403). An unknown or name-only data source is `DATA_SOURCE_NOT_FOUND` (404).
|
|
188
|
-
- **The cursor** is base64url JSON of the sort name, a fingerprint of the sort, filters, search and scope, and the sort fields' values of the page's last row; it is checked against the field kinds (`2026-02-30` is no date). It is opaque to callers but not secret: the scope still bounds every page.
|
|
189
|
-
- **A reader that breaks the rules** — more rows than `read.limit`, a missing or mistyped sort field, a `Date` — is `DATA_SOURCE_FAILED` (500, logged at error with the whole error). A reader's own errors (a database down: `DB_UNAVAILABLE` 503) pass through unchanged.
|
|
190
|
-
- **`readSql(read, { columns, dialect, start? })`** builds the filter, cursor and order parts for a SQL table (`columns`: field → column): `{ conditions, params, orderBy, limit, next }`. The cursor is a row comparison on PostgreSQL when every sort column goes one way, and the expanded `a < ? OR (a = ? AND b < ?)` otherwise and always on MySQL and MariaDB (@dokebi/db AI.md §7.4). Add the scope and search conditions yourself (parameters from `next`), then `SELECT <read.select> … WHERE … ORDER BY <orderBy> LIMIT <limit>`. Name the columns with their table (`{ id: 'members.id' }`) when the SELECT gives a field a computed value under the field's name (`id::text AS "id"`): PostgreSQL reads a bare `ORDER BY id` as that output column, so the index order is lost and every page is sorted. A filter `parent = $1` on a parent that holds a large share of the rows can make the planner walk a newest-first index from the cursor and discard the other parents' rows: write that equality as `parent_id = ANY($1::uuid[])` and keep `parent_id` first in the ORDER BY (against the sort's way), so only the `(parent_id, sort…)` index gives the order, and measure the deep page of that parent.
|
|
191
|
-
- **Measure every declared combination** (@dokebi/db AI.md §6.1, §7): each sort, each filter at its rarest, each scope for its busiest owner, the first and a deep page. `assertRowBudget(measure, { maxExamined: 2 * (page + 1), noFullScan: true, noSortOfAll: true })` must hold; when it fails, change the index or stop offering that combination to that scope.
|
|
192
|
-
- Debug logs: `Data sources registered` (ids), `Data source page read` (source, sort, scope, filter names, search, cursor, rows, more, ms).
|
|
193
|
-
|
|
194
|
-
## 2c. Actions and the general write (0.4.2)
|
|
195
|
-
|
|
196
|
-
An action is the write side of a data source ([D-0202](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0202-actions.md)): the module declares what it takes and who may run it, and one general write runs it for every caller — a form, a data grid row button, another program, an AI through MCP. Keep the input rules in the module's `validation/` and the work in its services; `run` only calls the service.
|
|
197
|
-
|
|
198
|
-
```ts snippet
|
|
199
|
-
import { defineModule } from '@dokebi/module';
|
|
200
|
-
import { MemberActions } from './services/member-actions.ts';
|
|
201
|
-
import { memberScope } from './services/member-scope.ts';
|
|
202
|
-
|
|
203
|
-
// validation/update.ts — the input rules, in one place.
|
|
204
|
-
export const updateInput = {
|
|
205
|
-
id: { type: 'id', label: 'No.', required: true },
|
|
206
|
-
version: { type: 'number', label: 'Version', required: true, integer: true, min: 1 },
|
|
207
|
-
name: { type: 'text', label: 'Name', minLength: 1, maxLength: 60, nullable: false },
|
|
208
|
-
status: {
|
|
209
|
-
type: 'status',
|
|
210
|
-
label: 'Status',
|
|
211
|
-
nullable: false,
|
|
212
|
-
choices: { active: { label: 'Active' }, blocked: { label: 'Blocked' } },
|
|
213
|
-
},
|
|
214
|
-
} as const;
|
|
215
|
-
|
|
216
|
-
const service = new MemberActions();
|
|
217
|
-
export default defineModule({
|
|
218
|
-
name: 'members',
|
|
219
|
-
permissions: {
|
|
220
|
-
'members.write': { title: 'Change members' },
|
|
221
|
-
'members.leave': { title: 'Mark members as left' },
|
|
222
|
-
},
|
|
223
|
-
actions: {
|
|
224
|
-
update: {
|
|
225
|
-
title: 'Change a member',
|
|
226
|
-
input: updateInput,
|
|
227
|
-
key: 'id', // the row it changes: a form reads the row by it
|
|
228
|
-
version: 'version', // the version the caller read; the service compares it
|
|
229
|
-
permission: 'members.write', // every action has one (writes are never public)
|
|
230
|
-
scopes: ['all', 'subtree', 'direct', 'own'],
|
|
231
|
-
scope: ({ request }) => memberScope(request),
|
|
232
|
-
run: (run) => service.update(run), // one transaction: lock in reach, compare, change, audit row
|
|
233
|
-
},
|
|
234
|
-
leave: {
|
|
235
|
-
title: 'Mark a member as left',
|
|
236
|
-
input: { id: { type: 'id', label: 'No.', required: true } },
|
|
237
|
-
key: 'id',
|
|
238
|
-
permission: 'members.leave',
|
|
239
|
-
danger: true, // two steps: the preview first, then the same input with confirm
|
|
240
|
-
preview: (run) => service.leavePreview(run), // JSON of what would change (16 KB at most)
|
|
241
|
-
run: (run) => service.leave(run),
|
|
242
|
-
},
|
|
243
|
-
},
|
|
244
|
-
});
|
|
245
|
-
```
|
|
246
|
-
|
|
247
|
-
| Field | Rule |
|
|
248
|
-
|---|---|
|
|
249
|
-
| `input` | 0–64 fields `{ type, label, required?, nullable?, … }` of the shared kinds (`FIELD_TYPES`, §2b; DEC-06: data sources, grids, forms and MCP tools use one list), names `a-z0-9_` (`confirm` is kept by the general write). Per kind: `text` `minLength`, `maxLength` (default 1000, at most 100,000, code points), `format: 'email'`; `number` `min`, `max`, `integer`; `money` a decimal text (`'12.50'`) with `scale` (0–4, default 2), `min`, `max`; `date` `YYYY-MM-DD` (a real date); `datetime` ISO 8601 with `Z` or an offset; `boolean`; `status` and `choice` with `choices` (required; `choice` may be `multiple`: a list of distinct values); `category` (`choices` optional); `id`, `person`, `image`, `file` an id (text up to 128 characters without spaces at the ends or control characters, or a positive whole number); `richtext` a JSON object of at most `maxBytes` (default 64 KB; check its nodes in the service with @dokebi/rich-text). Another rule of another kind is `INVALID_CONTRACT` |
|
|
250
|
-
| `required`, `nullable` | `required`: must be given and not empty (null, `''`, `[]`). Otherwise a field may be left out (**not changed**: the run's `input` has only the given fields) or null (**cleared**); `nullable: false` refuses the clearing (a name that must stay) |
|
|
251
|
-
| `key` | An input field of type `id`: the row the action changes |
|
|
252
|
-
| `version` | A required `number` or `text` input field: the version of the row the caller read. The run compares it with the stored one and throws `actionConflict(message?, { version })` (409 `ACTION_CONFLICT`) when they differ |
|
|
253
|
-
| `permission` | Required: a key `request.auth.can` must grant (a key of this module must be in `permissions`) |
|
|
254
|
-
| `scopes`, `scope` | As for data sources: the caller's scope (`run.scope`), null for 403. **The run checks the reach** (the row is in the scope: lock it with the scope's condition) |
|
|
255
|
-
| `danger`, `preview` | Together. The first call answers 428 `CONFIRM_REQUIRED` with `data: { preview, confirm }` and changes nothing; the same input with `confirm` runs it. The confirm call runs `preview` again: a different preview (the row changed) answers 409 `CONFIRM_STALE` with the new preview and token. The token is a hash of the action, the actor, the input and the preview (no secret, works across workers): it proves the caller was shown this preview, not who the caller is — the permission does that |
|
|
256
|
-
| `run` | `run({ action, input, scope, actor, request, module })` → its result, JSON of at most 64 KB (ids, counts; null when it returns nothing). `actor` is `{ type: 'user' \| 'ai', id?, client? }`: the AI client of an @dokebi/oauth grant (`request.oauth.grant`, its name), else the signed-in user — write it to the audit row (@dokebi/audit `record` in the run's transaction; its `actor(request, name)` gives the same) |
|
|
257
|
-
|
|
258
|
-
**The general write.** The group API (`ModuleGroupApi.actions`) runs any action of its modules; an app mounts the route next to the general read:
|
|
259
|
-
|
|
260
|
-
```ts snippet
|
|
261
|
-
app.getDependency(modules).actions.routes(route); // POST /actions/:module/:action (route id module.action)
|
|
262
|
-
```
|
|
263
|
-
|
|
264
|
-
`POST /actions/members/update` with `{ "input": { "id": "…", "version": 3, "name": "Kim" } }` answers `{ action, result }`. In code: `actions.run(request, 'members.update', { input, confirm? })`; `actions.ids` lists them. A browser page sends it with `sealedFetch` (CSRF and seal included).
|
|
265
|
-
|
|
266
|
-
- **Refusals**: no permission, no auth or a null scope 403 `FORBIDDEN`; an unknown action 404 `ACTION_NOT_FOUND`; a body other than `{ input, confirm? }`, an input field the action does not declare (also `constructor`), or `confirm` on an action that is not dangerous 400 `INVALID_INPUT` (`data.reason`: `body`, `field`, `confirm`; `data.name`). Wrong values are **422 `VALIDATION_FAILED` with `fields` and `errors`** (the shape @dokebi/web answers and template-inertia turns into form errors; one fixed English message per field, `data.rules` names the broken rule: `required`, `type`, `minLength`, `maxLength`, `format`, `min`, `max`, `integer`, `choice`, `size`). Nothing runs before every check passed.
|
|
267
|
-
- **What the service refuses later** (a username taken, a row out of reach): `throw actionInvalid({ field: 'message' }, run.action)`, the same 422. A changed row: `throw actionConflict(undefined, { version })`. Other errors of the run pass through unchanged (`DB_UNAVAILABLE` 503).
|
|
268
|
-
- **`ACTION_FAILED`** (500, logged at error with the whole error): a scope function that answers a name it did not declare, a preview or result that is not JSON or too large.
|
|
269
|
-
- **MCP**: `actionTools(module, { scope?, only? })` of `@dokebi/mcp/actions` makes one tool per action (`members.update`) that runs this same runner; §3a.
|
|
270
|
-
- Debug logs: `Actions registered` (ids), `Action answered` (action, outcome, code, actor type, user, client, ms; never input values).
|
|
271
|
-
|
|
272
|
-
## 2d. UI parts (0.4.2, D-0203)
|
|
273
|
-
|
|
274
|
-
A module that offers UI parts — Vue components, directives, CSS classes for page HTML, and its widgets — lists them in one JSON file the contract points at, so an editor and an AI connected over MCP can find them, their props and their live samples:
|
|
275
|
-
|
|
276
|
-
```ts snippet
|
|
277
|
-
defineModule({ name: 'ui', parts: new URL('./parts.json', import.meta.url), widgets: { 'admin-header': { /* … */ } } });
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
- The file is `{ parts: [...] }`. A part: `name` (`UiButton`, `v-truncate-tooltip`, `.btn`, or a widget name), `kind` (`component` · `directive` · `class` · `widget`), `title` (one line), `description?`, `use?` (when to use it) — each a text or `{ <locale>: text }` — `file?` (inside the module folder), `props?` (`{ name, type, required, default?, description? }`), `slots?` (`{ name, props? }`), `events?` (`{ name, payload? }`), `variants?` (`{ name, description? }`, classes or prop values), `examples?` (markup to start from), `sample?` (an address of the app, `/ui#buttons`). A `widget` part names a widget of the same module (`widget: 'admin-header'`).
|
|
281
|
-
- Generate it from the `.vue` files (props from `defineProps`, slots from the template) rather than writing props by hand, and keep a test that fails when the file is stale or a component is missing. `readParts(url, widgets)` / `checkParts(value, widgets)` check a file with the same rules.
|
|
282
|
-
- `dokebi describe --json` reads and checks it (2 MB at most) and gives `app.modules[].parts` = `{ file, parts }` (null without one). A file that breaks a rule makes the module's description `INVALID_CONTRACT` naming the field (listed under `unavailable`); a running app never reads it. Limits: `PARTS_LIMITS` (512 parts, 128 props/slots/events/variants each, 16 examples).
|
|
283
|
-
|
|
284
64
|
## 3. Mounting on apps and shared APIs
|
|
285
65
|
|
|
286
66
|
- App: `defineApp({ modules: { '/board': board } })`. Routes, sockets and SSE routes answer **only on that app's domains and prefix**. Several apps can mount the same module under different prefixes. The root route (`'/'`) answers `/board` and `/board/`; other paths match exactly. Build links with `page.base` (for example `${page.base}/new`).
|
|
@@ -318,27 +98,6 @@ export default defineModule({
|
|
|
318
98
|
- **No collector**: when no registered plugin collects a point (its plugin is not installed, or a test app leaves it out), the start goes on, the values are dropped and the module hears warn `POINT_NOT_COLLECTED` once per point (`point`, `count`, `fix`). Module tests without the MCP stack keep working; `npx dokebi check` makes the missing plugin an error (`module-point-not-installed`).
|
|
319
99
|
- A module that `requires` the collector of a point it contributes to is a `DEPENDENCY_CYCLE` (the contributor must set up first). Values with rules of their own are checked by the collector (two tools with one name: @dokebi/mcp's `INVALID_TOOL`, naming both modules).
|
|
320
100
|
|
|
321
|
-
**Actions as MCP tools (D-0202).** A module offers its actions (§2c) to AI clients with `actionTools` of `@dokebi/mcp/actions`: one tool per action, named `<module>.<action>`, whose input schema is the action's (`describe` `schema`) and whose handler runs the general write's runner — the same permission, scope, checks, preview and confirm and result.
|
|
322
|
-
|
|
323
|
-
```ts snippet
|
|
324
|
-
import { mcpTools } from '@dokebi/mcp';
|
|
325
|
-
import { actionTools } from '@dokebi/mcp/actions';
|
|
326
|
-
import { defineModule } from '@dokebi/module';
|
|
327
|
-
import { updateAction } from './actions/update.ts';
|
|
328
|
-
|
|
329
|
-
export default defineModule({
|
|
330
|
-
name: 'members',
|
|
331
|
-
permissions: { 'members.write': { title: 'Change members' } },
|
|
332
|
-
actions: { update: updateAction },
|
|
333
|
-
contributes: [mcpTools],
|
|
334
|
-
setup(module) {
|
|
335
|
-
for (const tool of actionTools(module)) module.contribute(mcpTools, tool);
|
|
336
|
-
},
|
|
337
|
-
});
|
|
338
|
-
```
|
|
339
|
-
|
|
340
|
-
The OAuth scope of each tool is the action's permission key by default (`scope` changes it): an OAuth token carries its scopes as abilities, and `request.auth.can(permission)` needs the permission among them, so list the permission keys (or `<module>.*`) in `dokebi-oauth.resources.<id>.scopes`. The run sees `actor: { type: 'ai', id, client }`.
|
|
341
|
-
|
|
342
101
|
## 4. View lookup order (how an app changes a module page)
|
|
343
102
|
|
|
344
103
|
1. `<app>/<template>/<module>/…`
|
|
@@ -352,7 +111,7 @@ To change a module page, an app never edits the module file; it puts a file with
|
|
|
352
111
|
|
|
353
112
|
## 5. Group plugin and lifecycle
|
|
354
113
|
|
|
355
|
-
- `createPlugin({ app, entry: { modules } })`: groups several modules into a dependency graph. The API is `{ names
|
|
114
|
+
- `createPlugin({ app, entry: { modules } })`: groups several modules into a dependency graph. The API is `{ names }` (`ModuleGroupApi`). It accepts only what `defineModule` made; duplicates are `INVALID_PLUGIN_INPUT`. A single module may also be registered directly with `app.register`.
|
|
356
115
|
- Hooks: setup (register routes, return the API) → start → drain (stop new input, wait for work in progress) → deferred cleanup. Drain runs in reverse dependency order (modules that depend on this one first); unrelated modules drain at the same time.
|
|
357
116
|
- A module instance is used by one Application only. There is no automatic discovery, dynamic import or hot reload while running.
|
|
358
117
|
- Options of the group plugin are an empty object.
|
|
@@ -361,7 +120,7 @@ To change a module page, an app never edits the module file; it puts a file with
|
|
|
361
120
|
## 6. Errors
|
|
362
121
|
|
|
363
122
|
<!-- docs-check: complete-error-codes ModuleErrorCode -->
|
|
364
|
-
`DokebiError` (`plugin: 'dokebi-module'`, a `fix` that says how to repair it): `INVALID_DEFINITION` (arguments of `defineModule`), `INVALID_REQUIREMENT` (shape of requires, duplicate names), `INVALID_ENTRY` (the group entry file; at registration the cause of `INVALID_PLUGIN_INPUT`), `ALREADY_SET_UP` (one instance in two apps), `NOT_SET_UP` (context used before setup), `NO_CONTROLLERS`, `VIEWS_MISSING` (no `views/default/`; the file error is the `cause`), `INVALID_CONTRIBUTION` (`contributes` is not a list of distinct points made by `definePoint`, or has more than 64), `UNDECLARED_POINT` (`module.contribute` to a point missing from `contributes`, or `module.collect`; the `fix` names the module)
|
|
123
|
+
`DokebiError` (`plugin: 'dokebi-module'`, a `fix` that says how to repair it): `INVALID_DEFINITION` (arguments of `defineModule`), `INVALID_REQUIREMENT` (shape of requires, duplicate names), `INVALID_ENTRY` (the group entry file; at registration the cause of `INVALID_PLUGIN_INPUT`), `ALREADY_SET_UP` (one instance in two apps), `NOT_SET_UP` (context used before setup), `NO_CONTROLLERS`, `VIEWS_MISSING` (no `views/default/`; the file error is the `cause`), `INVALID_CONTRIBUTION` (`contributes` is not a list of distinct points made by `definePoint`, or has more than 64), `UNDECLARED_POINT` (`module.contribute` to a point missing from `contributes`, or `module.collect`; the `fix` names the module). Warn log `POINT_NOT_COLLECTED` (core): values no registered plugin collects were dropped. Options of the group plugin other than an empty object are `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`). The `defineOptions` declaration in `src/options.ts` is the parser, and the build writes `options.schema.json` from it (D-0063 §3; never edit it by hand). Before 0.4.0 the codes had a `MODULE_` prefix (D-0071).
|
|
365
124
|
|
|
366
125
|
## 7. Cautions
|
|
367
126
|
|
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @dokebi/module 0.4.
|
|
1
|
+
# @dokebi/module 0.4.1
|
|
2
2
|
|
|
3
3
|
An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). A module is **one feature as an MVC unit of business code** ([D-0022](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0022-plugin-boundaries-and-db.md), [D-0032](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0032-feature-modules.md)). It keeps controllers, services, models, views, routes and sockets in one folder, and apps mount it under a prefix. It is not an HTTP-only bundle, so business code without a web side (job processing, event subscriptions) is a module too.
|
|
4
4
|
|
|
@@ -59,10 +59,6 @@ export default defineModule({
|
|
|
59
59
|
- **Sockets and SSE:** the return types of `sockets` and `events` (0.1.3) are defined by shape only (`ModuleSocketRoute`, `ModuleEventRoute`), so projects that do not use them need neither @dokebi/websocket nor @dokebi/sse. The mounting app registers them under its namespace rules ([D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md)): the tenant is `<namespace>:<authenticated tenant>`, and an authenticated `namespace` must be in that app's list.
|
|
60
60
|
- **`moduleMount(plugin)` and `MODULE_MOUNT`:** how the app plugin reads the mounting information. App code never needs them.
|
|
61
61
|
|
|
62
|
-
## The module contract (0.4.2)
|
|
63
|
-
|
|
64
|
-
A module also declares what it is made of — the modules it needs (`modules: { auth: '^0.1.0' }`), its `db/` folder of migrations and seeds and its `tables`, permission keys, data sources, widgets (a settings schema and a first HTML file), menu items, settings (`defineSettings`) and translations — so the framework, an editor and an AI read it without running it ([D-0197](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0197-module-contract.md)). `npx dokebi describe --json` lists it as `app.modules`; an app without a module another one needs refuses to start (`MODULE_MISSING`, then core's `MISSING_DEPENDENCY` or `INCOMPATIBLE_VERSION`); dokebi-migrate runs the module's migrations with the project's own. The rules of each field are in [AI.md](AI.md) §2a, and `examples/81-module-contract` uses them all.
|
|
65
|
-
|
|
66
62
|
## Group plugin
|
|
67
63
|
|
|
68
64
|
`createPlugin({ app: app.view, entry: { modules: [...] } })` groups several modules into a dependency graph and exposes the frozen `names` (plugin contract v2, [D-0028](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0028-plugin-contract-v2.md)).
|
package/dist/index.d.ts
CHANGED
|
@@ -4,26 +4,14 @@ import type { TemplateApi } from '@dokebi/template-ejs';
|
|
|
4
4
|
import type { InertiaApi } from '@dokebi/template-inertia';
|
|
5
5
|
import type { WebRoute } from '@dokebi/web';
|
|
6
6
|
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
7
|
-
import { type ActionApi, type ActionErrorCode } from './action-api.js';
|
|
8
|
-
import { type DescribedModule, type ModuleContract, type ModuleContractFields } from './contract.js';
|
|
9
|
-
import { type DataApi, type DataErrorCode } from './data-api.js';
|
|
10
|
-
export { ACTION_LIMITS, type ActionActor, type ActionField, type ActionFieldProblem, type ActionRun, type ActionTextFormat, checkInput, inputSchema, type ModuleAction, TEXT_FORMATS, } from './action.js';
|
|
11
|
-
export { type ActionApi, type ActionBody, type ActionEntry, type ActionErrorCode, type ActionHandler, type ActionResult, type ActionRouter, ActionValidationError, actionConflict, actionError, actionInvalid, actorOf, runAction, } from './action-api.js';
|
|
12
|
-
export { CONTRACT_LIMITS, type DescribedAction, type DescribedDataSource, type DescribedModule, islandName, type ModuleContract, type ModuleContractFields, type ModuleDataSource, type ModuleMenuEntry, type ModuleMenuItem, type ModulePermission, type ModulePreset, type ModuleText, type ModuleWidget, type ModuleWidgetLoadInput, } from './contract.js';
|
|
13
|
-
export { type DataApi, type DataErrorCode, type DataHandler, type DataPage, type DataRouter, dataError, } from './data-api.js';
|
|
14
|
-
export { CHOICE_TONES, type ChoiceTone, checkQuery, DATA_LIMITS, type DataAction, type DataField, type DataFieldType, type DataFilter, type DataFilterKind, type DataFilterValue, type DataRow, type DataSearch, type DataSort, type DataSourceRead, type DataValue, decodeCursor, encodeCursor, FIELD_TYPES, type ReadSql, readSql, } from './data-source.js';
|
|
15
|
-
export { checkParts, type ModulePart, type ModuleParts, PART_KINDS, PARTS_LIMITS, type PartEvent, type PartKind, type PartProp, type PartSlot, PartsIssue, type PartText, type PartVariant, readParts, } from './parts.js';
|
|
16
|
-
export { checkPresetApp, isSiteFile, PRESET_APP_KEYS, PRESET_KINDS, PRESET_LIMITS, type PresetKind, } from './preset.js';
|
|
17
7
|
/** Codes of the errors this package throws (`DokebiError` with `plugin: 'dokebi-module'`). */
|
|
18
|
-
export type ModuleErrorCode = 'INVALID_DEFINITION' | 'INVALID_REQUIREMENT' | 'INVALID_ENTRY' | 'ALREADY_SET_UP' | 'NOT_SET_UP' | 'NO_CONTROLLERS' | 'VIEWS_MISSING' | 'INVALID_CONTRIBUTION' | 'UNDECLARED_POINT'
|
|
8
|
+
export type ModuleErrorCode = 'INVALID_DEFINITION' | 'INVALID_REQUIREMENT' | 'INVALID_ENTRY' | 'ALREADY_SET_UP' | 'NOT_SET_UP' | 'NO_CONTROLLERS' | 'VIEWS_MISSING' | 'INVALID_CONTRIBUTION' | 'UNDECLARED_POINT';
|
|
19
9
|
/** A plugin instance (read with context.get) or a descriptor (read with context.getDependency). */
|
|
20
10
|
export type ModuleRequirement = Plugin<unknown> | PluginDependency;
|
|
21
11
|
/** The plugin context of a module, plus the controllers the module declares. */
|
|
22
12
|
export interface ModuleContext extends PluginContext {
|
|
23
13
|
/** The module name (the folder name under src/shared/modules). */
|
|
24
14
|
readonly module: string;
|
|
25
|
-
/** The checked contract of the module (D-0197): what `@dokebi/module/mcp` reads its actions from. */
|
|
26
|
-
readonly contract: ModuleContract;
|
|
27
15
|
controller<T>(definition: ControllerDefinition<T>): T;
|
|
28
16
|
}
|
|
29
17
|
/** What a module route handler receives besides the Fastify request and reply (D-0032). */
|
|
@@ -95,7 +83,7 @@ export interface ModuleEventRoute {
|
|
|
95
83
|
readonly namespace?: string;
|
|
96
84
|
} | undefined>;
|
|
97
85
|
}
|
|
98
|
-
export interface ModuleDefinition<T>
|
|
86
|
+
export interface ModuleDefinition<T> {
|
|
99
87
|
readonly name: string;
|
|
100
88
|
/** Exact plugin version of this module. Default '0.1.0'. */
|
|
101
89
|
readonly version?: string;
|
|
@@ -136,10 +124,6 @@ export interface ModuleMount {
|
|
|
136
124
|
readonly events: ModuleDefinition<unknown>['events'];
|
|
137
125
|
/** The module context; available once the module has been set up. */
|
|
138
126
|
context(): ModuleContext;
|
|
139
|
-
/** The checked contract (D-0197): what the module declares about itself. */
|
|
140
|
-
readonly contract: ModuleContract;
|
|
141
|
-
/** The module as `dokebi describe --json` gives it (reads its folders and widget templates). */
|
|
142
|
-
describe(): Promise<DescribedModule>;
|
|
143
127
|
}
|
|
144
128
|
export declare const MODULE_MOUNT: unique symbol;
|
|
145
129
|
export declare function defineModule<T = void>(definition: ModuleDefinition<T>): Plugin<T>;
|
|
@@ -150,14 +134,5 @@ export interface ModuleEntry {
|
|
|
150
134
|
}
|
|
151
135
|
export interface ModuleGroupApi {
|
|
152
136
|
readonly names: readonly string[];
|
|
153
|
-
/**
|
|
154
|
-
* The mount of a module of this group by its name (`members`), or undefined (D-0198): what an
|
|
155
|
-
* app runtime such as @dokebi/pages reads to draw the module's widgets.
|
|
156
|
-
*/
|
|
157
|
-
module(name: string): ModuleMount | undefined;
|
|
158
|
-
/** The data sources of the modules (D-0199): the general read and its route. */
|
|
159
|
-
readonly data: DataApi;
|
|
160
|
-
/** The actions of the modules (D-0202): the general write and its route. */
|
|
161
|
-
readonly actions: ActionApi;
|
|
162
137
|
}
|
|
163
138
|
export declare const createPlugin: import("@dokebi/core").PluginFactory<ModuleGroupApi>;
|