@dokebi/module 0.1.3 → 0.4.1

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 CHANGED
@@ -1,88 +1,143 @@
1
- # AI 작업 안내 — @dokebi/module 0.1.3
1
+ # AI guide — @dokebi/module
2
2
 
3
- 모듈은 **기능 하나의 업무 단위**다(D-0032). 컨트롤러·모델·뷰·라우트·소켓을 한 폴더에 담고, 앱이 접두사로 붙인다. 웹이 없는 업무(Job handler, 이벤트 구독, 공통 API)도 모듈로 만든다. Node >=24.0.0, core ^0.2.0. 세부는 [README](README.md)다.
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
- ## 1. 만들기
5
+ ## 1. Creating modules
6
6
 
7
7
  ```sh
8
- npx dokebi add @dokebi/module # src/shared/modules/ 준비
9
- npx dokebi module add board # 화면 있는 모듈(views/default 포함)
10
- npx dokebi module add stats --no-views # 라우트가 JSON을 돌려주는 모듈
11
- npx dokebi module remove board # 등록만 지우고 폴더는 남김
8
+ npx dokebi add @dokebi/module # prepares src/shared/modules/
9
+ npx dokebi module add board # a module with pages (includes views/default)
10
+ npx dokebi module add stats --no-views # a module whose routes return JSON
11
+ npx dokebi module remove board # removes only the registration; the folder stays
12
12
  npx dokebi module list
13
13
  ```
14
14
 
15
- 모듈 폴더를 손으로 만들면 등록되지 않는다. 생성 등록 코드가 각 모듈의 default export를 묶음 플러그인 entry로 넘긴다.
15
+ > `npx dokebi` is the @dokebi/cli installed in the project (`dokebi init` adds it to devDependencies). The npm package `dokebi` is not this CLI, so never use `npx -y dokebi`. Without an installed CLI use `npx -y @dokebi/cli …`.
16
+
17
+ A hand-made module folder is not registered. The generated registration code passes each module's default export to the group plugin's entry.
16
18
 
17
19
  ```
18
- src/shared/modules/<모듈>/
20
+ src/shared/modules/<module>/
19
21
  module.ts export default defineModule({ ... })
20
- routes.ts 앱에 붙을 때 등록되는 라우트
21
- controllers/ models/ views/default/(화면 모듈) sockets/(필요할 때)
22
+ routes.ts routes registered when an app mounts the module
23
+ controllers/ services/ models/ views/default/ (modules with pages) sockets/ (when needed)
22
24
  ```
23
25
 
24
- 컨트롤러·모델·뷰를 층별 폴더(`src/shared/controllers` 등)로 흩지 않는다.
26
+ Do not scatter controllers, models and views into layer folders (`src/shared/controllers` and so on).
25
27
 
26
28
  ## 2. defineModule
27
29
 
28
- ```ts
30
+ ```ts snippet
29
31
  import { defineModule } from '@dokebi/module';
30
32
  import { dependency as db } from '@dokebi/db';
33
+ import { mcpTools } from '@dokebi/mcp';
31
34
  import { postsController } from './controllers/posts.ts';
32
35
 
