@dokebi/module 0.1.2 → 0.4.0

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,86 +1,99 @@
1
- # AI 작업 안내 — @dokebi/module 0.1.2
1
+ # AI guide — @dokebi/module 0.4.0
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, 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/ 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';
31
33
  import { postsController } from './controllers/posts.ts';
32
34
 
33
35
  export default defineModule({
34
- name: 'board', // 폴더 이름. 플러그인 id는 dokebi-module.board
35
- requires: [db], // 인스턴스·descriptor·다른 모듈
36
+ name: 'board', // the folder name; the plugin id is dokebi-module.board
37
+ requires: [db], // instances, descriptors, other modules
36
38
  controllers: [postsController],
37
- views: new URL('./views/', import.meta.url), // default/ 필수(지정하면 template-ejs 의존 추가)
38
- routes(route, module) { // 붙인 앱마다 그 앱의 도메인·접두사로 등록
39
+ views: new URL('./views/', import.meta.url), // default/ is required (adds a template-ejs dependency)
40
+ routes(route, module) { // registered for every app that mounts it, on that app's domains and prefix
39
41
  route.get('/', async (request, reply, page) =>
40
42
  page.view.reply(reply, 'index', { posts: await module.controller(postsController).list(), base: page.base }),
41
43
  );
42
44
  route.post('/', async (request, reply, page) => { /* ... */ });
43
45
  },
44
- sockets: (module) => [boardSocket(module)], // defineSocket 결과. tenant는 <앱>:<tenant>
45
- setup(module) { return { count: () => module.controller(postsController).count() }; }, // 다른 쪽이 받는 API
46
+ sockets: (module) => [boardSocket(module)], // defineSocket results; tenant is <namespace>:<tenant>
47
+ events: (module) => [boardStream(module)], // (0.1.3) @dokebi/sse routes (SseRoute); same rules as sockets
48
+ setup(module) { return { count: () => module.controller(postsController).count() }; }, // the API others receive
46
49
  start(module) {}, drain(module) {},
47
50
  });
48
51
  ```
49
52
 
50
- - `module`(ModuleContext) = PluginContext + `module`(이름) + `controller(token)`. `requires`에 선언한 것만 `get`·`getDependency`로 읽는다.
51
- - `page`(ModulePage) = `{ app: { name, template, domain }, module, base, view, inertia }`. 링크는 `page.base`를 붙여 만든다(앱마다 접두사가 다를 수 있다).
52
- - `version`은 정확한 semver(기본 `'0.1.0'`). 같은 이름의 requires는 거부한다.
53
- - 컨트롤러 없이 `module.controller()`를 부르면 `declares no controllers` 오류.
53
+ - `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.
54
+ - `page` (ModulePage) = `{ app: { name, template, domain }, module, base, view, inertia }`. Build links with `page.base` (each app may use a different prefix).
55
+ - `version` is an exact semver (default `'0.1.0'`). Requires with duplicate names are refused.
56
+ - `views`: adds a template-ejs dependency automatically; the start fails without `views/default/`. Template names get the prefix `module.<name>`.
57
+ - `controllers`: uses @dokebi/controller (optional peer). Calling `module.controller()` without controllers is `NO_CONTROLLERS` (`declares no controllers`).
58
+ - `module.runtime` is core's runtime role (`solo`, `primary`, `worker`; D-0063 §4). Do not read `node:cluster` yourself.
59
+ - Route options are `WebRoute` options without `handler` and `constraints` (`ModuleRouteOptions`, so `seal` works).
60
+
61
+ ## 3. Mounting on apps and shared APIs
62
+
63
+ - 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`).
64
+ - 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).
65
+ - APIs that must answer on every domain (such as `/api/*`) are not `routes`; register them in `setup` directly with `@dokebi/router` (`mount`) or web.
66
+ - 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.
54
67
 
55
- ## 3. 앱에 붙이기와 공통 API
68
+ ## 4. View lookup order (how an app changes a module page)
56
69
 
57
- - 앱: `defineApp({ modules: { '/board': board } })`. 라우트·소켓은 **그 앱의 도메인과 접두사에서만** 응답한다. 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다.
58
- - 모든 도메인에서 응답해야 하는 API(예: `/api/*`)는 `routes`가 아니라 `setup`에서 `@dokebi/router`(`mount`)나 web으로 직접 등록한다.
59
- - 다른 모듈·플러그인이 이 모듈의 API를 쓰려면 `requires`에 이 모듈을 넣고 `get(모듈)` 하면 `setup`의 반환값을 받는다.
70
+ 1. `<app>/<template>/<module>/…`
71
+ 2. `<app>/default/<module>/…`
72
+ 3. the module's `<template>/…`
73
+ 4. the module's `default/…`
74
+ 5. the app's views (layouts and partials)
75
+ 6. shared `src/shared/views`
60
76
 
61
- ## 4. 화면 찾는 순서(앱이 모듈 화면을 바꾸는 법)
77
+ 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/`.
62
78
 
63
- 1. `<앱>/<템플릿>/<모듈>/…`
64
- 2. `<앱>/default/<모듈>/…`
65
- 3. 모듈의 `<템플릿>/…`
66
- 4. 모듈의 `default/…`
67
- 5. 앱 views(레이아웃·부분 템플릿)
68
- 6. 공통 `src/shared/views`
79
+ ## 5. Group plugin and lifecycle
69
80
 
70
- 앱이 모듈 화면을 바꿀 때는 모듈 파일을 고치지 말고 `src/apps/<앱>/views/<템플릿>/<모듈>/`에 같은 이름 파일을 둔다. Inertia 앱이 붙이면 모듈은 `page.inertia.render(request, reply, '컴포넌트', props)`로 props를 내고, Vue 페이지는 앱의 `views/<템플릿>/Pages/`에 둔다.
81
+ - `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`.
82
+ - 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.
83
+ - A module instance is used by one Application only. There is no automatic discovery, dynamic import or hot reload while running.
84
+ - Options of the group plugin are an empty object.
85
+ - Debug logs (D-0047): `Modules registered` (the group), `Module set up` (requires, number of controllers, 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`.
71
86
 
72
- ## 5. 묶음 플러그인과 수명주기
87
+ ## 6. Errors
73
88
 
74
- - `createPlugin({ app, entry: { modules } })`: 여러 모듈을 의존성 그래프로 묶는다. API는 `{ names }`. `defineModule`이 만든 것만 받고 중복은 `INVALID_PLUGIN_INPUT`.
75
- - 훅: setup(라우트 등록·API 반환) → start → drain(새 유입 차단, 진행 업무 대기) → defer 정리. drain은 의존 역순(이 모듈에 의존하는 모듈이 먼저), 무관한 모듈은 동시에.
76
- - 모듈 인스턴스는 Application 하나에만 쓴다. 실행 중 자동 검색·동적 import·hot reload는 없다.
77
- - debug 로그(D-0047): `Modules registered`(묶음)·`Module set up`(requires·컨트롤러 수·views 접두사·ms)·`Module start finished`·`Module drain finished`. `views/default/`가 없거나 읽을 수 없으면 시작 실패이고 원래 파일 오류는 `cause`에 남는다.
89
+ <!-- docs-check: complete-error-codes ModuleErrorCode -->
90
+ `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`). 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).
78
91
 
79
- ## 6. 주의 사항
92
+ ## 7. Cautions
80
93
 
81
- - 모듈은 앱에 의존하지 않는다(앱 이름으로 분기하지 않는다). 앱별 차이는 `page.app`과 앱의 화면 덮어쓰기로 처리한다.
82
- - `moduleMount`·`MODULE_MOUNT`는 @dokebi/app이 쓰는 내부 연결이다. 앱 코드에서 쓰지 않는다.
83
- - 소켓 타입은 모양으로만 정해져 있어 소켓 없는 프로젝트는 @dokebi/websocket이 필요 없다. 소켓을 쓰면 websocket을 add한다.
84
- - 응답 종료·연결 끊김을 업무 완료로 보지 않는다. 요청 밖으로 떼어 낸 작업은 모듈 `drain`에서 기다린다.
94
+ - 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.
95
+ - `moduleMount` and `MODULE_MOUNT` are the internal link @dokebi/app uses. App code does not use them.
96
+ - 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`).
97
+ - 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`.
85
98
 
86
- 근거: `examples/26-scaffold`(생성·붙이기·덮어쓰기 반복), `examples/25-playground`(기능 모듈 일곱 개), `examples/22-web/main.ts`(코드 조합), D-0022·D-0032.
99
+ 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.
package/README.md CHANGED
@@ -1,75 +1,78 @@
1
- # @dokebi/module 0.1.2
1
+ # @dokebi/module 0.4.0
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, 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
+ views: new URL('./views/', import.meta.url), // default/ required; template names get the prefix module.board
27
+ routes(route, module) { // registered per app (when mounted). page = { app, module, base, view, inertia }
28
28
  route.get('/', (request, reply, page) =>
29
29
  page.view.reply(reply, 'index', module.controller(postsController).list(page)));
30
30
  },
31
- sockets: (module) => [boardSocket(module)], // 앱마다 접두사 아래 등록, tenant는 <앱>:<tenant>
32
- setup(module) { return api; }, // 선택. 반환값이 이 모듈을 requires한 쪽이 받는 API
31
+ sockets: (module) => [boardSocket(module)], // registered per app under the prefix; tenant is <namespace>:<tenant>
32
+ events: (module) => [boardStream(module)], // (0.1.3) SSE routes (@dokebi/sse); same rules as sockets
33
+ setup(module) { return api; }, // optional; the return value is the API of whoever requires this module
33
34
  start(module) {}, drain(module) {},
34
35
  });
35
36
  ```
36
37
 
37
- - **`module`(ModuleContext):** PluginContext에 `module`(이름)과 `controller(token)`을 더한 것이다.
38
- - 선언한 `requires`만 읽는다.
39
- - 컨트롤러 factory가 descriptor 객체를 새로 만들어 넘겨도 이름으로 선언한 descriptor를 찾아 준다.
40
- - **`version`:** 정확한 semver이며 기본값은 `'0.1.0'`이다. 같은 이름의 requires는 거부한다.
41
- - **`views`:** 지정하면 template-ejs 의존이 자동으로 더해진다. `views/default/`가 없으면 시작이 실패한다.
42
- - **`controllers`:** 지정하면 @dokebi/controller를 쓴다(선택 peer). 컨트롤러 없이 `module.controller()`를 부르면 `declares no controllers` 오류가 난다.
43
- - **`setup`:** 선택이다. 기존 `setup(context)` 형태도 그대로 동작한다.
44
- - **공통 API:** 모든 도메인에서 응답해야 하는 API는 setup에서 router·web으로 직접 등록한다. 예: 플레이그라운드의 `/api/*`.
45
- - **앱에 붙이기:** `defineApp({ modules: { '/board': board } })`. 라우트·소켓이 그 앱의 도메인과 접두사에서만 응답한다. 붙인 모듈은 앱의 `requires`에 넣지 않아도 `app.get(board)`로 API를 읽을 수 있다. 자세한 내용은 [@dokebi/app](../dokebi-app/README.md)에 있다.
46
- - **화면 찾는 순서:**
47
- 1. `<앱>/<템플릿>/<모듈>/…`
48
- 2. `<앱>/default/<모듈>/…`
49
- 3. 모듈의 `<템플릿>/…`
50
- 4. 모듈의 `default/…`
51
- 5. 앱 views(레이아웃·부분 템플릿)
52
- 6. 공통 `src/shared/views`
38
+ - **`module` (ModuleContext):** PluginContext plus `module` (the name) and `controller(token)`.
39
+ - It reads only the declared `requires`.
40
+ - When a controller factory passes a freshly built descriptor object, the declared descriptor with that name is found.
41
+ - **`version`:** an exact semver, default `'0.1.0'`. Requires with duplicate names are refused.
42
+ - **`views`:** adds a template-ejs dependency automatically. Without `views/default/` the start fails.
43
+ - **`controllers`:** uses @dokebi/controller (optional peer). Calling `module.controller()` without controllers fails with `declares no controllers`.
44
+ - **`setup`:** optional. The older `setup(context)` form still works.
45
+ - **Shared APIs:** APIs that must answer on every domain are registered directly with router or web in setup, for example the playground's `/api/*`.
46
+ - **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).
47
+ - **View lookup order:**
48
+ 1. `<app>/<template>/<module>/…`
49
+ 2. `<app>/default/<module>/…`
50
+ 3. the module's `<template>/…`
51
+ 4. the module's `default/…`
52
+ 5. the app's views (layouts and partials)
53
+ 6. shared `src/shared/views`
53
54
 
54
- 그래서 앱은 모듈 화면의 파일 하나만 바꿀 수 있다. 예: `src/apps/<앱>/views/christmas/<모듈>/heading.ejs`.
55
- - **Inertia 앱:** 모듈이 `page.inertia.render(request, reply, '컴포넌트', props)`로 props를 낸다. Vue 페이지는 앱이 `views/<템플릿>/Pages/`에 둔다.
56
- - **소켓:** `sockets`의 반환 타입은 모양(`ModuleSocketRoute`)으로만 정한다. 그래서 소켓이 없는 프로젝트는 @dokebi/websocket이 없어도 된다.
57
- - **`moduleMount(plugin)`·`MODULE_MOUNT`:** 앱 플러그인이 붙이기 정보를 읽는 길이다. 앱 코드에서 쓸 일은 없다.
55
+ So an app can change a single file of a module page, for example `src/apps/<app>/views/christmas/<module>/heading.ejs`.
56
+ - **Inertia apps:** the module produces props with `page.inertia.render(request, reply, 'Component', props)`. The app keeps the Vue pages in `views/<template>/Pages/`.
57
+ - **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.
58
+ - **`moduleMount(plugin)` and `MODULE_MOUNT`:** how the app plugin reads the mounting information. App code never needs them.
58
59
 
59
- ## 묶음 플러그인
60
+ ## Group plugin
60
61
 
61
- `createPlugin({ app: app.view, entry: { modules: [...] } })`는 여러 모듈을 의존성 그래프로 묶고 frozen `names`를 공개한다(플러그인 계약 v2, [D-0028](../../docs/decisions/D-0028-plugin-contract-v2.md)).
62
+ `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)).
62
63
 
63
- - **생성 코드:** `dokebi module add`로 등록한 모듈의 default export를 이 entry로 넘긴다. 예전 진입 파일 `src/shared/modules/index.ts`가 있는 프로젝트는 그 `modules` 목록 뒤에 이어 붙인다.
64
- - **허용하는 모듈:** `defineModule`이 만든 것만(ID가 `dokebi-module.`으로 시작) 받는다. 중복은 `INVALID_PLUGIN_INPUT`이다. 단일 모듈은 app.register로 직접 등록해도 된다.
65
- - **수명주기:** setup에서 라우트를 등록하고, start는 실행 준비, drain은 유입 차단과 진행 업무 대기, context.defer는 전체 drain 이후 정리다.
66
- - **drain 순서:** 의존 역순이다. 어떤 모듈의 drain은 그 모듈에 의존하는 모듈의 drain이 끝난 뒤 시작한다. 서로 무관한 모듈은 동시에 진행한다.
67
- - **인스턴스:** 모듈 이름은 겹칠 수 없다. 하나의 모듈 인스턴스는 Application 하나에만 쓴다.
68
- - **제공하지 않는 것:** 실행 중 자동 검색·동적 import·hot reload·폴더 스캔은 없다. 등록은 CLI가 생성 코드에 적는다.
69
- - **설정:** YAML 설정은 빈 객체다.
64
+ - **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.
65
+ - **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.
66
+ - **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.
67
+ - **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.
68
+ - **Instances:** module names cannot repeat. One module instance is used by one Application only.
69
+ - **Not provided:** automatic discovery, dynamic import, hot reload and folder scanning while running. The CLI writes registrations into the generated code.
70
+ - **Configuration:** the YAML settings are an empty object.
70
71
 
71
- 예제:
72
+ Examples:
72
73
 
73
- - [examples/26-scaffold](../../examples/26-scaffold/README.md): 생성·붙이기·덮어쓰기 반복 검증
74
- - [examples/25-playground](../../examples/25-playground/README.md): 기능 모듈 일곱 개
75
- - examples/22-web/main.ts: 코드로 직접 조합
74
+ - [examples/26-scaffold](https://git.nyx-zone.com/dokebi/framework/-/blob/main/examples/26-scaffold/README.md): repeated checks of generation, mounting and overriding
75
+ - [examples/25-playground](https://git.nyx-zone.com/dokebi/framework/-/blob/main/examples/25-playground/README.md): eight feature modules
76
+ - `examples/22-web/main.ts`: assembled in code
77
+
78
+ See the [AI guide](AI.md) for errors and cautions.
package/dist/index.d.ts CHANGED
@@ -4,6 +4,8 @@ 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';
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. */
@@ -49,10 +51,28 @@ export interface ModuleRouter {
49
51
  * shape so projects whose modules have no sockets need not install @dokebi/websocket.
50
52
  */
51
53
  export interface ModuleSocketRoute {
54
+ readonly path: string;
55
+ readonly constraints?: Readonly<Record<string, unknown>>;
56
+ /**
57
+ * `namespace` (D-0061): one of the mounting app's `realtime.namespaces` (default its first);
58
+ * @dokebi/app prefixes the tenant with it and answers 401 for another one.
59
+ */
60
+ authenticate(request: FastifyRequest): Awaitable<{
61
+ readonly tenant: string;
62
+ readonly namespace?: string;
63
+ } | undefined>;
64
+ }
65
+ /**
66
+ * A server-sent event route of a module (0.1.3), as @dokebi/sse `SseRoute`. Typed by shape so
67
+ * projects whose modules have no event streams need not install @dokebi/sse. @dokebi/app mounts
68
+ * it like a module socket: under the prefix, on the app's domains, with the app's namespace rule.
69
+ */
70
+ export interface ModuleEventRoute {
52
71
  readonly path: string;
53
72
  readonly constraints?: Readonly<Record<string, unknown>>;
54
73
  authenticate(request: FastifyRequest): Awaitable<{
55
74
  readonly tenant: string;
75
+ readonly namespace?: string;
56
76
  } | undefined>;
57
77
  }
58
78
  export interface ModuleDefinition<T> {
@@ -68,6 +88,8 @@ export interface ModuleDefinition<T> {
68
88
  routes?(route: ModuleRouter, module: ModuleContext): Awaitable<void>;
69
89
  /** WebSocket routes registered by every app that mounts this module, under its prefix. */
70
90
  sockets?(module: ModuleContext): Awaitable<readonly ModuleSocketRoute[]>;
91
+ /** SSE routes (@dokebi/sse) registered by every app that mounts this module, under its prefix. */
92
+ events?(module: ModuleContext): Awaitable<readonly ModuleEventRoute[]>;
71
93
  /** Optional; the result is the API of this module for plugins and modules that require it. */
72
94
  setup?(module: ModuleContext): Awaitable<T>;
73
95
  start?(module: ModuleContext): Awaitable<void>;
@@ -83,6 +105,8 @@ export interface ModuleMount {
83
105
  readonly views: string | undefined;
84
106
  readonly routes: ModuleDefinition<unknown>['routes'];
85
107
  readonly sockets: ModuleDefinition<unknown>['sockets'];
108
+ /** SSE routes (0.1.3); undefined for a module without them (and in older module packages). */
109
+ readonly events: ModuleDefinition<unknown>['events'];
86
110
  /** The module context; available once the module has been set up. */
87
111
  context(): ModuleContext;
88
112
  }
package/dist/index.js CHANGED
@@ -1,7 +1,24 @@
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
+ };
15
+ function moduleError(code, message, cause) {
16
+ return new DokebiError(code, message, {
17
+ plugin: 'dokebi-module',
18
+ fix: FIX[code],
19
+ ...(cause === undefined ? {} : { cause }),
20
+ });
21
+ }
5
22
  export const MODULE_MOUNT = Symbol.for('dokebi.module.mount');
6
23
  const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
7
24
  const DEFINITION_KEYS = new Set([
@@ -12,23 +29,24 @@ const DEFINITION_KEYS = new Set([
12
29
  'views',
13
30
  'routes',
14
31
  'sockets',
32
+ 'events',
15
33
  'setup',
16
34
  'start',
17
35
  'drain',
18
36
  ]);
19
37
  const ejs = providerDependency({
20
38
  name: 'dokebi-template-ejs',
21
- version: '^0.1.0',
39
+ version: '^0.4.0',
22
40
  packageName: '@dokebi/template-ejs',
23
41
  load: () => import('@dokebi/template-ejs'),
24
42
  });
25
43
  function requirement(value) {
26
44
  if (value === null || typeof value !== 'object')
27
- throw new TypeError('Invalid module requirement');
45
+ throw moduleError('INVALID_REQUIREMENT', 'Invalid module requirement');
28
46
  if (typeof value.setup === 'function')
29
47
  return dependencyOf(value);
30
48
  if (typeof value.name !== 'string')
31
- throw new TypeError('Invalid module requirement');
49
+ throw moduleError('INVALID_REQUIREMENT', 'Invalid module requirement');
32
50
  return value;
33
51
  }
34
52
  function moduleContext(context, name, declared, controllers) {
@@ -48,14 +66,20 @@ function moduleContext(context, name, declared, controllers) {
48
66
  get drainSignal() {
49
67
  return context.drainSignal;
50
68
  },
69
+ // The same frozen object for the whole application (core's own).
70
+ runtime: context.runtime,
51
71
  get: (plugin) => context.get(plugin),
52
72
  getDependency: (dependency) => context.getDependency(own(dependency)),
53
73
  getOptionalDependency: (dependency) => context.getOptionalDependency(own(dependency)),
54
74
  defer: (cleanup) => context.defer(cleanup),
75
+ // The module plugin declares no contribution points, so core answers these with its coded
76
+ // errors (UNDECLARED_POINT, CONTRIBUTIONS_CLOSED); forwarded so ModuleContext stays a PluginContext.
77
+ contribute: (point, value) => context.contribute(point, value),
78
+ collect: (point) => context.collect(point),
55
79
  controller: (definition) => {
56
80
  const api = controllers();
57
81
  if (!api)
58
- throw new Error(`Module ${name} declares no controllers`);
82
+ throw moduleError('NO_CONTROLLERS', `Module ${name} declares no controllers`);
59
83
  return api.get(definition);
60
84
  },
61
85
  });
@@ -73,12 +97,12 @@ export function defineModule(definition) {
73
97
  (definition.controllers !== undefined && !Array.isArray(definition.controllers)) ||
74
98
  (definition.views !== undefined &&
75
99
  (!(definition.views instanceof URL) || definition.views.protocol !== 'file:')) ||
76
- ['routes', 'sockets', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function'))
77
- throw new TypeError('Invalid module definition');
100
+ ['routes', 'sockets', 'events', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function'))
101
+ throw moduleError('INVALID_DEFINITION', 'Invalid module definition');
78
102
  const { name, views } = definition;
79
103
  const dependencies = (definition.requires ?? []).map(requirement);
80
104
  if (new Set(dependencies.map((dependency) => dependency.name)).size !== dependencies.length)
81
- throw new TypeError('Duplicate module requirement');
105
+ throw moduleError('INVALID_REQUIREMENT', 'Duplicate module requirement');
82
106
  if (views && !dependencies.some((dependency) => dependency.name === ejs.name))
83
107
  dependencies.push(ejs);
84
108
  // core needs the declared descriptor object itself (the module's own or the one in requires).
@@ -100,12 +124,12 @@ export function defineModule(definition) {
100
124
  metadata: Object.freeze({
101
125
  name: 'dokebi-module.' + name,
102
126
  version,
103
- core: '^0.2.0',
127
+ core: '^0.4.0',
104
128
  dependencies: Object.freeze(dependencies),
105
129
  }),
106
130
  async setup(context) {
107
131
  if (started)
108
- throw new Error('Create one module instance per Application');
132
+ throw moduleError('ALREADY_SET_UP', 'Create one module instance per Application');
109
133
  started = true;
110
134
  current = moduleContext(context, name, declared, () => controllers);
111
135
  const begin = performance.now();
@@ -122,7 +146,7 @@ export function defineModule(definition) {
122
146
  return undefined;
123
147
  });
124
148
  if (!info?.isDirectory())
125
- throw new Error(`Module ${name} has no views/default/ folder`, failure === undefined ? undefined : { cause: failure });
149
+ throw moduleError('VIEWS_MISSING', `Module ${name} has no views/default/ folder`, failure);
126
150
  await context.getDependency(templates ?? ejs).addDirectory(views, prefix);
127
151
  }
128
152
  const api = (await definition.setup?.(current));
@@ -134,6 +158,7 @@ export function defineModule(definition) {
134
158
  views: views ? prefix : false,
135
159
  routes: Boolean(definition.routes),
136
160
  sockets: Boolean(definition.sockets),
161
+ events: Boolean(definition.events),
137
162
  ms: Math.round(performance.now() - begin),
138
163
  });
139
164
  return api;
@@ -146,9 +171,10 @@ export function defineModule(definition) {
146
171
  views: views ? prefix : undefined,
147
172
  routes: definition.routes?.bind(definition),
148
173
  sockets: definition.sockets?.bind(definition),
174
+ events: definition.events?.bind(definition),
149
175
  context: () => {
150
176
  if (!current)
151
- throw new Error(`Module ${name} is not set up yet`);
177
+ throw moduleError('NOT_SET_UP', `Module ${name} is not set up yet`);
152
178
  return current;
153
179
  },
154
180
  });
@@ -174,7 +200,7 @@ function parseEntry(input) {
174
200
  Array.isArray(input) ||
175
201
  types.isProxy(input) ||
176
202
  ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
177
- throw new TypeError('Invalid module entry');
203
+ throw moduleError('INVALID_ENTRY', 'Invalid module entry');
178
204
  let modules;
179
205
  for (const key of Reflect.ownKeys(input)) {
180
206
  // Module namespaces carry Symbol.toStringTag; only string exports are entry fields.
@@ -182,27 +208,17 @@ function parseEntry(input) {
182
208
  continue;
183
209
  const descriptor = Object.getOwnPropertyDescriptor(input, key);
184
210
  if (key !== 'modules' || !descriptor || !('value' in descriptor))
185
- throw new TypeError('Invalid module entry');
211
+ throw moduleError('INVALID_ENTRY', 'Invalid module entry');
186
212
  modules = descriptor.value;
187
213
  }
188
214
  if (!Array.isArray(modules) || modules.length > LIMIT)
189
- throw new TypeError('Expected a modules array');
215
+ throw moduleError('INVALID_ENTRY', 'Expected a modules array');
190
216
  const names = modules.map((module) => module?.metadata?.name);
191
217
  if (names.some((name) => typeof name !== 'string' || !name.startsWith('dokebi-module.')) ||
192
218
  new Set(names).size !== names.length)
193
- throw new TypeError('Expected distinct module plugins');
219
+ throw moduleError('INVALID_ENTRY', 'Expected distinct module plugins');
194
220
  return [...modules];
195
221
  }
196
- function parseOptions(input) {
197
- if (input === null ||
198
- typeof input !== 'object' ||
199
- Array.isArray(input) ||
200
- types.isProxy(input) ||
201
- ![Object.prototype, null].includes(Object.getPrototypeOf(input)) ||
202
- Reflect.ownKeys(input).length)
203
- throw new TypeError('dokebi-module accepts no options');
204
- return Object.freeze({});
205
- }
206
222
  class ModuleGroupRuntime {
207
223
  names;
208
224
  constructor(names) {
@@ -215,9 +231,9 @@ class ModuleGroupRuntime {
215
231
  }
216
232
  export const createPlugin = definePlugin({
217
233
  name: 'dokebi-module',
218
- version: '0.1.2',
219
- core: '^0.2.0',
220
- options: parseOptions,
234
+ version: '0.4.0',
235
+ core: '^0.4.0',
236
+ options,
221
237
  entry: parseEntry,
222
238
  dependencies: ({ entry }) => (entry ?? []).map((module) => dependencyOf(module)),
223
239
  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.2",
3
+ "version": "0.4.0",
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",
36
- "@dokebi/web": "^0.1.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.1.3",
73
- "@dokebi/web": "0.1.2"
96
+ "@dokebi/controller": "0.4.0",
97
+ "@dokebi/template-ejs": "0.4.0",
98
+ "@dokebi/template-inertia": "0.4.0",
99
+ "@dokebi/web": "0.4.0"
74
100
  },
75
101
  "publishConfig": {
76
102
  "access": "public",