@dokebi/module 0.4.1 → 0.4.2
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 +244 -3
- package/README.md +5 -1
- package/dist/action-api.d.ts +73 -0
- package/dist/action-api.js +249 -0
- package/dist/action.d.ts +152 -0
- package/dist/action.js +498 -0
- package/dist/contract.d.ts +305 -0
- package/dist/contract.js +524 -0
- package/dist/data-api.d.ts +49 -0
- package/dist/data-api.js +147 -0
- package/dist/data-source.d.ts +238 -0
- package/dist/data-source.js +742 -0
- package/dist/dependency.d.ts +3 -0
- package/dist/dependency.js +10 -0
- package/dist/index.d.ts +27 -2
- package/dist/index.js +158 -10
- package/dist/parts.d.ts +75 -0
- package/dist/parts.js +231 -0
- package/dist/preset.d.ts +25 -0
- package/dist/preset.js +165 -0
- package/package.json +13 -3
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The module group as a dependency (D-0199): an app's routes read the group API with
|
|
2
|
+
// `app.getDependency(dependency)` — `data.routes(route)` mounts the general read of the data sources.
|
|
3
|
+
import { defineProvider } from '@dokebi/core';
|
|
4
|
+
export const provider = defineProvider({
|
|
5
|
+
name: 'dokebi-module',
|
|
6
|
+
packageName: '@dokebi/module',
|
|
7
|
+
version: '^0.4.2',
|
|
8
|
+
load: () => import('./index.js'),
|
|
9
|
+
});
|
|
10
|
+
export const dependency = provider.dependency;
|
package/dist/index.d.ts
CHANGED
|
@@ -4,14 +4,26 @@ 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';
|
|
7
17
|
/** Codes of the errors this package throws (`DokebiError` with `plugin: 'dokebi-module'`). */
|
|
8
|
-
export type ModuleErrorCode = 'INVALID_DEFINITION' | 'INVALID_REQUIREMENT' | 'INVALID_ENTRY' | 'ALREADY_SET_UP' | 'NOT_SET_UP' | 'NO_CONTROLLERS' | 'VIEWS_MISSING' | 'INVALID_CONTRIBUTION' | 'UNDECLARED_POINT';
|
|
18
|
+
export type ModuleErrorCode = 'INVALID_DEFINITION' | 'INVALID_REQUIREMENT' | 'INVALID_ENTRY' | 'ALREADY_SET_UP' | 'NOT_SET_UP' | 'NO_CONTROLLERS' | 'VIEWS_MISSING' | 'INVALID_CONTRIBUTION' | 'UNDECLARED_POINT' | 'INVALID_CONTRACT' | 'MODULE_MISSING' | DataErrorCode | ActionErrorCode;
|
|
9
19
|
/** A plugin instance (read with context.get) or a descriptor (read with context.getDependency). */
|
|
10
20
|
export type ModuleRequirement = Plugin<unknown> | PluginDependency;
|
|
11
21
|
/** The plugin context of a module, plus the controllers the module declares. */
|
|
12
22
|
export interface ModuleContext extends PluginContext {
|
|
13
23
|
/** The module name (the folder name under src/shared/modules). */
|
|
14
24
|
readonly module: string;
|
|
25
|
+
/** The checked contract of the module (D-0197): what `@dokebi/module/mcp` reads its actions from. */
|
|
26
|
+
readonly contract: ModuleContract;
|
|
15
27
|
controller<T>(definition: ControllerDefinition<T>): T;
|
|
16
28
|
}
|
|
17
29
|
/** What a module route handler receives besides the Fastify request and reply (D-0032). */
|
|
@@ -83,7 +95,7 @@ export interface ModuleEventRoute {
|
|
|
83
95
|
readonly namespace?: string;
|
|
84
96
|
} | undefined>;
|
|
85
97
|
}
|
|
86
|
-
export interface ModuleDefinition<T> {
|
|
98
|
+
export interface ModuleDefinition<T> extends ModuleContractFields {
|
|
87
99
|
readonly name: string;
|
|
88
100
|
/** Exact plugin version of this module. Default '0.1.0'. */
|
|
89
101
|
readonly version?: string;
|
|
@@ -124,6 +136,10 @@ export interface ModuleMount {
|
|
|
124
136
|
readonly events: ModuleDefinition<unknown>['events'];
|
|
125
137
|
/** The module context; available once the module has been set up. */
|
|
126
138
|
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>;
|
|
127
143
|
}
|
|
128
144
|
export declare const MODULE_MOUNT: unique symbol;
|
|
129
145
|
export declare function defineModule<T = void>(definition: ModuleDefinition<T>): Plugin<T>;
|
|
@@ -134,5 +150,14 @@ export interface ModuleEntry {
|
|
|
134
150
|
}
|
|
135
151
|
export interface ModuleGroupApi {
|
|
136
152
|
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;
|
|
137
162
|
}
|
|
138
163
|
export declare const createPlugin: import("@dokebi/core").PluginFactory<ModuleGroupApi>;
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
import { stat } from 'node:fs/promises';
|
|
2
2
|
import { fileURLToPath } from 'node:url';
|
|
3
3
|
import { types } from 'node:util';
|
|
4
|
-
import { DokebiError, definePlugin, dependencyOf, providerDependency, } from '@dokebi/core';
|
|
4
|
+
import { DokebiError, definePlugin, definePoint, dependencyOf, providerDependency, } from '@dokebi/core';
|
|
5
|
+
import { createActionApi, } from './action-api.js';
|
|
6
|
+
import { CONTRACT_KEYS, ContractIssue, describeContract, readContract, readPresets, readTemplate, } from './contract.js';
|
|
7
|
+
import { createDataApi } from './data-api.js';
|
|
5
8
|
import { options } from './options.js';
|
|
9
|
+
export { ACTION_LIMITS, checkInput, inputSchema, TEXT_FORMATS, } from './action.js';
|
|
10
|
+
export { ActionValidationError, actionConflict, actionError, actionInvalid, actorOf, runAction, } from './action-api.js';
|
|
11
|
+
export { CONTRACT_LIMITS, islandName, } from './contract.js';
|
|
12
|
+
export { dataError, } from './data-api.js';
|
|
13
|
+
export { CHOICE_TONES, checkQuery, DATA_LIMITS, decodeCursor, encodeCursor, FIELD_TYPES, readSql, } from './data-source.js';
|
|
14
|
+
export { checkParts, PART_KINDS, PARTS_LIMITS, PartsIssue, readParts, } from './parts.js';
|
|
15
|
+
export { checkPresetApp, isSiteFile, PRESET_APP_KEYS, PRESET_KINDS, PRESET_LIMITS, } from './preset.js';
|
|
6
16
|
const FIX = {
|
|
7
17
|
INVALID_DEFINITION: 'Pass defineModule a lower-case name (a-z, 0-9, ., _, -) and only the documented fields: requires and controllers arrays, views as a file: URL, hooks as functions.',
|
|
8
18
|
INVALID_REQUIREMENT: 'List plugin instances or dependency descriptors ({ name, version }) in requires, each name once.',
|
|
@@ -13,6 +23,8 @@ const FIX = {
|
|
|
13
23
|
VIEWS_MISSING: 'Create the views/default/ folder of the module (the cause names the file system error), or remove views.',
|
|
14
24
|
INVALID_CONTRIBUTION: 'List in contributes the points made by definePoint that the module contributes to, each once and at most 64 (import them from the plugin that owns them, as mcpTools from @dokebi/mcp).',
|
|
15
25
|
UNDECLARED_POINT: 'Add the point to contributes of defineModule and call module.contribute(point, value) in the setup of the module. Modules only contribute: a plugin collects.',
|
|
26
|
+
INVALID_CONTRACT: 'Correct the contract fields of defineModule as the message says (AI.md of @dokebi/module, section 2a): titles, permission keys <module>.<action>, data source, action (input fields, permission, danger with preview), widget and menu names, file: URLs for db, locales and widget templates (.html, at most 64 KB).',
|
|
27
|
+
MODULE_MISSING: 'Add the module the message names to the project (npx dokebi module add <name>, or its package), or remove it from modules of the module that needs it.',
|
|
16
28
|
};
|
|
17
29
|
function moduleError(code, message, cause, fix = FIX[code]) {
|
|
18
30
|
return new DokebiError(code, message, {
|
|
@@ -23,6 +35,13 @@ function moduleError(code, message, cause, fix = FIX[code]) {
|
|
|
23
35
|
}
|
|
24
36
|
export const MODULE_MOUNT = Symbol.for('dokebi.module.mount');
|
|
25
37
|
const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
38
|
+
/** Module plugins are `dokebi-module.<name>` (D-0032). */
|
|
39
|
+
const MODULE_PREFIX = 'dokebi-module.';
|
|
40
|
+
/**
|
|
41
|
+
* The `core:describe` point of @dokebi/core 0.4.2, declared here by name (its identity) so this
|
|
42
|
+
* package keeps working with older cores, which never describe.
|
|
43
|
+
*/
|
|
44
|
+
const describePoint = definePoint('core:describe');
|
|
26
45
|
/** core's point name (`<owner plugin>:<name>`) and its limit per plugin (D-0063). */
|
|
27
46
|
const POINT_NAME = /^[a-z0-9][a-z0-9._/-]{0,95}:[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
28
47
|
const POINT_LIMIT = 64;
|
|
@@ -39,6 +58,7 @@ const DEFINITION_KEYS = new Set([
|
|
|
39
58
|
'setup',
|
|
40
59
|
'start',
|
|
41
60
|
'drain',
|
|
61
|
+
...CONTRACT_KEYS,
|
|
42
62
|
]);
|
|
43
63
|
const ejs = providerDependency({
|
|
44
64
|
name: 'dokebi-template-ejs',
|
|
@@ -75,11 +95,12 @@ function contributedPoints(value, module) {
|
|
|
75
95
|
}
|
|
76
96
|
return Object.freeze([...names]);
|
|
77
97
|
}
|
|
78
|
-
function moduleContext(context, name, declared, controllers, points) {
|
|
98
|
+
function moduleContext(context, name, declared, controllers, points, contract) {
|
|
79
99
|
// core accepts only the descriptor object this module declared; look it up by name.
|
|
80
100
|
const own = (dependency) => declared.get(dependency?.name) ?? dependency;
|
|
81
101
|
return Object.freeze({
|
|
82
102
|
module: name,
|
|
103
|
+
contract,
|
|
83
104
|
get app() {
|
|
84
105
|
return context.app;
|
|
85
106
|
},
|
|
@@ -139,9 +160,21 @@ export function defineModule(definition) {
|
|
|
139
160
|
['routes', 'sockets', 'events', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function'))
|
|
140
161
|
throw moduleError('INVALID_DEFINITION', 'Invalid module definition');
|
|
141
162
|
const { name, views } = definition;
|
|
163
|
+
let contract;
|
|
164
|
+
try {
|
|
165
|
+
contract = readContract(name, definition);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
if (error instanceof ContractIssue)
|
|
169
|
+
throw moduleError('INVALID_CONTRACT', error.message);
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
142
172
|
const points = contributedPoints(definition.contributes, name);
|
|
143
173
|
const pointSet = new Set(points);
|
|
144
174
|
const dependencies = (definition.requires ?? []).map(requirement);
|
|
175
|
+
// D-0197: the modules it needs by name and range; core refuses the start without them.
|
|
176
|
+
for (const [other, range] of Object.entries(contract.modules))
|
|
177
|
+
dependencies.push(Object.freeze({ name: MODULE_PREFIX + other, version: range }));
|
|
145
178
|
if (new Set(dependencies.map((dependency) => dependency.name)).size !== dependencies.length)
|
|
146
179
|
throw moduleError('INVALID_REQUIREMENT', 'Duplicate module requirement');
|
|
147
180
|
if (views && !dependencies.some((dependency) => dependency.name === ejs.name))
|
|
@@ -155,7 +188,7 @@ export function defineModule(definition) {
|
|
|
155
188
|
const prefix = `module.${name}`;
|
|
156
189
|
const hook = (key) => async (context) => {
|
|
157
190
|
const begin = performance.now();
|
|
158
|
-
await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet));
|
|
191
|
+
await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet, contract));
|
|
159
192
|
context.logger.log('debug', `Module ${key} finished`, {
|
|
160
193
|
module: name,
|
|
161
194
|
ms: Math.round(performance.now() - begin),
|
|
@@ -163,7 +196,7 @@ export function defineModule(definition) {
|
|
|
163
196
|
};
|
|
164
197
|
const plugin = {
|
|
165
198
|
metadata: Object.freeze({
|
|
166
|
-
name:
|
|
199
|
+
name: MODULE_PREFIX + name,
|
|
167
200
|
version,
|
|
168
201
|
core: '^0.4.0',
|
|
169
202
|
dependencies: Object.freeze(dependencies),
|
|
@@ -174,7 +207,7 @@ export function defineModule(definition) {
|
|
|
174
207
|
if (started)
|
|
175
208
|
throw moduleError('ALREADY_SET_UP', 'Create one module instance per Application');
|
|
176
209
|
started = true;
|
|
177
|
-
current = moduleContext(context, name, declared, () => controllers, pointSet);
|
|
210
|
+
current = moduleContext(context, name, declared, () => controllers, pointSet, contract);
|
|
178
211
|
const begin = performance.now();
|
|
179
212
|
if (definition.controllers?.length) {
|
|
180
213
|
const { createControllers } = await import('@dokebi/controller');
|
|
@@ -192,6 +225,26 @@ export function defineModule(definition) {
|
|
|
192
225
|
throw moduleError('VIEWS_MISSING', `Module ${name} has no views/default/ folder`, failure);
|
|
193
226
|
await context.getDependency(templates ?? ejs).addDirectory(views, prefix);
|
|
194
227
|
}
|
|
228
|
+
// D-0197: a widget's first HTML must be readable and its settings valid before anything runs.
|
|
229
|
+
for (const [widget, item] of Object.entries(contract.widgets)) {
|
|
230
|
+
try {
|
|
231
|
+
await readTemplate(item.template);
|
|
232
|
+
}
|
|
233
|
+
catch (cause) {
|
|
234
|
+
throw moduleError('INVALID_CONTRACT', `The template of widget ${widget} of module ${name} cannot be read as UTF-8 HTML of at most 64 KB`, cause);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
// dokebi-platform DEC-16: a preset folder must have the shape of an app folder before anything runs.
|
|
238
|
+
try {
|
|
239
|
+
await readPresets(name, contract.presets);
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
if (error instanceof ContractIssue)
|
|
243
|
+
throw moduleError('INVALID_CONTRACT', error.message);
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
// Throws INVALID_PLUGIN_OPTIONS (paths, never values) for settings that do not fit.
|
|
247
|
+
contract.settings?.read(context.app.config);
|
|
195
248
|
const api = (await definition.setup?.(current));
|
|
196
249
|
context.logger.log('debug', 'Module set up', {
|
|
197
250
|
module: name,
|
|
@@ -203,6 +256,13 @@ export function defineModule(definition) {
|
|
|
203
256
|
routes: Boolean(definition.routes),
|
|
204
257
|
sockets: Boolean(definition.sockets),
|
|
205
258
|
events: Boolean(definition.events),
|
|
259
|
+
modules: contract.modules,
|
|
260
|
+
permissions: Object.keys(contract.permissions).length,
|
|
261
|
+
dataSources: Object.keys(contract.dataSources),
|
|
262
|
+
actions: Object.keys(contract.actions),
|
|
263
|
+
widgets: Object.keys(contract.widgets),
|
|
264
|
+
menu: contract.menu.length,
|
|
265
|
+
settings: contract.settings?.section ?? false,
|
|
206
266
|
ms: Math.round(performance.now() - begin),
|
|
207
267
|
});
|
|
208
268
|
return api;
|
|
@@ -221,6 +281,27 @@ export function defineModule(definition) {
|
|
|
221
281
|
throw moduleError('NOT_SET_UP', `Module ${name} is not set up yet`);
|
|
222
282
|
return current;
|
|
223
283
|
},
|
|
284
|
+
contract,
|
|
285
|
+
describe: () => describeContract({
|
|
286
|
+
name,
|
|
287
|
+
version,
|
|
288
|
+
requires: dependencies
|
|
289
|
+
.map((dependency) => dependency.name)
|
|
290
|
+
.filter((dependency) => !dependency.startsWith(MODULE_PREFIX)),
|
|
291
|
+
contributes: points,
|
|
292
|
+
views: views ? prefix : undefined,
|
|
293
|
+
hooks: {
|
|
294
|
+
routes: Boolean(definition.routes),
|
|
295
|
+
sockets: Boolean(definition.sockets),
|
|
296
|
+
events: Boolean(definition.events),
|
|
297
|
+
},
|
|
298
|
+
contract,
|
|
299
|
+
}).catch((error) => {
|
|
300
|
+
// A parts file that breaks its rules (D-0203) is found here, when it is read.
|
|
301
|
+
if (error instanceof ContractIssue)
|
|
302
|
+
throw moduleError('INVALID_CONTRACT', error.message);
|
|
303
|
+
throw error;
|
|
304
|
+
}),
|
|
224
305
|
});
|
|
225
306
|
Object.defineProperty(plugin, MODULE_MOUNT, { value: mount });
|
|
226
307
|
return Object.freeze(plugin);
|
|
@@ -258,27 +339,94 @@ function parseEntry(input) {
|
|
|
258
339
|
if (!Array.isArray(modules) || modules.length > LIMIT)
|
|
259
340
|
throw moduleError('INVALID_ENTRY', 'Expected a modules array');
|
|
260
341
|
const names = modules.map((module) => module?.metadata?.name);
|
|
261
|
-
if (names.some((name) => typeof name !== 'string' || !name.startsWith(
|
|
342
|
+
if (names.some((name) => typeof name !== 'string' || !name.startsWith(MODULE_PREFIX)) ||
|
|
262
343
|
new Set(names).size !== names.length)
|
|
263
344
|
throw moduleError('INVALID_ENTRY', 'Expected distinct module plugins');
|
|
345
|
+
// D-0197: a module that needs another one which is not in the project says so by name, before
|
|
346
|
+
// core's MISSING_DEPENDENCY (whose message only names the plugin).
|
|
347
|
+
const present = new Set(names);
|
|
348
|
+
for (const module of modules) {
|
|
349
|
+
const mount = moduleMount(module);
|
|
350
|
+
for (const [other, range] of Object.entries(mount?.contract?.modules ?? {}))
|
|
351
|
+
if (!present.has(MODULE_PREFIX + other))
|
|
352
|
+
throw moduleError('MODULE_MISSING', `Module ${mount?.name} needs module ${other} (${range}), which is not in the project`, undefined, `Add module ${other} to the project (npx dokebi module add ${other}, or install the package that provides it), or remove ${other} from modules of module ${mount?.name}.`);
|
|
353
|
+
}
|
|
264
354
|
return [...modules];
|
|
265
355
|
}
|
|
266
356
|
class ModuleGroupRuntime {
|
|
267
357
|
names;
|
|
268
|
-
|
|
358
|
+
modules;
|
|
359
|
+
constructor(names, modules) {
|
|
269
360
|
this.names = names;
|
|
361
|
+
this.modules = modules;
|
|
270
362
|
}
|
|
271
363
|
setup(context) {
|
|
272
364
|
context.logger.log('debug', 'Modules registered', { modules: this.names });
|
|
273
|
-
|
|
365
|
+
// D-0197: only `dokebi describe` (runtime.describing) asks; a normal start adds nothing.
|
|
366
|
+
if (context.runtime.describing) {
|
|
367
|
+
const mounts = this.modules
|
|
368
|
+
.map((module) => moduleMount(module))
|
|
369
|
+
.filter((mount) => mount !== undefined);
|
|
370
|
+
context.contribute(describePoint, {
|
|
371
|
+
section: 'modules',
|
|
372
|
+
describe: async () => {
|
|
373
|
+
const described = [];
|
|
374
|
+
for (const mount of mounts)
|
|
375
|
+
described.push(await mount.describe());
|
|
376
|
+
return described;
|
|
377
|
+
},
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
const byName = new Map();
|
|
381
|
+
for (const module of this.modules) {
|
|
382
|
+
const mount = moduleMount(module);
|
|
383
|
+
if (mount)
|
|
384
|
+
byName.set(mount.name, mount);
|
|
385
|
+
}
|
|
386
|
+
const sources = new Map();
|
|
387
|
+
for (const mount of byName.values())
|
|
388
|
+
for (const [name, declaration] of Object.entries(mount.contract?.dataSources ?? {}))
|
|
389
|
+
sources.set(`${mount.name}.${name}`, {
|
|
390
|
+
module: mount.name,
|
|
391
|
+
declaration,
|
|
392
|
+
context: () => mount.context(),
|
|
393
|
+
});
|
|
394
|
+
const data = createDataApi(sources, context.logger);
|
|
395
|
+
context.logger.log('debug', 'Data sources registered', { sources: data.ids });
|
|
396
|
+
const actions = new Map();
|
|
397
|
+
for (const mount of byName.values())
|
|
398
|
+
for (const [name, declaration] of Object.entries(mount.contract?.actions ?? {}))
|
|
399
|
+
actions.set(`${mount.name}.${name}`, {
|
|
400
|
+
id: `${mount.name}.${name}`,
|
|
401
|
+
module: mount.name,
|
|
402
|
+
declaration,
|
|
403
|
+
context: () => mount.context(),
|
|
404
|
+
});
|
|
405
|
+
// D-0202: a row action naming another module's action names one that module declares.
|
|
406
|
+
for (const mount of byName.values())
|
|
407
|
+
for (const [source, item] of Object.entries(mount.contract?.dataSources ?? {}))
|
|
408
|
+
for (const [name, rowAction] of Object.entries(item.actions ?? {})) {
|
|
409
|
+
const target = rowAction.action;
|
|
410
|
+
if (target?.includes('.') && !actions.has(target))
|
|
411
|
+
throw moduleError('INVALID_CONTRACT', `dataSources.${source}.actions.${name}.action of module ${mount.name} names ${target}, which no module of the project declares`);
|
|
412
|
+
}
|
|
413
|
+
const write = createActionApi(actions, context.logger);
|
|
414
|
+
context.logger.log('debug', 'Actions registered', { actions: write.ids });
|
|
415
|
+
return Object.freeze({
|
|
416
|
+
names: this.names,
|
|
417
|
+
module: (name) => byName.get(name),
|
|
418
|
+
data,
|
|
419
|
+
actions: write,
|
|
420
|
+
});
|
|
274
421
|
}
|
|
275
422
|
}
|
|
276
423
|
export const createPlugin = definePlugin({
|
|
277
424
|
name: 'dokebi-module',
|
|
278
|
-
version: '0.4.
|
|
425
|
+
version: '0.4.2',
|
|
279
426
|
core: '^0.4.0',
|
|
280
427
|
options,
|
|
428
|
+
contributes: [describePoint],
|
|
281
429
|
entry: parseEntry,
|
|
282
430
|
dependencies: ({ entry }) => (entry ?? []).map((module) => dependencyOf(module)),
|
|
283
|
-
instance: ({ dependencies }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name))),
|
|
431
|
+
instance: ({ dependencies, entry }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name)), Object.freeze([...(entry ?? [])])),
|
|
284
432
|
});
|
package/dist/parts.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** A text, or a text per locale (`{ en: 'Button', ko: '단추' }`). */
|
|
2
|
+
export type PartText = string | Readonly<Record<string, string>>;
|
|
3
|
+
export declare const PART_KINDS: readonly ['component', 'directive', 'class', 'widget'];
|
|
4
|
+
export type PartKind = (typeof PART_KINDS)[number];
|
|
5
|
+
export interface PartProp {
|
|
6
|
+
readonly name: string;
|
|
7
|
+
/** The type as written (`'sm' | 'md'`, `boolean`, `UiOption[]`). */
|
|
8
|
+
readonly type: string;
|
|
9
|
+
readonly required: boolean;
|
|
10
|
+
/** The default as written (`'md'`, `false`, `() => []`), when there is one. */
|
|
11
|
+
readonly default?: string;
|
|
12
|
+
readonly description?: PartText;
|
|
13
|
+
}
|
|
14
|
+
export interface PartSlot {
|
|
15
|
+
readonly name: string;
|
|
16
|
+
/** What the slot hands its content (`{ row, value }`), when anything. */
|
|
17
|
+
readonly props?: string;
|
|
18
|
+
readonly description?: PartText;
|
|
19
|
+
}
|
|
20
|
+
export interface PartEvent {
|
|
21
|
+
readonly name: string;
|
|
22
|
+
/** The payload type (`[value: string]`), when there is one. */
|
|
23
|
+
readonly payload?: string;
|
|
24
|
+
readonly description?: PartText;
|
|
25
|
+
}
|
|
26
|
+
export interface PartVariant {
|
|
27
|
+
/** A class (`btn-primary`) or a prop value (`variant="outline"`). */
|
|
28
|
+
readonly name: string;
|
|
29
|
+
readonly description?: PartText;
|
|
30
|
+
}
|
|
31
|
+
export interface ModulePart {
|
|
32
|
+
/** `UiButton`, `v-truncate-tooltip`, `.btn`, or the widget's name. */
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly kind: PartKind;
|
|
35
|
+
/** One line: what it is. */
|
|
36
|
+
readonly title: PartText;
|
|
37
|
+
readonly description?: PartText;
|
|
38
|
+
/** When to use it (and when not). */
|
|
39
|
+
readonly use?: PartText;
|
|
40
|
+
/** The source file, relative to the module folder. */
|
|
41
|
+
readonly file?: string;
|
|
42
|
+
readonly props?: readonly PartProp[];
|
|
43
|
+
readonly slots?: readonly PartSlot[];
|
|
44
|
+
readonly events?: readonly PartEvent[];
|
|
45
|
+
readonly variants?: readonly PartVariant[];
|
|
46
|
+
/** Markup to start from (Vue template or page HTML). */
|
|
47
|
+
readonly examples?: readonly string[];
|
|
48
|
+
/** Where its live sample is (`/ui#buttons`), an address of the app that shows the samples. */
|
|
49
|
+
readonly sample?: string;
|
|
50
|
+
/** kind `widget`: the widget of this module (`admin-header`). */
|
|
51
|
+
readonly widget?: string;
|
|
52
|
+
}
|
|
53
|
+
export interface ModuleParts {
|
|
54
|
+
readonly parts: readonly ModulePart[];
|
|
55
|
+
}
|
|
56
|
+
export declare const PARTS_LIMITS: Readonly<{
|
|
57
|
+
/** Bytes of the parts file. */
|
|
58
|
+
fileBytes: 2000000;
|
|
59
|
+
parts: 512;
|
|
60
|
+
/** Props, slots, events or variants of one part. */
|
|
61
|
+
members: 128;
|
|
62
|
+
examples: 16;
|
|
63
|
+
/** Characters of one text (a description, a type, a default). */
|
|
64
|
+
textChars: 2000;
|
|
65
|
+
/** Characters of one example. */
|
|
66
|
+
exampleChars: 8000;
|
|
67
|
+
locales: 32;
|
|
68
|
+
}>;
|
|
69
|
+
/** Thrown for a parts file that breaks a rule; the caller turns it into INVALID_CONTRACT. */
|
|
70
|
+
export declare class PartsIssue extends Error {
|
|
71
|
+
}
|
|
72
|
+
/** Checks parsed parts (`{ parts: [...] }`) against the module's widget names. */
|
|
73
|
+
export declare function checkParts(value: unknown, widgets: Iterable<string>, where?: string): ModuleParts;
|
|
74
|
+
/** Reads and checks a module's parts file (UTF-8 JSON of at most PARTS_LIMITS.fileBytes). */
|
|
75
|
+
export declare function readParts(file: URL, widgets: Iterable<string>): Promise<ModuleParts>;
|
package/dist/parts.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// The UI parts a module offers (D-0203): the Vue components, directives, CSS classes and widgets
|
|
2
|
+
// that page authors, an editor and an AI place on screens — each with its name, a line of what it
|
|
3
|
+
// is and when to use it, its props, slots and events, example markup and the address of its live
|
|
4
|
+
// sample. A module points at one JSON file (`parts: new URL('./parts.json', import.meta.url)`),
|
|
5
|
+
// usually generated from its .vue files so the props are never written twice; `dokebi describe
|
|
6
|
+
// --json` reads and checks it and gives it as `app.modules[].parts`, and the MCP tools of an editor
|
|
7
|
+
// list and fetch parts from there. A part of kind `widget` names a widget of the same module.
|
|
8
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { types } from 'node:util';
|
|
11
|
+
export const PART_KINDS = ['component', 'directive', 'class', 'widget'];
|
|
12
|
+
export const PARTS_LIMITS = Object.freeze({
|
|
13
|
+
/** Bytes of the parts file. */
|
|
14
|
+
fileBytes: 2_000_000,
|
|
15
|
+
parts: 512,
|
|
16
|
+
/** Props, slots, events or variants of one part. */
|
|
17
|
+
members: 128,
|
|
18
|
+
examples: 16,
|
|
19
|
+
/** Characters of one text (a description, a type, a default). */
|
|
20
|
+
textChars: 2000,
|
|
21
|
+
/** Characters of one example. */
|
|
22
|
+
exampleChars: 8000,
|
|
23
|
+
locales: 32,
|
|
24
|
+
});
|
|
25
|
+
/** Thrown for a parts file that breaks a rule; the caller turns it into INVALID_CONTRACT. */
|
|
26
|
+
export class PartsIssue extends Error {
|
|
27
|
+
}
|
|
28
|
+
const NAME = /^(?:[A-Z][A-Za-z0-9]{0,63}|v-[a-z][a-z0-9-]{0,62}|\.[a-z][a-z0-9-]{0,62}|[a-z][a-z0-9-]{0,63})$/;
|
|
29
|
+
const MEMBER = /^[A-Za-z_$#@:][A-Za-z0-9_$.:#@-]{0,127}$/;
|
|
30
|
+
const LOCALE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
|
|
31
|
+
const SAMPLE = /^\/[A-Za-z0-9._~/-]{0,255}(?:#[A-Za-z0-9._-]{1,64})?$/;
|
|
32
|
+
const FILE = /^(?!\/)(?!.*\.\.)[A-Za-z0-9._/-]{1,255}$/;
|
|
33
|
+
const plain = (value) => value !== null &&
|
|
34
|
+
typeof value === 'object' &&
|
|
35
|
+
!Array.isArray(value) &&
|
|
36
|
+
!types.isProxy(value) &&
|
|
37
|
+
[Object.prototype, null].includes(Object.getPrototypeOf(value));
|
|
38
|
+
function only(input, keys, where) {
|
|
39
|
+
const extra = Object.keys(input).find((name) => !keys.includes(name));
|
|
40
|
+
if (extra)
|
|
41
|
+
throw new PartsIssue(`${where} has an unknown field: ${extra}`);
|
|
42
|
+
}
|
|
43
|
+
function str(value, where, limit = PARTS_LIMITS.textChars) {
|
|
44
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > limit)
|
|
45
|
+
throw new PartsIssue(`${where} must be a text of 1 to ${limit} characters`);
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
function text(value, where) {
|
|
49
|
+
if (typeof value === 'string')
|
|
50
|
+
return str(value, where);
|
|
51
|
+
if (plain(value)) {
|
|
52
|
+
const entries = Object.entries(value);
|
|
53
|
+
if (entries.length > 0 &&
|
|
54
|
+
entries.length <= PARTS_LIMITS.locales &&
|
|
55
|
+
entries.every(([locale, item]) => LOCALE.test(locale) &&
|
|
56
|
+
typeof item === 'string' &&
|
|
57
|
+
item.length > 0 &&
|
|
58
|
+
item.length <= PARTS_LIMITS.textChars))
|
|
59
|
+
return Object.freeze(Object.fromEntries(entries));
|
|
60
|
+
}
|
|
61
|
+
throw new PartsIssue(`${where} must be a text or { <locale>: text }`);
|
|
62
|
+
}
|
|
63
|
+
const optionalText = (input, key, where) => input[key] === undefined ? {} : { [key]: text(input[key], `${where}.${key}`) };
|
|
64
|
+
function list(value, where, limit, item) {
|
|
65
|
+
if (value === undefined)
|
|
66
|
+
return undefined;
|
|
67
|
+
if (!Array.isArray(value) || types.isProxy(value))
|
|
68
|
+
throw new PartsIssue(`${where} must be an array`);
|
|
69
|
+
if (value.length > limit)
|
|
70
|
+
throw new PartsIssue(`${where} has more than ${limit} entries`);
|
|
71
|
+
const names = new Set();
|
|
72
|
+
return Object.freeze(value.map((entry, index) => {
|
|
73
|
+
const at = `${where}[${index}]`;
|
|
74
|
+
if (!plain(entry))
|
|
75
|
+
throw new PartsIssue(`${at} must be an object`);
|
|
76
|
+
if (typeof entry.name !== 'string' || !MEMBER.test(entry.name))
|
|
77
|
+
throw new PartsIssue(`${at}.name must be a name`);
|
|
78
|
+
if (names.has(entry.name))
|
|
79
|
+
throw new PartsIssue(`${where} has ${entry.name} twice`);
|
|
80
|
+
names.add(entry.name);
|
|
81
|
+
return item(entry, at);
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
function readPart(input, at, widgets) {
|
|
85
|
+
only(input, [
|
|
86
|
+
'name',
|
|
87
|
+
'kind',
|
|
88
|
+
'title',
|
|
89
|
+
'description',
|
|
90
|
+
'use',
|
|
91
|
+
'file',
|
|
92
|
+
'props',
|
|
93
|
+
'slots',
|
|
94
|
+
'events',
|
|
95
|
+
'variants',
|
|
96
|
+
'examples',
|
|
97
|
+
'sample',
|
|
98
|
+
'widget',
|
|
99
|
+
], at);
|
|
100
|
+
if (typeof input.name !== 'string' || !NAME.test(input.name))
|
|
101
|
+
throw new PartsIssue(`${at}.name must be a component (UiButton), directive (v-name), class (.name) or widget name`);
|
|
102
|
+
if (!PART_KINDS.includes(input.kind))
|
|
103
|
+
throw new PartsIssue(`${at}.kind must be one of ${PART_KINDS.join(', ')}`);
|
|
104
|
+
const kind = input.kind;
|
|
105
|
+
if (input.file !== undefined && (typeof input.file !== 'string' || !FILE.test(input.file)))
|
|
106
|
+
throw new PartsIssue(`${at}.file must be a path inside the module folder`);
|
|
107
|
+
if (input.sample !== undefined &&
|
|
108
|
+
(typeof input.sample !== 'string' || !SAMPLE.test(input.sample)))
|
|
109
|
+
throw new PartsIssue(`${at}.sample must be an address of the app: /path or /path#part`);
|
|
110
|
+
if (kind === 'widget') {
|
|
111
|
+
if (typeof input.widget !== 'string' || !widgets.has(input.widget))
|
|
112
|
+
throw new PartsIssue(`${at}.widget must name a widget of the module`);
|
|
113
|
+
}
|
|
114
|
+
else if (input.widget !== undefined)
|
|
115
|
+
throw new PartsIssue(`${at}.widget is for kind widget only`);
|
|
116
|
+
const props = list(input.props, `${at}.props`, PARTS_LIMITS.members, (prop, where) => {
|
|
117
|
+
only(prop, ['name', 'type', 'required', 'default', 'description'], where);
|
|
118
|
+
if (typeof prop.required !== 'boolean')
|
|
119
|
+
throw new PartsIssue(`${where}.required must be true or false`);
|
|
120
|
+
return Object.freeze({
|
|
121
|
+
name: prop.name,
|
|
122
|
+
type: str(prop.type, `${where}.type`),
|
|
123
|
+
required: prop.required,
|
|
124
|
+
...(prop.default === undefined ? {} : { default: str(prop.default, `${where}.default`) }),
|
|
125
|
+
...optionalText(prop, 'description', where),
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
const slots = list(input.slots, `${at}.slots`, PARTS_LIMITS.members, (slot, where) => {
|
|
129
|
+
only(slot, ['name', 'props', 'description'], where);
|
|
130
|
+
return Object.freeze({
|
|
131
|
+
name: slot.name,
|
|
132
|
+
...(slot.props === undefined ? {} : { props: str(slot.props, `${where}.props`) }),
|
|
133
|
+
...optionalText(slot, 'description', where),
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
const events = list(input.events, `${at}.events`, PARTS_LIMITS.members, (event, where) => {
|
|
137
|
+
only(event, ['name', 'payload', 'description'], where);
|
|
138
|
+
return Object.freeze({
|
|
139
|
+
name: event.name,
|
|
140
|
+
...(event.payload === undefined ? {} : { payload: str(event.payload, `${where}.payload`) }),
|
|
141
|
+
...optionalText(event, 'description', where),
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
const variants = list(input.variants, `${at}.variants`, PARTS_LIMITS.members, (variant, where) => {
|
|
145
|
+
only(variant, ['name', 'description'], where);
|
|
146
|
+
return Object.freeze({
|
|
147
|
+
name: variant.name,
|
|
148
|
+
...optionalText(variant, 'description', where),
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
let examples;
|
|
152
|
+
if (input.examples !== undefined) {
|
|
153
|
+
if (!Array.isArray(input.examples) || input.examples.length > PARTS_LIMITS.examples)
|
|
154
|
+
throw new PartsIssue(`${at}.examples must be an array of at most ${PARTS_LIMITS.examples} texts`);
|
|
155
|
+
examples = Object.freeze(input.examples.map((example, index) => str(example, `${at}.examples[${index}]`, PARTS_LIMITS.exampleChars)));
|
|
156
|
+
}
|
|
157
|
+
return Object.freeze({
|
|
158
|
+
name: input.name,
|
|
159
|
+
kind,
|
|
160
|
+
title: text(input.title, `${at}.title`),
|
|
161
|
+
...optionalText(input, 'description', at),
|
|
162
|
+
...optionalText(input, 'use', at),
|
|
163
|
+
...(input.file === undefined ? {} : { file: input.file }),
|
|
164
|
+
...(props ? { props } : {}),
|
|
165
|
+
...(slots ? { slots } : {}),
|
|
166
|
+
...(events ? { events } : {}),
|
|
167
|
+
...(variants ? { variants } : {}),
|
|
168
|
+
...(examples ? { examples } : {}),
|
|
169
|
+
...(input.sample === undefined ? {} : { sample: input.sample }),
|
|
170
|
+
...(input.widget === undefined ? {} : { widget: input.widget }),
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/** Checks parsed parts (`{ parts: [...] }`) against the module's widget names. */
|
|
174
|
+
export function checkParts(value, widgets, where = 'parts') {
|
|
175
|
+
if (!plain(value))
|
|
176
|
+
throw new PartsIssue(`${where} must be an object { parts: [...] }`);
|
|
177
|
+
only(value, ['$schema', 'parts'], where);
|
|
178
|
+
if (!Array.isArray(value.parts) || types.isProxy(value.parts))
|
|
179
|
+
throw new PartsIssue(`${where}.parts must be an array`);
|
|
180
|
+
if (value.parts.length > PARTS_LIMITS.parts)
|
|
181
|
+
throw new PartsIssue(`${where}.parts has more than ${PARTS_LIMITS.parts} parts`);
|
|
182
|
+
const known = new Set(widgets);
|
|
183
|
+
const seen = new Set();
|
|
184
|
+
const parts = value.parts.map((entry, index) => {
|
|
185
|
+
const at = `${where}.parts[${index}]`;
|
|
186
|
+
if (!plain(entry))
|
|
187
|
+
throw new PartsIssue(`${at} must be an object`);
|
|
188
|
+
const part = readPart(entry, at, known);
|
|
189
|
+
const key = `${part.kind}:${part.name}`;
|
|
190
|
+
if (seen.has(key))
|
|
191
|
+
throw new PartsIssue(`${where}.parts has the ${part.kind} ${part.name} twice`);
|
|
192
|
+
seen.add(key);
|
|
193
|
+
return part;
|
|
194
|
+
});
|
|
195
|
+
return Object.freeze({ parts: Object.freeze(parts) });
|
|
196
|
+
}
|
|
197
|
+
/** Reads and checks a module's parts file (UTF-8 JSON of at most PARTS_LIMITS.fileBytes). */
|
|
198
|
+
export async function readParts(file, widgets) {
|
|
199
|
+
const path = fileURLToPath(file);
|
|
200
|
+
let info;
|
|
201
|
+
try {
|
|
202
|
+
info = await stat(path);
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
// A parts file the contract names but the module lacks is a broken contract (D-0203 review).
|
|
206
|
+
if (error.code === 'ENOENT')
|
|
207
|
+
throw new PartsIssue(`${path} does not exist`, { cause: error });
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
if (!info.isFile())
|
|
211
|
+
throw new PartsIssue(`${path} is not a file`);
|
|
212
|
+
if (info.size > PARTS_LIMITS.fileBytes)
|
|
213
|
+
throw new PartsIssue(`${path} is larger than ${PARTS_LIMITS.fileBytes} bytes`);
|
|
214
|
+
let source;
|
|
215
|
+
try {
|
|
216
|
+
source = new TextDecoder('utf-8', { fatal: true }).decode(await readFile(path));
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
if (error instanceof TypeError)
|
|
220
|
+
throw new PartsIssue(`${path} is not UTF-8 text`, { cause: error });
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
let value;
|
|
224
|
+
try {
|
|
225
|
+
value = JSON.parse(source);
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
throw new PartsIssue(`${path} is not JSON: ${error.message}`, { cause: error });
|
|
229
|
+
}
|
|
230
|
+
return checkParts(value, widgets, path);
|
|
231
|
+
}
|