33
36
  export default defineModule({
34
- name: 'board', // 폴더 이름. 플러그인 id는 dokebi-module.board
35
- requires: [db], // 인스턴스·descriptor·다른 모듈
37
+ name: 'board', // the folder name; the plugin id is dokebi-module.board
38
+ requires: [db], // instances, descriptors, other modules
36
39
  controllers: [postsController],
37
- views: new URL('./views/', import.meta.url), // default/ 필수(지정하면 template-ejs 의존 추가)
38
- routes(route, module) { // 붙인 앱마다 그 앱의 도메인·접두사로 등록
40
+ contributes: [mcpTools], // points of plugins this module contributes to (§3a)
41
+ views: new URL('./views/', import.meta.url), // default/ is required (adds a template-ejs dependency)
42
+ routes(route, module) { // registered for every app that mounts it, on that app's domains and prefix
39
43
  route.get('/', async (request, reply, page) =>
40
44
  page.view.reply(reply, 'index', { posts: await module.controller(postsController).list(), base: page.base }),
41
45
  );
42
46
  route.post('/', async (request, reply, page) => { /* ... */ });
43
47
  },
44
- sockets: (module) => [boardSocket(module)], // defineSocket 결과. tenant는 <네임스페이스>:<tenant>
45
- events: (module) => [boardStream(module)], // (0.1.3) @dokebi/sse 라우트(SseRoute). 소켓과 같은 규칙
46
- setup(module) { return { count: () => module.controller(postsController).count() }; }, // 다른 쪽이 받는 API
48
+ sockets: (module) => [boardSocket(module)], // defineSocket results; tenant is <namespace>:<tenant>
49
+ events: (module) => [boardStream(module)], // (0.1.3) @dokebi/sse routes (SseRoute); same rules as sockets
50
+ setup(module) { return { count: () => module.controller(postsController).count() }; }, // the API others receive
47
51
  start(module) {}, drain(module) {},
48
52
  });
49
53
  ```
50
54
 
51
- - `module`(ModuleContext) = PluginContext + `module`(이름) + `controller(token)`. `requires`에 선언한 것만 `get`·`getDependency`로 읽는다.
52
- - `page`(ModulePage) = `{ app: { name, template, domain }, module, base, view, inertia }`. 링크는 `page.base`를 붙여 만든다(앱마다 접두사가 다를 수 있다).
53
- - `version`은 정확한 semver(기본 `'0.1.0'`). 같은 이름의 requires는 거부한다.
54
- - 컨트롤러 없이 `module.controller()`를 부르면 `declares no controllers` 오류.
55
+ - `module` (ModuleContext) = PluginContext + `module` (the name) + `controller(token)`. Only what `requires` declares can be read with `get` or `getDependency`. When a controller factory passes a freshly built descriptor object, the declared descriptor with that name is found.
56
+ - `page` (ModulePage) = `{ app: { name, template, domain }, module, base, view, inertia }`. Build links with `page.base` (each app may use a different prefix).
57
+ - `version` is an exact semver (default `'0.1.0'`). Requires with duplicate names are refused.
58
+ - `views`: adds a template-ejs dependency automatically; the start fails without `views/default/`. Template names get the prefix `module.<name>`.
59
+ - `controllers`: uses @dokebi/controller (optional peer). Calling `module.controller()` without controllers is `NO_CONTROLLERS` (`declares no controllers`).
60
+ - `module.runtime` is core's runtime role (`solo`, `primary`, `worker`; D-0063 §4). Do not read `node:cluster` yourself.
61
+ - Route options are `WebRoute` options without `handler` and `constraints` (`ModuleRouteOptions`, so `seal` works).
62
+ - `contributes`: the points of other plugins this module contributes to (§3a). Without it `module.contribute` is `UNDECLARED_POINT`.
63
+
64
+ ## 3. Mounting on apps and shared APIs
65
+
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`).
67
+ - The hub tenant of sockets and SSE routes (`events`, 0.1.3) follows the mounting app's rules ([D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md)): `<namespace>:<authenticated tenant>`, and a `namespace` returned by `authenticate` must be in the mounting app's `realtime.namespaces` (otherwise 401). The module context has no `realtime` handle. Publish with @dokebi/sse `publish({ tenantPrefix: '<namespace>:' }, …)` or the app's `app.realtime(ns).publish`. `events` are mounted by @dokebi/app 0.2.0 or later (0.1.x apps do not read the field, so no stream is created).
68
+ - APIs that must answer on every domain (such as `/api/*`) are not `routes`; register them in `setup` directly with `@dokebi/router` (`mount`) or web.
69
+ - For another module or plugin to use this module's API, put this module into its `requires` and `get(module)`; it receives what `setup` returned.
70
+
71
+ ## 3a. Contributing to plugin points (MCP tools and others)
72
+
73
+ A module offers values to a plugin that collects a point ([D-0130](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0130-module-contributions.md); the points are core's, D-0063): MCP tools, prompts and resources of @dokebi/mcp (`mcpTools`, `mcpPrompts`, `mcpResources`), mail template folders, error translators. It is the same mechanism for every point; nothing is special to MCP.
74
+
75
+ ```ts snippet
76
+ import { dependency as db } from '@dokebi/db';
77
+ import { mcpTools } from '@dokebi/mcp';
78
+ import { defineModule } from '@dokebi/module';
79
+ import { DocumentService } from './services/documents.ts';
80
+ import { ListDocuments } from './tools/list-documents.ts';
81
+
82
+ export default defineModule({
83
+ name: 'workspace',
84
+ requires: [db],
85
+ contributes: [mcpTools], // declared when the module is defined
86
+ setup(module) {
87
+ const documents = new DocumentService(module.getDependency(db));
88
+ module.contribute(mcpTools, new ListDocuments(documents)); // the module's own service
89
+ return { documents }; // the module API: the same object
90
+ },
91
+ });
92
+ ```
93
+
94
+ - **Declared, not dynamic**: `contributes` becomes the module plugin's `metadata.contributes` when `defineModule` runs, before the app registers anything, so core checks every `module.contribute` against it and `npx dokebi describe` lists it (each plugin's `contributes` and `collects`, and a summary line per module point with its collector). Points made by `definePoint`, each once, at most 64 (`INVALID_CONTRIBUTION`).
95
+ - **Order**: core's rule for every contributor: the module sets up (and builds its services) before every plugin that collects the point, and drains after it; registration order does not matter. Contribute in `setup` only (in `start`, `drain` or a route it is core's `CONTRIBUTIONS_CLOSED`).
96
+ - **The module boundary holds**: the contributed objects get the services the module built; nothing builds them again. Another module that contributes tools for this one lists it in `requires` and reads `module.get(workspace).documents`. Never write a separate `definePlugin` that builds the services a second time, and never register an app plugin by hand in `src/main.ts` or `src/infra/runtime/application.ts` for this: `npx dokebi describe` and the tests build the app from the generated registration and do not see it, and doctor and check do not read it.
97
+ - **A module never collects**: `module.collect` is `UNDECLARED_POINT` (collecting is a plugin's role).
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`).
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).
100
+
101
+ ## 4. View lookup order (how an app changes a module page)
102
+
103
+ 1. `<app>/<template>/<module>/…`
104
+ 2. `<app>/default/<module>/…`
105
+ 3. the module's `<template>/…`
106
+ 4. the module's `default/…`
107
+ 5. the app's views (layouts and partials)
108
+ 6. shared `src/shared/views`
55
109
 
56
- ## 3. 앱에 붙이기와 공통 API
110
+ To change a module page, an app never edits the module file; it puts a file with the same name into `src/apps/<app>/views/<template>/<module>/`. When an Inertia app mounts the module, the module produces props with `page.inertia.render(request, reply, 'Component', props)` and the Vue pages live in the app's `views/<template>/Pages/`.
57
111
 
58
- - 앱: `defineApp({ modules: { '/board': board } })`. 라우트·소켓·SSE 라우트는 **그 앱의 도메인과 접두사에서만** 응답한다. 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다.
59
- - 소켓·SSE 라우트(`events`, 0.1.3)의 허브 tenant는 붙인 앱의 규칙을 따른다([D-0061](../../docs/decisions/D-0061-realtime-namespaces.md)): `<네임스페이스>:<인증 tenant>`이고, `authenticate`가 `namespace`를 돌려주면 붙인 앱의 `realtime.namespaces` 안이어야 한다(아니면 401). 모듈 문맥에는 `realtime` 핸들이 없다. 발행은 @dokebi/sse `publish({ tenantPrefix: '<네임스페이스>:' }, …)`나 앱의 `app.realtime(ns).publish`로 한다. `events`는 @dokebi/app 0.2.0 이상이 붙인다(0.1.x 앱은 이 필드를 읽지 않아 스트림이 생기지 않는다).
60
- - 모든 도메인에서 응답해야 하는 API(예: `/api/*`)는 `routes`가 아니라 `setup`에서 `@dokebi/router`(`mount`)나 web으로 직접 등록한다.
61
- - 다른 모듈·플러그인이 이 모듈의 API를 쓰려면 `requires`에 이 모듈을 넣고 `get(모듈)` 하면 `setup`의 반환값을 받는다.
112
+ ## 5. Group plugin and lifecycle
62
113
 
63
- ## 4. 화면 찾는 순서(앱이 모듈 화면을 바꾸는 법)
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`.
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.
116
+ - A module instance is used by one Application only. There is no automatic discovery, dynamic import or hot reload while running.
117
+ - Options of the group plugin are an empty object.
118
+ - Debug logs (D-0047): `Modules registered` (the group), `Module set up` (requires, number of controllers, contributes, views prefix, whether routes, sockets and events exist, ms), `Module start finished`, `Module drain finished`. A missing or unreadable `views/default/` fails the start, with the original file error kept as `cause`.
64
119
 
65
- 1. `<앱>/<템플릿>/<모듈>/…`
66
- 2. `<앱>/default/<모듈>/…`
67
- 3. 모듈의 `<템플릿>/…`
68
- 4. 모듈의 `default/…`
69
- 5. 앱 views(레이아웃·부분 템플릿)
70
- 6. 공통 `src/shared/views`
120
+ ## 6. Errors
71
121
 
72
- 앱이 모듈 화면을 바꿀 때는 모듈 파일을 고치지 말고 `src/apps/<앱>/views/<템플릿>/<모듈>/`에 같은 이름 파일을 둔다. Inertia 앱이 붙이면 모듈은 `page.inertia.render(request, reply, '컴포넌트', props)`로 props를 내고, Vue 페이지는 앱의 `views/<템플릿>/Pages/`에 둔다.
122
+ <!-- docs-check: complete-error-codes ModuleErrorCode -->
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).
73
124
 
74
- ## 5. 묶음 플러그인과 수명주기
125
+ ## 7. Cautions
75
126
 
76
- - `createPlugin({ app, entry: { modules } })`: 여러 모듈을 의존성 그래프로 묶는다. API는 `{ names }`. `defineModule`이 만든 것만 받고 중복은 `INVALID_PLUGIN_INPUT`.
77
- - 훅: setup(라우트 등록·API 반환) → start → drain(새 유입 차단, 진행 업무 대기) → defer 정리. drain은 의존 역순(이 모듈에 의존하는 모듈이 먼저), 무관한 모듈은 동시에.
78
- - 모듈 인스턴스는 Application 하나에만 쓴다. 실행 중 자동 검색·동적 import·hot reload는 없다.
79
- - debug 로그(D-0047): `Modules registered`(묶음)·`Module set up`(requires·컨트롤러 수·views 접두사·routes·sockets·events 유무·ms)·`Module start finished`·`Module drain finished`. `views/default/`가 없거나 읽을 수 없으면 시작 실패이고 원래 파일 오류는 `cause`에 남는다.
127
+ - A module does not depend on apps (never branch on an app name). Handle per-app differences with `page.app` and the app's view overrides.
128
+ - `moduleMount` and `MODULE_MOUNT` are the internal link @dokebi/app uses. App code does not use them.
129
+ - Socket and SSE route types (`ModuleSocketRoute`, `ModuleEventRoute`) are defined by shape only, so projects that do not use them need neither @dokebi/websocket nor @dokebi/sse. When used, add that package (otherwise the app start fails: `has sockets; add @dokebi/websocket`, `has event streams; add @dokebi/sse`). Both take `config: { id }`, the route id (D-0140), like the module's routes: it must be unique among the routes, sockets and streams of each app that mounts the module (`DUPLICATE_ROUTE_ID` at start otherwise).
130
+ - Do not treat the end of a response or a dropped connection as the work being done. Work detached from the request is awaited in the module's `drain`.
80
131
 
81
- ## 6. 주의 사항
132
+ References: `examples/26-scaffold` (repeated generation, mounting and overriding), `examples/25-playground` (eight feature modules; the sse module mounts `/api/sse/events` on every app through `events`), `examples/22-web/main.ts` (assembled in code), D-0022, D-0032.
82
133
 
83
- - 모듈은 앱에 의존하지 않는다(앱 이름으로 분기하지 않는다). 앱별 차이는 `page.app`과 앱의 화면 덮어쓰기로 처리한다.
84
- - `moduleMount`·`MODULE_MOUNT`는 @dokebi/app이 쓰는 내부 연결이다. 앱 코드에서 쓰지 않는다.
85
- - 소켓·SSE 라우트 타입은 모양으로만 정해져 있어 쓰지 않는 프로젝트는 @dokebi/websocket·@dokebi/sse가 필요 없다. 쓰면 그 패키지를 add한다(없으면 앱 시작 실패: `has sockets; add @dokebi/websocket`, `has event streams; add @dokebi/sse`).
86
- - 응답 종료·연결 끊김을 업무 완료로 보지 않는다. 요청 밖으로 떼어 낸 작업은 모듈 `drain`에서 기다린다.
134
+ ## Service composition
87
135
 
88
- 근거: `examples/26-scaffold`(생성·붙이기·덮어쓰기 반복), `examples/25-playground`(기능 모듈 여덟 개, sse 모듈이 `events`로 앱마다 `/api/sse/events`를 붙임), `examples/22-web/main.ts`(코드 조합), D-0022·D-0032.
136
+ Use Controller -> Service -> Model for application data. Controllers handle HTTP input/output;
137
+ services provide data and coordinate workflows through models; models own persistence.
138
+ Generated app/module starters include this chain. Keep services free of request/reply and
139
+ rendering objects, and reuse them from jobs. Compose dependencies once during setup.
140
+ App-specific services belong in `src/apps/<app>/services`, cross-app services in
141
+ `src/shared/services`, and module services in `src/shared/modules/<module>/services`.
142
+ Shared services must not import app-specific code. These are ordinary application classes,
143
+ not a new framework plugin or service registry. Existing projects are not moved automatically.
package/README.md CHANGED
@@ -1,76 +1,91 @@
1
- # @dokebi/module 0.1.2
1
+ # @dokebi/module 0.4.1
2
2
 
3
- Node >=24.0.0, core ^0.2.0의 선택 패키지다(npm 공개). 모듈은 **기능 하나의 MVC 업무 단위**다([D-0022](../../docs/decisions/D-0022-plugin-boundaries-and-db.md), [D-0032](../../docs/decisions/D-0032-feature-modules.md)). 컨트롤러·모델·뷰·라우트·소켓을 한 폴더에 담고, 앱이 접두사로 붙인다. HTTP 전용 묶음이 아니어서 웹 없는 업무(Job 처리, 이벤트 구독)도 모듈로 만든다.
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
 
5
- ## 폴더
5
+ ## Folder
6
6
 
7
7
  ```
8
- src/shared/modules/<모듈>/
8
+ src/shared/modules/<module>/
9
9
  module.ts export default defineModule({ ... })
10
- routes.ts 앱에 붙을 때 등록되는 라우트
11
- controllers/ 이 모듈의 컨트롤러(모듈 setup에서 한 번 만든다)
12
- models/ 이 모듈의 모델(일반 코드)
13
- views/default/ (화면이 있는 모듈만) EJS 화면. 다른 템플릿은 바꿀 파일만
14
- sockets/ (필요할 때) defineSocket
10
+ routes.ts routes registered when an app mounts the module
11
+ controllers/ this module's controllers (created once in the module's setup)
12
+ models/ this module's models (plain code)
13
+ views/default/ (modules with pages only) EJS views; other templates hold only changed files
14
+ sockets/ (when needed) defineSocket
15
15
  ```
16
16
 
17
- `dokebi module add <이름>`이 골격을 만들고 생성 등록 코드에 넣는다. 화면 없는 모듈은 `--no-views`로 만든다. 이때 라우트는 JSON을 돌려준다. `dokebi module remove <이름>`은 등록만 지우고 폴더를 남긴다. `dokebi module list`는 목록을 보여 준다. `dokebi add @dokebi/module`은 `src/shared/modules/` 폴더만 만든다.
17
+ `dokebi module add <name>` creates the skeleton and adds it to the generated registration code. Create a module without pages with `--no-views`; its routes then return JSON. `dokebi module remove <name>` removes only the registration and leaves the folder. `dokebi module list` shows the list. `dokebi add @dokebi/module` only creates the `src/shared/modules/` folder.
18
18
 
19
19
  ## defineModule
20
20
 
21
- ```ts
21
+ ```ts snippet
22
22
  export default defineModule({
23
- name: 'board', // 폴더 이름. ID는 dokebi-module.board
24
- requires: [db, other], // 플러그인 인스턴스·descriptor·다른 모듈
25
- controllers: [postsController], // 모듈 문맥으로 한 번 만든다
26
- views: new URL('./views/', import.meta.url), // default/ 필수, 템플릿 이름 접두사 module.board
27
- routes(route, module) { // 앱마다(붙을 때) 등록. page = { app, module, base, view, inertia }
23
+ name: 'board', // the folder name; the ID is dokebi-module.board
24
+ requires: [db, other], // plugin instances, descriptors, other modules
25
+ controllers: [postsController], // created once with the module context
26
+ contributes: [mcpTools], // points of plugins it contributes to; module.contribute in setup
27
+ views: new URL('./views/', import.meta.url), // default/ required; template names get the prefix module.board
28
+ routes(route, module) { // registered per app (when mounted). page = { app, module, base, view, inertia }
28
29
  route.get('/', (request, reply, page) =>
29
30
  page.view.reply(reply, 'index', module.controller(postsController).list(page)));
30
31
  },
31
- sockets: (module) => [boardSocket(module)], // 앱마다 접두사 아래 등록, tenant는 <네임스페이스>:<tenant>
32
- events: (module) => [boardStream(module)], // (0.1.3) SSE 라우트(@dokebi/sse). 소켓과 같은 규칙
33
- setup(module) { return api; }, // 선택. 반환값이 이 모듈을 requires한 쪽이 받는 API
32
+ sockets: (module) => [boardSocket(module)], // registered per app under the prefix; tenant is <namespace>:<tenant>
33
+ events: (module) => [boardStream(module)], // (0.1.3) SSE routes (@dokebi/sse); same rules as sockets
34
+ setup(module) { return api; }, // optional; the return value is the API of whoever requires this module
34
35
  start(module) {}, drain(module) {},
35
36
  });
36
37
  ```
37
38
 
38
- - **`module`(ModuleContext):** PluginContext에 `module`(이름)과 `controller(token)`을 더한 것이다.
39
- - 선언한 `requires`만 읽는다.
40
- - 컨트롤러 factory가 descriptor 객체를 새로 만들어 넘겨도 이름으로 선언한 descriptor를 찾아 준다.
41
- - **`version`:** 정확한 semver이며 기본값은 `'0.1.0'`이다. 같은 이름의 requires는 거부한다.
42
- - **`views`:** 지정하면 template-ejs 의존이 자동으로 더해진다. `views/default/`가 없으면 시작이 실패한다.
43
- - **`controllers`:** 지정하면 @dokebi/controller를 쓴다(선택 peer). 컨트롤러 없이 `module.controller()`를 부르면 `declares no controllers` 오류가 난다.
44
- - **`setup`:** 선택이다. 기존 `setup(context)` 형태도 그대로 동작한다.
45
- - **공통 API:** 모든 도메인에서 응답해야 하는 API는 setup에서 router·web으로 직접 등록한다. 예: 플레이그라운드의 `/api/*`.
46
- - **앱에 붙이기:** `defineApp({ modules: { '/board': board } })`. 라우트·소켓이 그 앱의 도메인과 접두사에서만 응답한다. 붙인 모듈은 앱의 `requires`에 넣지 않아도 `app.get(board)`로 API를 읽을 수 있다. 자세한 내용은 [@dokebi/app](../dokebi-app/README.md)에 있다.
47
- - **화면 찾는 순서:**
48
- 1. `<앱>/<템플릿>/<모듈>/…`
49
- 2. `<앱>/default/<모듈>/…`
50
- 3. 모듈의 `<템플릿>/…`
51
- 4. 모듈의 `default/…`
52
- 5. 앱 views(레이아웃·부분 템플릿)
53
- 6. 공통 `src/shared/views`
54
-
55
- 그래서 앱은 모듈 화면의 파일 하나만 바꿀 수 있다. 예: `src/apps/<앱>/views/christmas/<모듈>/heading.ejs`.
56
- - **Inertia 앱:** 모듈이 `page.inertia.render(request, reply, '컴포넌트', props)`로 props를 낸다. Vue 페이지는 앱이 `views/<템플릿>/Pages/`에 둔다.
57
- - **소켓·SSE:** `sockets`·`events`(0.1.3)의 반환 타입은 모양(`ModuleSocketRoute`·`ModuleEventRoute`)으로만 정한다. 그래서 쓰지 않는 프로젝트는 @dokebi/websocket·@dokebi/sse가 없어도 된다. 붙인 앱이 자기 네임스페이스 규칙으로 등록한다([D-0061](../../docs/decisions/D-0061-realtime-namespaces.md)): tenant는 `<네임스페이스>:<인증 tenant>`, 인증의 `namespace`는 그 앱의 목록 안이어야 한다.
58
- - **`moduleMount(plugin)`·`MODULE_MOUNT`:** 앱 플러그인이 붙이기 정보를 읽는 길이다. 앱 코드에서 쓸 일은 없다.
59
-
60
- ## 묶음 플러그인
61
-
62
- `createPlugin({ app: app.view, entry: { modules: [...] } })`는 여러 모듈을 의존성 그래프로 묶고 frozen `names`를 공개한다(플러그인 계약 v2, [D-0028](../../docs/decisions/D-0028-plugin-contract-v2.md)).
63
-
64
- - **생성 코드:** `dokebi module add`로 등록한 모듈의 default export를 이 entry로 넘긴다. 예전 진입 파일 `src/shared/modules/index.ts`가 있는 프로젝트는 그 `modules` 목록 뒤에 이어 붙인다.
65
- - **허용하는 모듈:** `defineModule`이 만든 것만(ID가 `dokebi-module.`으로 시작) 받는다. 중복은 `INVALID_PLUGIN_INPUT`이다. 단일 모듈은 app.register로 직접 등록해도 된다.
66
- - **수명주기:** setup에서 라우트를 등록하고, start는 실행 준비, drain은 유입 차단과 진행 업무 대기, context.defer는 전체 drain 이후 정리다.
67
- - **drain 순서:** 의존 역순이다. 어떤 모듈의 drain은 그 모듈에 의존하는 모듈의 drain이 끝난 뒤 시작한다. 서로 무관한 모듈은 동시에 진행한다.
68
- - **인스턴스:** 모듈 이름은 겹칠 수 없다. 하나의 모듈 인스턴스는 Application 하나에만 쓴다.
69
- - **제공하지 않는 것:** 실행 중 자동 검색·동적 import·hot reload·폴더 스캔은 없다. 등록은 CLI가 생성 코드에 적는다.
70
- - **설정:** YAML 설정은 빈 객체다.
71
-
72
- 예제:
73
-
74
- - [examples/26-scaffold](../../examples/26-scaffold/README.md): 생성·붙이기·덮어쓰기 반복 검증
75
- - [examples/25-playground](../../examples/25-playground/README.md): 기능 모듈 일곱 개
76
- - examples/22-web/main.ts: 코드로 직접 조합
39
+ - **`module` (ModuleContext):** PluginContext plus `module` (the name) and `controller(token)`.
40
+ - It reads only the declared `requires`.
41
+ - When a controller factory passes a freshly built descriptor object, the declared descriptor with that name is found.
42
+ - **`version`:** an exact semver, default `'0.1.0'`. Requires with duplicate names are refused.
43
+ - **`views`:** adds a template-ejs dependency automatically. Without `views/default/` the start fails.
44
+ - **`controllers`:** uses @dokebi/controller (optional peer). Calling `module.controller()` without controllers fails with `declares no controllers`.
45
+ - **`setup`:** optional. The older `setup(context)` form still works.
46
+ - **`contributes`** ([D-0130](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0130-module-contributions.md)): the points of other plugins this module contributes to (for example `mcpTools` of @dokebi/mcp). `setup` calls `module.contribute(point, value)` with objects that use the module's own services; core sets the module up before every collector of the point. A point that nothing collects drops its values with warn `POINT_NOT_COLLECTED`; an undeclared point is `UNDECLARED_POINT`; modules never collect. See AI.md §3a.
47
+ - **Shared APIs:** APIs that must answer on every domain are registered directly with router or web in setup, for example the playground's `/api/*`.
48
+ - **Mounting on apps:** `defineApp({ modules: { '/board': board } })`. Routes and sockets answer only on that app's domains and prefix. A mounted module's API is readable with `app.get(board)` without listing it in the app's `requires`. Details are in [@dokebi/app](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-app/README.md).
49
+ - **View lookup order:**
50
+ 1. `<app>/<template>/<module>/…`
51
+ 2. `<app>/default/<module>/…`
52
+ 3. the module's `<template>/…`
53
+ 4. the module's `default/…`
54
+ 5. the app's views (layouts and partials)
55
+ 6. shared `src/shared/views`
56
+
57
+ So an app can change a single file of a module page, for example `src/apps/<app>/views/christmas/<module>/heading.ejs`.
58
+ - **Inertia apps:** the module produces props with `page.inertia.render(request, reply, 'Component', props)`. The app keeps the Vue pages in `views/<template>/Pages/`.
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
+ - **`moduleMount(plugin)` and `MODULE_MOUNT`:** how the app plugin reads the mounting information. App code never needs them.
61
+
62
+ ## Group plugin
63
+
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)).
65
+
66
+ - **Generated code:** passes the default exports of the modules registered with `dokebi module add` to this entry. Projects with the old entry file `src/shared/modules/index.ts` get them appended after its `modules` list.
67
+ - **Accepted modules:** only what `defineModule` made (IDs starting with `dokebi-module.`). Duplicates are `INVALID_PLUGIN_INPUT`. A single module may also be registered directly with app.register.
68
+ - **Lifecycle:** setup registers routes, start prepares to run, drain stops new input and waits for work in progress, and context.defer cleans up after the whole drain.
69
+ - **Drain order:** reverse dependency order. A module's drain starts after the drains of the modules that depend on it have finished. Unrelated modules drain at the same time.
70
+ - **Instances:** module names cannot repeat. One module instance is used by one Application only.
71
+ - **Not provided:** automatic discovery, dynamic import, hot reload and folder scanning while running. The CLI writes registrations into the generated code.
72
+ - **Configuration:** the YAML settings are an empty object.
73
+
74
+ Examples:
75
+
76
+ - [examples/26-scaffold](https://git.nyx-zone.com/dokebi/framework/-/blob/main/examples/26-scaffold/README.md): repeated checks of generation, mounting and overriding
77
+ - [examples/25-playground](https://git.nyx-zone.com/dokebi/framework/-/blob/main/examples/25-playground/README.md): eight feature modules
78
+ - `examples/22-web/main.ts`: assembled in code
79
+
80
+ See the [AI guide](AI.md) for errors and cautions.
81
+
82
+ ## Service composition
83
+
84
+ Use Controller -> Service -> Model for application data. Controllers handle HTTP input/output;
85
+ services provide data and coordinate workflows through models; models own persistence.
86
+ Generated app/module starters include this chain. Keep services free of request/reply and
87
+ rendering objects, and reuse them from jobs. Compose dependencies once during setup.
88
+ App-specific services belong in `src/apps/<app>/services`, cross-app services in
89
+ `src/shared/services`, and module services in `src/shared/modules/<module>/services`.
90
+ Shared services must not import app-specific code. These are ordinary application classes,
91
+ not a new framework plugin or service registry. Existing projects are not moved automatically.
package/dist/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import type { ControllerDefinition } from '@dokebi/controller';
2
- import { type Awaitable, type Plugin, type PluginContext, type PluginDependency } from '@dokebi/core';
2
+ import { type Awaitable, type ContributionPoint, type Plugin, type PluginContext, type PluginDependency } from '@dokebi/core';
3
3
  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
+ /** 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';
7
9
  /** A plugin instance (read with context.get) or a descriptor (read with context.getDependency). */
8
10
  export type ModuleRequirement = Plugin<unknown> | PluginDependency;
9
11
  /** The plugin context of a module, plus the controllers the module declares. */
@@ -50,6 +52,10 @@ export interface ModuleRouter {
50
52
  */
51
53
  export interface ModuleSocketRoute {
52
54
  readonly path: string;
55
+ /** `{ id }`: the route id (D-0140), unique in each app that mounts the module. */
56
+ readonly config?: {
57
+ readonly id?: string;
58
+ };
53
59
  readonly constraints?: Readonly<Record<string, unknown>>;
54
60
  /**
55
61
  * `namespace` (D-0061): one of the mounting app's `realtime.namespaces` (default its first);
@@ -67,6 +73,10 @@ export interface ModuleSocketRoute {
67
73
  */
68
74
  export interface ModuleEventRoute {
69
75
  readonly path: string;
76
+ /** `{ id }`: the route id (D-0140), unique in each app that mounts the module. */
77
+ readonly config?: {
78
+ readonly id?: string;
79
+ };
70
80
  readonly constraints?: Readonly<Record<string, unknown>>;
71
81
  authenticate(request: FastifyRequest): Awaitable<{
72
82
  readonly tenant: string;
@@ -80,6 +90,13 @@ export interface ModuleDefinition<T> {
80
90
  readonly requires?: readonly ModuleRequirement[];
81
91
  /** `defineController` tokens, built once with this module's context. */
82
92
  readonly controllers?: readonly ControllerDefinition<unknown>[];
93
+ /**
94
+ * Points this module contributes to (D-0130), made by `definePoint` and imported from the
95
+ * plugin that owns them (for example `mcpTools` of @dokebi/mcp). The module's setup calls
96
+ * `module.contribute(point, value)`; core sets the module up before every collector of the
97
+ * point. Values that no registered plugin collects are dropped with warn `POINT_NOT_COLLECTED`.
98
+ */
99
+ readonly contributes?: readonly Pick<ContributionPoint<unknown>, 'name'>[];
83
100
  /** Folder with one sub-folder per template (`default/` is required). */
84
101
  readonly views?: URL;
85
102
  /** Routes registered by every app that mounts this module (`defineApp({ modules })`). */
package/dist/index.js CHANGED
@@ -1,14 +1,37 @@
1
1
  import { stat } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { types } from 'node:util';
4
- import { definePlugin, dependencyOf, providerDependency, } from '@dokebi/core';
4
+ import { DokebiError, definePlugin, dependencyOf, providerDependency, } from '@dokebi/core';
5
+ import { options } from './options.js';
6
+ const FIX = {
7
+ 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
+ INVALID_REQUIREMENT: 'List plugin instances or dependency descriptors ({ name, version }) in requires, each name once.',
9
+ INVALID_ENTRY: 'Export modules: an array of distinct defineModule plugins (at most 1024) from src/shared/modules/index.ts (npx dokebi module add <name> writes it).',
10
+ ALREADY_SET_UP: 'Create the module plugin once per Application (call defineModule for each application).',
11
+ NOT_SET_UP: 'Read the module context after the module plugin has set up.',
12
+ NO_CONTROLLERS: 'Add the controller token to controllers of defineModule before calling module.controller().',
13
+ VIEWS_MISSING: 'Create the views/default/ folder of the module (the cause names the file system error), or remove views.',
14
+ 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
+ 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.',
16
+ };
17
+ function moduleError(code, message, cause, fix = FIX[code]) {
18
+ return new DokebiError(code, message, {
19
+ plugin: 'dokebi-module',
20
+ fix,
21
+ ...(cause === undefined ? {} : { cause }),
22
+ });
23
+ }
5
24
  export const MODULE_MOUNT = Symbol.for('dokebi.module.mount');
6
25
  const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
26
+ /** core's point name (`<owner plugin>:<name>`) and its limit per plugin (D-0063). */
27
+ const POINT_NAME = /^[a-z0-9][a-z0-9._/-]{0,95}:[a-z0-9][a-z0-9._-]{0,63}$/;
28
+ const POINT_LIMIT = 64;
7
29
  const DEFINITION_KEYS = new Set([
8
30
  'name',
9
31
  'version',
10
32
  'requires',
11
33
  'controllers',
34
+ 'contributes',
12
35
  'views',
13
36
  'routes',
14
37
  'sockets',
@@ -19,20 +42,40 @@ const DEFINITION_KEYS = new Set([
19
42
  ]);
20
43
  const ejs = providerDependency({
21
44
  name: 'dokebi-template-ejs',
22
- version: '^0.1.0',
45
+ version: '^0.4.0',
23
46
  packageName: '@dokebi/template-ejs',
24
47
  load: () => import('@dokebi/template-ejs'),
25
48
  });
26
49
  function requirement(value) {
27
50
  if (value === null || typeof value !== 'object')
28
- throw new TypeError('Invalid module requirement');
51
+ throw moduleError('INVALID_REQUIREMENT', 'Invalid module requirement');
29
52
  if (typeof value.setup === 'function')
30
53
  return dependencyOf(value);
31
54
  if (typeof value.name !== 'string')
32
- throw new TypeError('Invalid module requirement');
55
+ throw moduleError('INVALID_REQUIREMENT', 'Invalid module requirement');
33
56
  return value;
34
57
  }
35
- function moduleContext(context, name, declared, controllers) {
58
+ /** The point names of `contributes` (D-0130): made by definePoint, distinct, at most 64. */
59
+ function contributedPoints(value, module) {
60
+ if (value === undefined)
61
+ return Object.freeze([]);
62
+ const invalid = (detail) => moduleError('INVALID_CONTRIBUTION', `Invalid contributes of module ${module}: ${detail}`);
63
+ if (!Array.isArray(value) || types.isProxy(value))
64
+ throw invalid('expected an array of points');
65
+ if (value.length > POINT_LIMIT)
66
+ throw invalid(`more than ${POINT_LIMIT} points`);
67
+ const names = new Set();
68
+ for (const point of value) {
69
+ const name = point?.name;
70
+ if (typeof name !== 'string' || !POINT_NAME.test(name))
71
+ throw invalid('a point made by definePoint (<owner plugin>:<name>) was expected');
72
+ if (names.has(name))
73
+ throw invalid(`${name} is listed twice`);
74
+ names.add(name);
75
+ }
76
+ return Object.freeze([...names]);
77
+ }
78
+ function moduleContext(context, name, declared, controllers, points) {
36
79
  // core accepts only the descriptor object this module declared; look it up by name.
37
80
  const own = (dependency) => declared.get(dependency?.name) ?? dependency;
38
81
  return Object.freeze({
@@ -49,14 +92,33 @@ function moduleContext(context, name, declared, controllers) {
49
92
  get drainSignal() {
50
93
  return context.drainSignal;
51
94
  },
95
+ // Set when the drain phase starts: read it there, not at setup.
96
+ get drainDeadline() {
97
+ return context.drainDeadline;
98
+ },
99
+ // The same frozen object for the whole application (core's own).
100
+ runtime: context.runtime,
52
101
  get: (plugin) => context.get(plugin),
53
102
  getDependency: (dependency) => context.getDependency(own(dependency)),
54
103
  getOptionalDependency: (dependency) => context.getOptionalDependency(own(dependency)),
55
104
  defer: (cleanup) => context.defer(cleanup),
105
+ // D-0130: a module contributes to the points of its `contributes`; core then checks the
106
+ // phase (CONTRIBUTIONS_CLOSED outside the module's setup) and orders the collectors after it.
107
+ contribute: (point, value) => {
108
+ const pointName = point?.name;
109
+ if (typeof pointName === 'string' && POINT_NAME.test(pointName) && !points.has(pointName))
110
+ throw moduleError('UNDECLARED_POINT', `Module ${name} does not declare the point ${pointName}`, undefined, `Add ${pointName} to contributes of defineModule({ name: '${name}', contributes: [...] }).`);
111
+ context.contribute(point, value);
112
+ },
113
+ // Modules never collect: reading a point is a plugin's role (definePlugin collects).
114
+ collect: (point) => {
115
+ const pointName = point?.name;
116
+ throw moduleError('UNDECLARED_POINT', `Module ${name} cannot collect ${typeof pointName === 'string' ? pointName : 'a point'}`, undefined, 'Modules only contribute. Collect the point in a plugin that declares it in collects (definePlugin), and give the module what it needs through requires.');
117
+ },
56
118
  controller: (definition) => {
57
119
  const api = controllers();
58
120
  if (!api)
59
- throw new Error(`Module ${name} declares no controllers`);
121
+ throw moduleError('NO_CONTROLLERS', `Module ${name} declares no controllers`);
60
122
  return api.get(definition);
61
123
  },
62
124
  });
@@ -75,11 +137,13 @@ export function defineModule(definition) {
75
137
  (definition.views !== undefined &&
76
138
  (!(definition.views instanceof URL) || definition.views.protocol !== 'file:')) ||
77
139
  ['routes', 'sockets', 'events', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function'))
78
- throw new TypeError('Invalid module definition');
140
+ throw moduleError('INVALID_DEFINITION', 'Invalid module definition');
79
141
  const { name, views } = definition;
142
+ const points = contributedPoints(definition.contributes, name);
143
+ const pointSet = new Set(points);
80
144
  const dependencies = (definition.requires ?? []).map(requirement);
81
145
  if (new Set(dependencies.map((dependency) => dependency.name)).size !== dependencies.length)
82
- throw new TypeError('Duplicate module requirement');
146
+ throw moduleError('INVALID_REQUIREMENT', 'Duplicate module requirement');
83
147
  if (views && !dependencies.some((dependency) => dependency.name === ejs.name))
84
148
  dependencies.push(ejs);
85
149
  // core needs the declared descriptor object itself (the module's own or the one in requires).
@@ -91,7 +155,7 @@ export function defineModule(definition) {
91
155
  const prefix = `module.${name}`;
92
156
  const hook = (key) => async (context) => {
93
157
  const begin = performance.now();
94
- await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers));
158
+ await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet));
95
159
  context.logger.log('debug', `Module ${key} finished`, {
96
160
  module: name,
97
161
  ms: Math.round(performance.now() - begin),
@@ -101,14 +165,16 @@ export function defineModule(definition) {
101
165
  metadata: Object.freeze({
102
166
  name: 'dokebi-module.' + name,
103
167
  version,
104
- core: '^0.2.0',
168
+ core: '^0.4.0',
105
169
  dependencies: Object.freeze(dependencies),
170
+ // D-0130: declared when the module is defined, so core orders the collectors after it.
171
+ ...(points.length ? { contributes: points, uncollected: 'warn' } : {}),
106
172
  }),
107
173
  async setup(context) {
108
174
  if (started)
109
- throw new Error('Create one module instance per Application');
175
+ throw moduleError('ALREADY_SET_UP', 'Create one module instance per Application');
110
176
  started = true;
111
- current = moduleContext(context, name, declared, () => controllers);
177
+ current = moduleContext(context, name, declared, () => controllers, pointSet);
112
178
  const begin = performance.now();
113
179
  if (definition.controllers?.length) {
114
180
  const { createControllers } = await import('@dokebi/controller');
@@ -123,7 +189,7 @@ export function defineModule(definition) {
123
189
  return undefined;
124
190
  });
125
191
  if (!info?.isDirectory())
126
- throw new Error(`Module ${name} has no views/default/ folder`, failure === undefined ? undefined : { cause: failure });
192
+ throw moduleError('VIEWS_MISSING', `Module ${name} has no views/default/ folder`, failure);
127
193
  await context.getDependency(templates ?? ejs).addDirectory(views, prefix);
128
194
  }
129
195
  const api = (await definition.setup?.(current));
@@ -132,6 +198,7 @@ export function defineModule(definition) {
132
198
  version,
133
199
  requires: dependencies.map((dependency) => dependency.name),
134
200
  controllers: definition.controllers?.length ?? 0,
201
+ contributes: points,
135
202
  views: views ? prefix : false,
136
203
  routes: Boolean(definition.routes),
137
204
  sockets: Boolean(definition.sockets),
@@ -151,7 +218,7 @@ export function defineModule(definition) {
151
218
  events: definition.events?.bind(definition),
152
219
  context: () => {
153
220
  if (!current)
154
- throw new Error(`Module ${name} is not set up yet`);
221
+ throw moduleError('NOT_SET_UP', `Module ${name} is not set up yet`);
155
222
  return current;
156
223
  },
157
224
  });
@@ -177,7 +244,7 @@ function parseEntry(input) {
177
244
  Array.isArray(input) ||
178
245
  types.isProxy(input) ||
179
246
  ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
180
- throw new TypeError('Invalid module entry');
247
+ throw moduleError('INVALID_ENTRY', 'Invalid module entry');
181
248
  let modules;
182
249
  for (const key of Reflect.ownKeys(input)) {
183
250
  // Module namespaces carry Symbol.toStringTag; only string exports are entry fields.
@@ -185,27 +252,17 @@ function parseEntry(input) {
185
252
  continue;
186
253
  const descriptor = Object.getOwnPropertyDescriptor(input, key);
187
254
  if (key !== 'modules' || !descriptor || !('value' in descriptor))
188
- throw new TypeError('Invalid module entry');
255
+ throw moduleError('INVALID_ENTRY', 'Invalid module entry');
189
256
  modules = descriptor.value;
190
257
  }
191
258
  if (!Array.isArray(modules) || modules.length > LIMIT)
192
- throw new TypeError('Expected a modules array');
259
+ throw moduleError('INVALID_ENTRY', 'Expected a modules array');
193
260
  const names = modules.map((module) => module?.metadata?.name);
194
261
  if (names.some((name) => typeof name !== 'string' || !name.startsWith('dokebi-module.')) ||
195
262
  new Set(names).size !== names.length)
196
- throw new TypeError('Expected distinct module plugins');
263
+ throw moduleError('INVALID_ENTRY', 'Expected distinct module plugins');
197
264
  return [...modules];
198
265
  }
199
- function parseOptions(input) {
200
- if (input === null ||
201
- typeof input !== 'object' ||
202
- Array.isArray(input) ||
203
- types.isProxy(input) ||
204
- ![Object.prototype, null].includes(Object.getPrototypeOf(input)) ||
205
- Reflect.ownKeys(input).length)
206
- throw new TypeError('dokebi-module accepts no options');
207
- return Object.freeze({});
208
- }
209
266
  class ModuleGroupRuntime {
210
267
  names;
211
268
  constructor(names) {
@@ -218,9 +275,9 @@ class ModuleGroupRuntime {
218
275
  }
219
276
  export const createPlugin = definePlugin({
220
277
  name: 'dokebi-module',
221
- version: '0.1.3',
222
- core: '^0.2.0',
223
- options: parseOptions,
278
+ version: '0.4.1',
279
+ core: '^0.4.0',
280
+ options,
224
281
  entry: parseEntry,
225
282
  dependencies: ({ entry }) => (entry ?? []).map((module) => dependencyOf(module)),
226
283
  instance: ({ dependencies }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name))),
@@ -0,0 +1,7 @@
1
+ import { type OptionsOf } from '@dokebi/core';
2
+ /**
3
+ * dokebi-module has no options: dokebi.yaml may only give an empty mapping (D-0063 §3). The
4
+ * build writes options.schema.json from this declaration.
5
+ */
6
+ export declare const options: import("@dokebi/core").OptionsDeclaration<{}>;
7
+ export type ModuleGroupOptions = OptionsOf<typeof options>;
@@ -0,0 +1,6 @@
1
+ import { defineOptions } from '@dokebi/core';
2
+ /**
3
+ * dokebi-module has no options: dokebi.yaml may only give an empty mapping (D-0063 §3). The
4
+ * build writes options.schema.json from this declaration.
5
+ */
6
+ export const options = defineOptions({});
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "@dokebi/module",
3
- "version": "0.1.3",
3
+ "version": "0.4.1",
4
+ "description": "Feature modules for Dokebi apps: controllers, models, views and routes in one folder mounted under a prefix.",
5
+ "keywords": [
6
+ "dokebi",
7
+ "dokebi-plugin",
8
+ "web",
9
+ "modules",
10
+ "mvc"
11
+ ],
4
12
  "private": false,
5
13
  "type": "module",
6
14
  "license": "MIT",
@@ -24,23 +32,26 @@
24
32
  "node": ">=24.0.0"
25
33
  },
26
34
  "scripts": {
27
- "build": "tsc -p tsconfig.json",
35
+ "build": "tsc -p tsconfig.json && node -e \"import('./dist/options.js').then(async (m) => { const { renderOptionsSchema } = await import('@dokebi/core'); process.stdout.write(renderOptionsSchema(m.options)); })\" > options.schema.json",
28
36
  "typecheck": "tsc -p tsconfig.test.json --noEmit",
29
- "test": "tsc -p tsconfig.test.json && node --test .tmp/tests/tests/*.test.js"
37
+ "test": "node -e \"require('node:fs').rmSync('.tmp/tests',{recursive:true,force:true})\" && tsc -p tsconfig.test.json && node --test .tmp/tests/tests/*.test.js"
30
38
  },
31
39
  "peerDependencies": {
32
- "@dokebi/controller": "^0.1.0",
33
- "@dokebi/core": "^0.2.0",
34
- "@dokebi/template-ejs": "^0.1.0",
35
- "@dokebi/template-inertia": "^0.1.0 || ^0.2.0",
36
- "@dokebi/web": "^0.1.0 || ^0.2.0",
40
+ "@dokebi/controller": "^0.4.0",
41
+ "@dokebi/core": "^0.4.0",
42
+ "@dokebi/template-ejs": "^0.4.0",
43
+ "@dokebi/template-inertia": "^0.4.0",
44
+ "@dokebi/web": "^0.4.0",
37
45
  "fastify": "^5.12.7"
38
46
  },
39
47
  "dokebi": {
40
48
  "schemaVersion": 2,
41
49
  "id": "dokebi-module",
42
- "core": "^0.2.0",
50
+ "core": "^0.4.0",
43
51
  "dependencies": [],
52
+ "hosts": [
53
+ "modules"
54
+ ],
44
55
  "install": {
45
56
  "directories": [
46
57
  "src/shared/modules"
@@ -49,6 +60,21 @@
49
60
  "optionsSchema": "options.schema.json",
50
61
  "documentation": "AI.md"
51
62
  },
63
+ "dokebiCatalog": {
64
+ "kind": "plugin",
65
+ "summary": "Modules that hold one feature each (src/shared/modules/<module>); an app attaches them under a prefix",
66
+ "maturity": "preview",
67
+ "provides": [
68
+ "web.modules"
69
+ ],
70
+ "doesNot": [
71
+ "Does not attach modules to apps by itself (modules in app.ts)"
72
+ ],
73
+ "recipes": [
74
+ "api",
75
+ "blog"
76
+ ]
77
+ },
52
78
  "peerDependenciesMeta": {
53
79
  "@dokebi/controller": {
54
80
  "optional": true
@@ -67,10 +93,10 @@
67
93
  }
68
94
  },
69
95
  "devDependencies": {
70
- "@dokebi/controller": "0.1.2",
71
- "@dokebi/template-ejs": "0.1.2",
72
- "@dokebi/template-inertia": "0.2.0",
73
- "@dokebi/web": "0.2.0"
96
+ "@dokebi/controller": "0.4.2",
97
+ "@dokebi/template-ejs": "0.4.3",
98
+ "@dokebi/template-inertia": "0.4.4",
99
+ "@dokebi/web": "0.4.3"
74
100
  },
75
101
  "publishConfig": {
76
102
  "access": "public",
@@ -1,11 +1,22 @@
1
1
  import { defineController } from '@dokebi/controller';
2
2
  import type { ModulePage } from '@dokebi/module';
3
- import { summary } from '../models/summary.ts';
3
+ import { ItemsService } from '../services/items.ts';
4
4
 
5
5
  export class ItemsController {
6
+ readonly #service: ItemsService;
7
+ constructor(service: ItemsService) {
8
+ this.#service = service;
9
+ }
6
10
  list(page: ModulePage) {
7
- return { title: '{{module}}', message: summary(page) };
11
+ return this.#service.list({
12
+ appName: page.app.name,
13
+ base: page.base,
14
+ template: page.app.template,
15
+ });
8
16
  }
9
17
  }
10
18
  // Built once with this module's context; read it with module.controller(itemsController).
11
- export const itemsController = defineController('items', () => new ItemsController());
19
+ export const itemsController = defineController(
20
+ 'items',
21
+ () => new ItemsController(new ItemsService()),
22
+ );
@@ -1,6 +1,6 @@
1
- import type { ModulePage } from '@dokebi/module';
1
+ export type ModuleIdentity = { appName: string; base: string; template: string };
2
2
 
3
- /** Models are plain code; controllers pass them what they need. */
4
- export function summary(page: ModulePage): string {
5
- return `{{module}} module in app ${page.app.name} at ${page.base || '/'} (template: ${page.app.template})`;
3
+ /** A pure model for this starter; services provide data without HTTP objects. */
4
+ export function summary(module: ModuleIdentity): string {
5
+ return `{{module}} module in app ${module.appName} at ${module.base || '/'} (template: ${module.template})`;
6
6
  }
@@ -11,6 +11,10 @@ export default defineModule({
11
11
  // Plugins and other modules this module uses (instances or dependency descriptors).
12
12
  requires: [],
13
13
  controllers: [itemsController],
14
+ // Points of plugins this module contributes to (D-0130), for example MCP tools:
15
+ // contributes: [mcpTools], // import { mcpTools } from '@dokebi/mcp'
16
+ // setup(module) { module.contribute(mcpTools, new ListItems(service)); },
17
+ // The contributed objects use this module's own services; the collector sets up after it.
14
18
  // One folder per template; `default` is required. An app replaces a file of this module by
15
19
  // putting it in src/apps/<app>/views/<template>/{{module}}/.
16
20
  views: new URL('./views/', import.meta.url),
@@ -0,0 +1,7 @@
1
+ import { type ModuleIdentity, summary } from '../models/summary.ts';
2
+
3
+ export class ItemsService {
4
+ list(module: ModuleIdentity) {
5
+ return { title: '{{module}}', message: summary(module) };
6
+ }
7
+ }
@@ -1,11 +1,22 @@
1
1
  import { defineController } from '@dokebi/controller';
2
2
  import type { ModulePage } from '@dokebi/module';
3
- import { summary } from '../models/summary.ts';
3
+ import { ItemsService } from '../services/items.ts';
4
4
 
5
5
  export class ItemsController {
6
+ readonly #service: ItemsService;
7
+ constructor(service: ItemsService) {
8
+ this.#service = service;
9
+ }
6
10
  list(page: ModulePage) {
7
- return { title: '{{module}}', message: summary(page) };
11
+ return this.#service.list({
12
+ appName: page.app.name,
13
+ base: page.base,
14
+ template: page.app.template,
15
+ });
8
16
  }
9
17
  }
10
18
  // Built once with this module's context; read it with module.controller(itemsController).
11
- export const itemsController = defineController('items', () => new ItemsController());
19
+ export const itemsController = defineController(
20
+ 'items',
21
+ () => new ItemsController(new ItemsService()),
22
+ );
@@ -1,6 +1,6 @@
1
- import type { ModulePage } from '@dokebi/module';
1
+ export type ModuleIdentity = { appName: string; base: string; template: string };
2
2
 
3
- /** Models are plain code; controllers pass them what they need. */
4
- export function summary(page: ModulePage): string {
5
- return `{{module}} module in app ${page.app.name} at ${page.base || '/'} (template: ${page.app.template})`;
3
+ /** A pure model for this starter; services provide data without HTTP objects. */
4
+ export function summary(module: ModuleIdentity): string {
5
+ return `{{module}} module in app ${module.appName} at ${module.base || '/'} (template: ${module.template})`;
6
6
  }
@@ -12,5 +12,9 @@ export default defineModule({
12
12
  // Plugins and other modules this module uses (instances or dependency descriptors).
13
13
  requires: [],
14
14
  controllers: [itemsController],
15
+ // Points of plugins this module contributes to (D-0130), for example MCP tools:
16
+ // contributes: [mcpTools], // import { mcpTools } from '@dokebi/mcp'
17
+ // setup(module) { module.contribute(mcpTools, new ListItems(service)); },
18
+ // The contributed objects use this module's own services; the collector sets up after it.
15
19
  routes,
16
20
  });
@@ -0,0 +1,7 @@
1
+ import { type ModuleIdentity, summary } from '../models/summary.ts';
2
+
3
+ export class ItemsService {
4
+ list(module: ModuleIdentity) {
5
+ return { title: '{{module}}', message: summary(module) };
6
+ }
7
+ }