@dokebi/app 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,114 +1,267 @@
1
- # AI 작업 안내 — @dokebi/app 0.1.2
1
+ # AI guide — @dokebi/app 0.4.0
2
2
 
3
- 한 프로젝트에 앱을 여러 개 두고, **요청 도메인으로 앱과 템플릿을 고르는** 플러그인이다(D-0030). 앱 하나는 `src/apps/<앱>/` 폴더 하나이고 `defineApp`으로 정의한다. Node >=24.0.0, core ^0.2.0. 사람용 설명은 [README](README.md)다.
3
+ A plugin for several apps in one project that **picks the app and template by request domain** (D-0030). One app is one folder `src/apps/<app>/`, defined with `defineApp`. Node >=24.0.0, core ^0.4.0. The human-oriented description is the [README](README.md).
4
4
 
5
- ## 1. 설치와 만드는 것
5
+ ## 1. Install and what it creates
6
6
 
7
7
  ```sh
8
- npx dokebi add @dokebi/app # web·controller·template-ejs 함께 설치, 첫 앱 src/apps/main, localhost → main
8
+ npx dokebi add @dokebi/app # installs web, controller and template-ejs too; first app src/apps/main, localhost → main
9
9
  npx dokebi app add shop --domain a.com --domain www.a.com
10
- npx dokebi app add admin --inertia [--ssr] --domain admin.a.com # Vue 앱(+서버 렌더링)
10
+ npx dokebi app add admin --inertia [--ssr] --domain admin.a.com # a Vue app (+ server rendering)
11
11
  npx dokebi app link shop b.com --template christmas
12
12
  npx dokebi app unlink b.com
13
- npx dokebi app remove shop # 그 앱을 가리키는 도메인을 먼저 unlink. 폴더는 남는다
13
+ npx dokebi app remove shop # unlink the domains that point at the app first; the folder stays
14
14
  ```
15
15
 
16
- - 앱 폴더를 손으로 만들면 등록되지 않는다. 생성 등록 코드가 `.dokebi/state.json`의 앱 목록대로 `./apps/<앱>/app.ts`를 import해 entry `{ apps }`로 넘긴다.
17
- - Inertia·WebSocket을 쓰는 앱이 있으면 `@dokebi/template-inertia`, `@dokebi/websocket`을 따로 add한다(없으면 시작 실패: `App <앱> uses Inertia; add @dokebi/template-inertia`, `has sockets; add @dokebi/websocket`).
18
- - 이름 규칙: 앱·템플릿 `^[a-z][a-z0-9-]{0,31}$`, 도메인은 포트 없는 소문자 호스트.
16
+ > `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 …`.
19
17
 
20
- ## 2. 앱 폴더
18
+ - A hand-made app folder is not registered. The generated registration code imports `./apps/<app>/app.ts` for every app listed in `.dokebi/state.json` and passes them as entry `{ apps }`.
19
+ - **View engines and realtime transports are collected by name (D-0063 §5)**: app does not import template-ejs, template-inertia, websocket or sse. In setup it collects what registered plugins contributed to @dokebi/web's points `dokebi-web:view-engine` (`ejs`, `inertia`) and `dokebi-web:realtime` (`websocket`, `sse`). Adding a new transport plugin needs no change to app.
20
+ - When an app uses Inertia, WebSocket or SSE, add `@dokebi/template-inertia`, `@dokebi/websocket` or `@dokebi/sse` separately (otherwise the start fails: `VIEW_ENGINE_MISSING` `App <app> uses the inertia view engine; add @dokebi/template-inertia`, `REALTIME_UNAVAILABLE` `has sockets; add @dokebi/websocket` or `has event streams; add @dokebi/sse`).
21
+ - `add @dokebi/app` installs template-ejs because the first app `main` is an EJS skeleton (a required manifest dependency, at install time only). At run time app never calls template-ejs by name; it collects the `ejs` engine. When you assemble outside the CLI and an app uses `views`, register template-ejs yourself (it is no longer created automatically).
22
+ - Naming: apps and templates `^[a-z][a-z0-9-]{0,31}$`; domains are lower-case hosts without a port.
23
+
24
+ ## 2. App folder
21
25
 
22
26
  ```
23
- src/apps/<앱>/
27
+ src/apps/<app>/
24
28
  app.ts export default defineApp({ ... })
25
- routes.ts 라우트
26
- controllers/ 이 앱의 defineController
27
- models/ 일반 코드
28
- views/default/ 기본 템플릿(필수). EJS: home.ejs / Inertia: Layout.vue, Pages/*.vue
29
- views/<템플릿>/ 바꿀 파일만
30
- views/app.js (Inertia) 브라우저 진입 views/ssr.js (--ssr) 서버 진입
31
- sockets/ (선택) defineSocket
29
+ routes.ts routes
30
+ controllers/ this app's defineController tokens
31
+ models/ plain code
32
+ views/default/ the default template (required). EJS: home.ejs / Inertia: Layout.vue, Pages/*.vue
33
+ views/<template>/errors/404.ejs, errors/error.ejs (EJS, optional) error pages for browser pages (D-0074)
34
+ views/<template>/Pages/Error.vue (Inertia, with inertia.errorPage) the error page component
35
+ views/<template>/ only the files that change
36
+ views/app.js (Inertia) browser entry views/ssr.js (--ssr) server entry
37
+ sockets/ (optional) defineSocket
32
38
  ```
33
39
 
34
- 여러 앱이 같이 쓰는 기능은 앱에 두지 말고 기능 모듈(`npx dokebi module add <이름>` → `src/shared/modules/<이름>`, @dokebi/module)로 만든다.
40
+ Do not put features several apps share into an app; make a feature module (`npx dokebi module add <name>` → `src/shared/modules/<name>`, @dokebi/module).
35
41
 
36
- ## 3. 설정 `options.dokebi-app`
42
+ ## 3. Options `options.dokebi-app`
37
43
 
38
- | 키 | 형식 | 뜻 |
39
- |---|---|---|
40
- | `domains` (필수) | `{ <host>: { app, template? } }`, 최대 1024 | 호스트 → 앱·템플릿(생략은 default) |
41
- | `unknownDomain` | `reject`(기본) 또는 domains의 키 하나 | 모르는 호스트: 404, 또는 그 도메인의 설정으로 응답 |
44
+ | Key | Type | Default | Description |
45
+ |---|---|---|---|
46
+ | `domains` | `{ <host>: { app, template?, seal? } }`, up to 1024 | required | host → app and template (`default` when left out). `seal: true` seals that host's WebSocket frames and HTTP data (JSON bodies, Inertia pages, SSE data) (§4 seal hosts; default false) |
47
+ | `domains.<host>.app` | string | required | a defined app |
48
+ | `domains.<host>.template` | string | `default` | a folder under the app's views |
49
+ | `domains.<host>.seal` | boolean | false | seal this host (needs the `dokebi-seal` plugin) |
50
+ | `unknownDomain` | `reject` or a key of `domains` | `reject` | unknown hosts: 404, or answered with that domain's settings |
51
+ | `apps` | `{ <app>: { realtime?: { namespaces } } }` | none | per-app settings. **Keys must be defined app names** (otherwise the start fails with `UNKNOWN_APP`) |
52
+ | `apps.<app>.realtime.namespaces` | 1 to 32 names (`^[a-z][a-z0-9-]{0,31}$`, no duplicates) | `[<app>]` | this app's realtime spaces (§4 realtime namespaces, D-0061) |
42
53
 
43
- 호스트는 dokebi-web `requestHost()`(trustProxy면 `X-Forwarded-Host`)에서 포트를 떼고 소문자로 **정확히** 비교한다. 와일드카드·경로 접두사는 없다. 프락시 뒤면 dokebi-web `trustProxy`에 프락시 주소를 넣는다.
54
+ The host is dokebi-web's `requestHost()` (`X-Forwarded-Host` with trustProxy) without the port, in lower case, compared **exactly**. There are no wildcards or path prefixes. Behind a proxy, put the proxy addresses into dokebi-web `trustProxy`.
44
55
 
45
56
  ## 4. defineApp
46
57
 
47
- ```ts
58
+ ```ts snippet
48
59
  import { defineApp } from '@dokebi/app';
49
60
  import { dependency as db } from '@dokebi/db';
50
61
  import board from '../../shared/modules/board/module.ts';
51
62
  import { productController } from './controllers/product.ts';
52
63
 
53
64
  export default defineApp({
54
- requires: [db], // 이 앱이 쓰는 플러그인·모듈. 이 밖은 get 불가
65
+ requires: [db], // plugins and modules this app uses; nothing else can be read
55
66
  controllers: [productController],
56
- views: new URL('./views/', import.meta.url), // file: URL, views/default 필수
67
+ views: new URL('./views/', import.meta.url), // a file: URL; views/default is required
57
68
  inertia: { title: 'Shop', vite: { manifest: 'dist/.vite/manifest.json', entry: 'src/apps/shop/views/app.js', base: '/build/' } },
58
- modules: { '/board': board }, // 모듈의 routes·sockets·views를 이 앱 도메인에 붙임
59
- shared: (request, page) => ({ menu: MENU }), // 모든 EJS 페이지 데이터 밑에 합침(페이지 값이 이김)
69
+ modules: { '/board': board }, // mounts the module's routes, sockets and views on this app's domains
70
+ shared: (request, page) => ({ menu: MENU }), // merged under every EJS page's data (page values win)
60
71
  routes(route, app) {
61
72
  route.get('/', async (request, reply, page) =>
62
73
  page.view.reply(reply, 'home', { items: await app.controller(productController).list() }, { layout: 'layouts/main' }),
63
74
  );
64
75
  },
65
76
  sockets: (app) => [chatSocket(app)],
77
+ events: (app) => [orderStream(app)], // @dokebi/sse routes (SseRoute); same constraint and namespaces as sockets
66
78
  setup(app) {}, start(app) {}, drain(app) {},
67
79
  });
68
80
  ```
69
81
 
70
- - `route`: `get`·`post`·`put`·`patch`·`delete(url, handler, options?)`, `route(options)`. 핸들러는 `(request, reply, page)`.
71
- - `page`: `{ app: { name, template, domain }, module, base, view, inertia }`. 앱 라우트에서 `module`은 undefined, `base`는 `''`.
72
- - `view`: EJS 렌더러. 찾는 순서 `<앱>/<템플릿>` → `<앱>/default` → `src/shared/views`(레이아웃·`$include`도 같음).
73
- - `inertia`: 앱의 문서 설정을 쓰는 Inertia 렌더러(앱에 `inertia`가 있을 때). 공통 props에 `app`(`{ name, template, domain }`)을 더한다.
74
- - `app`(AppContext): `name`·`logger`·`signal`·`get`·`getDependency`·`getOptionalDependency`·`controller`·`defer`. **`requires`에 없는 것을 꺼내면 오류**(`App <앱> does not list <플러그인> in requires`). 컨트롤러 팩토리도 같은 제한을 받는다.
75
- - `inertia.ssr: { bundle: 'dist/ssr/<앱>/ssr.js' }`면 첫 HTML을 서버에서 그린다(D-0039, template-inertia AI.md).
82
+ - `route`: `get`, `post`, `put`, `patch`, `delete(url, handler, options?)` and `route(options)`. Handlers are `(request, reply, page)`. Options are `WebRoute` options without `handler` and `constraints` (so `seal` works).
83
+ - `page`: `{ app: { name, template, domain }, module, base, view, inertia, sealed }`. In app routes `module` is undefined and `base` is `''`.
84
+ - `view`: the EJS renderer. Lookup order `<app>/<template>` → `<app>/default` → `src/shared/views` (layouts and `$include` too).
85
+ - `inertia`: an Inertia renderer with the app's document settings (when the app has `inertia`). It adds `app` (`{ name, template, domain }`) and `sealed` to the shared props.
86
+ - `sealed`: whether the request host has `seal: true`. EJS data gets it as `sealed` too (the app's `shared` and the page data win).
87
+ - `app` (AppContext): `name`, `logger`, `signal`, `get`, `getDependency`, `getOptionalDependency`, `controller`, `defer`, `realtime(namespace?)` (§4 realtime namespaces). **Reading something not in `requires` is an error** (`NOT_REQUIRED`: `App <app> does not list <plugin> in requires`). Controller factories have the same limit.
88
+ - `inertia.ssr: { bundle: 'dist/ssr/<app>/ssr.js' }` renders the first HTML on the server (D-0039, see the template-inertia AI.md).
89
+ - `inertia.errorPage: 'Error'` renders that page component for the error answers of this app's Inertia visits and page loads (D-0074; `false` turns off a plugin-level default). The `app add --inertia` skeleton sets it and creates `views/default/Pages/Error.vue`.
90
+
91
+ ### Errors on an app's hosts (D-0074)
92
+
93
+ Every error answer on an app's host — a thrown error, a refused schema, an unknown route (404) — goes through this app first (a dokebi-web error responder):
94
+
95
+ 1. **Inertia** (`inertia` set): the app's scope answers an Inertia validation error with the redirect back (`errors` in the session flash, template-inertia §3.3) and other errors with `inertia.errorPage` when set.
96
+ 2. **EJS error views** (an HTML answer: a browser navigation or an HTML form post): `errors/<status>` (for example `errors/404.ejs`), else `errors/error`, looked up like any page (`<app>/<template>` → `<app>/default` → `src/shared/views`, so a shared `errors/404.ejs` serves every app), with the app's `shared` data and the default layout. Data: `{ status, title ('404 Not Found'), error, message, hint, fields ([{ field, message }], empty unless 422), fix, stack }` — `fix` and `stack` (5xx) only outside production, otherwise null.
97
+ 3. Otherwise dokebi-web's own answer: JSON for scripts (Inertia, `fetch`, XHR, Bearer, JSON bodies), a small HTML page for browser pages.
98
+
99
+ JSON clients never get a view. A view that fails to render (a missing data field, a broken include) falls back to web's page and logs `error` `Web error responder failed` (`WEB_ERROR_RESPONDER_FAILED`, once per route and interval). Refuse input in handlers with `throw validationError({ name: 'Already taken' })` from @dokebi/web (422, the same answer as a refused schema). Debug: `App error view rendered` (app, template, view, status).
100
+
101
+ ### Mounting modules (D-0032)
102
+
103
+ - `modules: { '/prefix': module }`. The prefix is `/` or `/a/b` (lower-case letters, digits, `.`, `_`, `~`, `-`).
104
+ - The module's routes, sockets and SSE routes (`events`, since @dokebi/module 0.1.3) are registered on this app's domains under the prefix, and `page.module` and `page.base` are filled in. Several apps can mount the same module under different prefixes. A mounted module's API is readable with `app.get(module)` without listing it in `requires`.
105
+ - The module's root route (`route.get('/')`) answers both `/prefix` and `/prefix/`, so links and form actions may use either. Other paths match exactly (`/prefix/items/7/` is 404).
106
+ - Module views are looked up in this order, so module pages render inside the app layout. To change a module page, an app puts the same file into `views/<template>/<module>/`.
107
+ 1. `<app>/<template>/<module>`
108
+ 2. `<app>/default/<module>`
109
+ 3. the module's `<template>`
110
+ 4. the module's `default`
111
+ 5. the app's views
112
+ 6. shared views
113
+
114
+ ### Routing and WebSocket
115
+
116
+ - App routes are registered with the Fastify constraint `dokebiApp` (`APP_CONSTRAINT`), so several apps can own the same path. Routes without the constraint (health checks, `@dokebi/router` APIs) answer on every domain.
117
+ - App sockets use the same constraint. The hub tenant is `<namespace>:<tenant>` (the default namespace is the app name, so without settings it is `<app>:<tenant>`), and the session's `identity.tenant` holds that value. Messages use the `{ type, data, id? }` shape of `defineSocket`.
118
+ - App `events` (SSE, @dokebi/sse) attach with the same constraint and tenant rule (`stream.tenant` is `<namespace>:<tenant>`). Without @dokebi/sse the start fails with `App <app> has event streams; add @dokebi/sse`. The `events` of a mounted module attach under the module prefix with the same rule (`Module <module> (app <app>) has event streams; add @dokebi/sse`).
119
+
120
+ ### Realtime namespaces (0.2.0, [D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md))
121
+
122
+ Presence lists, broadcasts and SSE publishing are divided by **namespace, not by app**. Apps with the same namespace share presence, broadcasts and chat. This is not the hub's `namespace` (a Redis key prefix, per cluster).
123
+
124
+ ```yaml
125
+ dokebi-app:
126
+ domains:
127
+ www.a.com: { app: shop }
128
+ m.a.com: { app: mobile }
129
+ admin.a.com: { app: admin }
130
+ apps:
131
+ shop: { realtime: { namespaces: [front] } }
132
+ mobile: { realtime: { namespaces: [front] } } # the same space as shop
133
+ admin: { realtime: { namespaces: [admin, front] } } # the first is the default for its own sockets
134
+ ```
135
+
136
+ - **One connection = one namespace**: the hub tenant of a socket or SSE stream is `<namespace>:<authenticated tenant>`. When `authenticate` returns a `namespace` (it must be in the app's list) the connection joins that space, otherwise the first one in the list. Outside the list it gets 401 and the warn `Realtime namespace refused` (code `NAMESPACE_FORBIDDEN`, `app`, `kind` (socket or stream), `path`, `namespace`, `allowed`). app removes `namespace`, so it is not in the session's `identity` or `stream.identity` (the space shows as the prefix of `identity.tenant`).
137
+ - **The server-side handle** `app.realtime(namespace?)` (`RealtimeHandle`; the first namespace when left out; outside the list it throws `NAMESPACE_FORBIDDEN` at once). The tenant of a target `{ tenant?, member?, room? }` is the authenticated tenant without the prefix. **Leaving out tenant means every tenant of that namespace**.
138
+ - `list(filter?)` → connections (`tenant` (no prefix), `member`, `connection`, `ownerEpoch`, `clientId?`, `rooms`, `metadata`). With a tenant it asks the hub (the whole cluster; failures carry the hub's code); without one it reads the presence this server received (every server, possibly slightly late; an empty list before start).
139
+ - `send(target, type, data?)` → the same `{ type, data }` text frame as defineSocket broadcasts, through the hub (at most once; sealed per sealed socket). Receipt `{ ids, recipients }`. Without a tenant, one broadcast per tenant.
140
+ - `kick(target, code?, reason?)` → closes those connections on every server (4000–4999, default 4403).
141
+ - `onPresence(listener)` → joins and leaves of that space's tenants (`{ tenant, joined, left }`, tenant without prefix). Call the returned function to stop. A listener that throws or rejects is logged by websocket as error `PRESENCE_LISTENER_FAILED`.
142
+ - `publish(target, event, data?)` → @dokebi/sse publishing (that space's streams; every process when there is a bus). Without a tenant, every process writes to its own streams whose tenant has the prefix.
143
+ - When the needed transport is missing it throws `REALTIME_UNAVAILABLE` (list, send, kick and onPresence need the `websocket` transport = @dokebi/websocket; publish needs the `sse` transport = @dokebi/sse).
144
+ - **The app decides permissions**: within a space, who sees whom is decided by rooms, roles and app code. Namespaces only divide spaces. For an admin app that must not appear in the front presence list, keep its own sockets in its own space (`admin`) and gather data with `realtime('front')` in server code.
145
+ - Module sockets and SSE routes (`events`) follow the namespace rules of the app they are mounted on. The module context (ModuleContext) has no `realtime` (a module can be mounted on several apps, so it is not an app context).
76
146
 
77
- ### 모듈 붙이기(D-0032)
147
+ #### Example: an admin app that watches two front spaces and chats with users
78
148
 
79
- - `modules: { '/접두사': 모듈 }`. 접두사는 `/` 또는 `/a/b`(소문자·숫자·`.`·`_`·`~`·`-`).
80
- - 모듈의 라우트·소켓이 이 앱의 도메인·접두사로 등록되고 `page.module`·`page.base`가 채워진다. 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
81
- - 모듈 화면 찾는 순서는 다음과 같다. 그래서 모듈 화면이 앱 레이아웃 안에 그려진다. 앱이 모듈 화면을 바꾸려면 `views/<템플릿>/<모듈>/`에 같은 파일을 둔다.
82
- 1. `<앱>/<템플릿>/<모듈>`
83
- 2. `<앱>/default/<모듈>`
84
- 3. 모듈의 `<템플릿>`
85
- 4. 모듈의 `default`
86
- 5. 앱 views
87
- 6. 공통
149
+ ```yaml
150
+ dokebi-app:
151
+ apps:
152
+ shop: { realtime: { namespaces: [shop] } }
153
+ blog: { realtime: { namespaces: [blog] } }
154
+ admin: { realtime: { namespaces: [admin, shop, blog] } }
155
+ ```
156
+
157
+ ```ts snippet
158
+ // src/apps/admin/app.ts
159
+ import { type AppContext, defineApp } from '@dokebi/app';
160
+ import { defineSocket } from '@dokebi/websocket';
161
+ import { staffOf } from './models/staff.ts';
162
+
163
+ const WATCHED = ['shop', 'blog'] as const;
164
+ type Watched = (typeof WATCHED)[number];
165
+
166
+ export default defineApp({
167
+ // The admin screens join the admin space only (they do not appear in the front presence list).
168
+ sockets: (app) => [
169
+ defineSocket({
170
+ path: '/ws',
171
+ authenticate: async (request) => {
172
+ const staff = await staffOf(request); // check the staff session; undefined → 401
173
+ return staff && { tenant: 'staff', member: staff.id, namespace: 'admin' };
174
+ },
175
+ on: {
176
+ // When a screen opens, read the current users of both spaces at once.
177
+ 'users.list': async () =>
178
+ Object.fromEntries(
179
+ await Promise.all(WATCHED.map(async (space) => [space, await app.realtime(space).list()])),
180
+ ),
181
+ // Admin → one front user (all of that person's tabs).
182
+ 'chat.send': async (data, socket) => {
183
+ const { space, tenant, member, text } = data as { space: Watched; tenant: string; member: string; text: string };
184
+ if (!WATCHED.includes(space)) throw Object.assign(new Error('bad space'), { code: 'BAD_SPACE' });
185
+ const receipt = await app.realtime(space).send({ tenant, member }, 'chat.message', {
186
+ from: socket.identity.member, text,
187
+ });
188
+ return { recipients: receipt.recipients.length }; // 0: the user already left
189
+ },
190
+ // Notice: every tenant of that space.
191
+ 'notice.send': async (data) => {
192
+ const { space, text } = data as { space: Watched; text: string };
193
+ await app.realtime(space).send({}, 'notice', { text });
194
+ },
195
+ },
196
+ }),
197
+ ],
198
+ // Forward the front's joins and leaves to the admin screens in real time.
199
+ start(app) {
200
+ for (const space of WATCHED) {
201
+ const stop = app.realtime(space).onPresence((change) =>
202
+ app.realtime('admin').send({ tenant: 'staff' }, 'users.changed', { space, ...change }),
203
+ );
204
+ app.defer(stop);
205
+ }
206
+ },
207
+ });
208
+ ```
209
+
210
+ - The front apps' (shop, blog) sockets need no change. To deliver a user's reply to the staff screens, set shop's namespaces to `[shop, admin]` and have a shop handler call `app.realtime('admin').send({ tenant: 'staff' }, 'chat.reply', …)` (shop comes first, so user sockets stay in the shop space). shop's server code can then write to the admin space, so limit in app code what it sends.
211
+ - When an admin screen should also appear as a front user (staff present in a chat room), let that screen's socket join with `namespace: 'shop'`.
88
212
 
89
- ### 라우팅과 WebSocket
213
+ ### Seal hosts (0.2.0, D-0059 §4)
214
+
215
+ ```yaml
216
+ dokebi-app:
217
+ domains:
218
+ secure.example.com: { app: shop, seal: true } # every frame of this host's sockets is sealed
219
+ www.example.com: { app: shop } # plain, even for the same app and socket path
220
+ ```
90
221
 
91
- - 앱 라우트는 Fastify 제약 `dokebiApp`(`APP_CONSTRAINT`)으로 등록된다. 여러 앱이 같은 경로를 가질 수 있다. 제약 없는 라우트(헬스 체크, `@dokebi/router` API)는 모든 도메인에서 응답한다.
92
- - 앱 소켓도 같은 제약을 쓴다. 허브 tenant는 `<앱>:<tenant>`로 앱마다 나뉘며 세션 `identity.tenant`도 그 값이다. 메시지는 `defineSocket`의 `{ type, data, id? }` 형식.
222
+ - app fills an app socket's `route.seal` from the request host (only when at least one of that app's hosts is sealed; a route's own `seal` is kept on plain hosts too). The **`@dokebi/seal` plugin** (`dokebi-seal`) owns the algorithm and the static files under `/dokebi/seal/*`. This public package only looks it up by name.
223
+ - Pages: when `sealed` is true, load `/dokebi/seal/seal.mjs` and `socket.mjs`, call `initSeal()`, then `connectChannel({ path, seal: sealBridge })`. (Passing the bridge always is fine: the client offers both `dokebi.seal` and `dokebi.plain`, and a plain host picks `dokebi.plain` and runs in plain text. `sealed` decides whether to fetch the wasm early.) Connecting to a seal host without a bridge closes with 4415 (no reconnect); an unopenable frame closes with 4400. Details are in @dokebi/websocket AI.md §4a and the @dokebi/seal README.
224
+ - Same app = same hub tenant, so a broadcast sent on a seal host reaches plain-host sockets in plain text and sealed sockets sealed.
225
+ - **HTTP (D-0062)**: when sealed domains exist, app registers `sealRequests(is the host sealed)` with dokebi-web. Every HTTP request to such a host (app routes or `/api/*` routes a module put directly on web) gets sealed JSON responses, 415 for plain JSON bodies, a sealed Inertia first page and sealed SSE data. An app route with `seal: false` (`route.post('/hook', handler, { seal: false })`) stays plain (webhooks, server to server), as does dokebi-web `sealExclude`. EJS HTML stays as it is; give routes that take native forms `seal: false`. Inertia scopes of apps on sealed domains get `sealed: true`, and combining that with SSR fails the start (`SEAL_SSR_CONFLICT`). Browser: `sealInertia`, `sealedFetch` and `currentSealBridge` of `@dokebi/seal/http` (the CLI template `views/app.js` loads `/dokebi/seal/http.mjs` and calls `sealInertia(http)` on sealed pages).
93
226
 
94
227
  ## 5. API
95
228
 
96
- `createPlugin`의 API는 `{ names, resolve(request) }`. `resolve`는 요청의 `{ name, template, domain }` 또는 모르는 호스트면 undefined. `APP_CONSTRAINT`, `hostOf(request)`(Host 헤더에서 포트 뗀 값, 프락시 무시)도 내보낸다. 앱 판정에는 `resolve`를 쓴다.
229
+ The API of `createPlugin` is `{ names, resolve(request) }` (`AppGroupApi`). `resolve` returns the request's `{ name, template, domain }` or undefined for an unknown host. Also exported: `APP_CONSTRAINT`, `hostOf(request)` (the Host header without the port, ignoring proxies), `withoutPort(host)`, `options` (the `defineOptions` declaration) and the types (`AppDefinition`, `AppContext`, `AppPage`, `RealtimeHandle`, …). Use `resolve` to decide the app.
230
+
231
+ ## 6. Errors and what is refused at start
232
+
233
+ <!-- docs-check: complete-error-codes AppErrorCode -->
234
+ `AppError` (`plugin: 'dokebi-app'`, all with a `fix`):
235
+
236
+ | Code | When |
237
+ |---|---|
238
+ | `INVALID_DEFINITION` | unknown fields or bad values in `defineApp`, a bad module prefix, a module not made with `defineModule`, a bad requires item |
239
+ | `INVALID_ENTRY` | the entry is not `{ apps: { <name>: defineApp(...) } }` (the cause of `INVALID_PLUGIN_INPUT`) |
240
+ | `UNKNOWN_APP` | a domain pointing at an undefined app, or `apps.<app>` naming an undefined app |
241
+ | `SEAL_PROVIDER_MISSING` | a `seal: true` domain exists but the `dokebi-seal` plugin does not (even without sockets) |
242
+ | `VIEW_ENGINE_MISSING` | an app's `views` or module views without the `ejs` engine, or `inertia` without the `inertia` engine |
243
+ | `VIEWS_MISSING` | `views/default/` or the `views/<template>/` a domain picked is missing (the original file error is the `cause`), or `page.view` renders in an app without views |
244
+ | `REALTIME_UNAVAILABLE` | `sockets` without the `websocket` transport, `events` without the `sse` transport, or that call on a `realtime()` handle |
245
+ | `NAMESPACE_FORBIDDEN` | `realtime(namespace)` outside the app's list |
246
+ | `INVALID_TARGET` | a realtime target that is not `{ tenant?, member?, room? }` (1 to 256 characters) |
247
+ | `NOT_REQUIRED` | reading a plugin that is not in `requires` |
248
+ | `NOT_READY` | `controller()` before setup |
97
249
 
98
- ## 6. 시작 때 거절되는 것
250
+ Option errors (missing `domains`, a bad host, app name or `seal`, an `unknownDomain` that is neither reject nor a key of domains, bad `realtime.namespaces` — empty, duplicate, malformed or 33 or more) are core `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS` with paths in `details.issues`). The options are a `defineOptions` declaration in `src/options.ts`; the build writes `options.schema.json`.
99
251
 
100
- 없는 앱을 가리키는 도메인, 등록 안 된 앱, `views` 폴더나 `views/default/`·도메인이 고른 `views/<템플릿>/` 누락(원래 파일 오류는 `cause`), `defineApp`의 모르는 필드, 잘못된 모듈 접두사, `defineModule`로 만들지 않은 모듈.
252
+ warn: authentication picked a namespace outside the list (`Realtime namespace refused`, code `NAMESPACE_FORBIDDEN`, 401).
101
253
 
102
- debug 로그(D-0047): `App domains configured`(도메인 → 앱/템플릿, 64개까지)·`App set up`(requires·템플릿·inertia·모듈·라우트·소켓 수·ms)·`App start finished`·`App drain finished`, 요청마다는 설정에 없는 호스트일 때만 `App domain not configured`(debug가 켜졌을 때만 만든다).
254
+ Debug logs (D-0047): `App domains configured` (domain → app/template, `(sealed)` marks and the number of sealed domains `sealed`, up to 64), `App set up` (requires, templates, inertia, modules, routes, sockets, the number of SSE routes `events`, `namespaces`, ms), `App realtime handle created` (app, namespace, whether websocket and sse exist; once per namespace), per connection `Realtime namespace chosen` (only when debug is on), `App start finished`, `App drain finished`; per request only for a host missing from the settings, `App domain not configured` (built only when debug is on).
103
255
 
104
- ## 7. 주의 사항
256
+ ## 7. Cautions
105
257
 
106
- - 코드에서 Host 헤더로 분기하지 않는다. 도메인 → 앱·템플릿은 dokebi.yaml에만 두고 핸들러는 `page.app`을 읽는다.
107
- - `views/default/`를 지우지 않는다. 템플릿 폴더에는 바꿀 파일만 둔다.
108
- - 앱끼리 서로 import하지 않는다. 공통 코드는 `src/shared/`(모델·뷰) 또는 모듈.
109
- - 생성 등록 코드와 `.dokebi/state.json`을 고치지 않는다. 앱·도메인 변경은 `dokebi app` 명령으로 한다(dokebi.example.yaml에도 같이 남는다).
110
- - Inertia 앱의 빌드 파일이 없으면 시작이 실패한다. `npm run build`를 먼저 한다.
258
+ - Do not branch on the Host header in code. Keep domain → app/template in dokebi.yaml only; handlers read `page.app`.
259
+ - Do not delete `views/default/`. Template folders hold only the files that change.
260
+ - Apps do not import each other. Shared code goes into `src/shared/` (models, views) or a module.
261
+ - Do not edit the generated registration code or `.dokebi/state.json`. Change apps and domains with `dokebi app` commands (they are recorded in dokebi.example.yaml too).
262
+ - An Inertia app without its build files fails to start. Run `npm run build` first.
263
+ - Do not answer validation with `reply.code(422).send(…)` by hand: `throw validationError({ field: 'message' })` so Inertia forms get the redirect with `errors` and other clients the standard `fields`/`errors` body (D-0074).
111
264
 
112
- ## 8. 근거
265
+ ## 8. References
113
266
 
114
- `examples/25-playground`(vue·ejs 두 앱, 도메인·템플릿, 모듈, 소켓), `examples/26-scaffold`(CLI 생성 반복 검증), D-0030·D-0031·D-0032·D-0039.
267
+ `examples/25-playground` (vue, ejs and admin apps; domains and templates; modules; sockets; namespaces: admin watches the vue and ejs users, chats and publishes SSE), `examples/26-scaffold` (repeated checks of CLI generation), D-0030, D-0031, D-0032, D-0039, D-0059 (seal hosts — the playground's `sealed.localhost`; real server and Chromium checks are @dokebi/seal's `seal:test` and `seal:browser-check`), D-0061, D-0062.
package/README.md CHANGED
@@ -1,102 +1,137 @@
1
- # @dokebi/app 0.1.2
1
+ # @dokebi/app 0.4.0
2
2
 
3
- 한 프로젝트 안에 여러 앱을 두고, 요청 도메인으로 앱과 템플릿을 고르는 선택 플러그인이다. Node >=24.0.0, core ^0.2.0의 선택 패키지다(npm 공개). 설계는 [D-0030](../../docs/decisions/D-0030-multi-app-and-domains.md)이다.
3
+ An optional plugin for several apps in one project that picks the app and template by request domain. An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). The design is [D-0030](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0030-multi-app-and-domains.md).
4
4
 
5
- ## 설치
5
+ ## Install
6
6
 
7
7
  ```sh
8
8
  dokebi add @dokebi/app
9
9
  ```
10
10
 
11
- 필수 플러그인 dokebi-web·dokebi-controller·dokebi-template-ejs가 같은 변경에서 함께 설치되고(결과 `autoInstalled`), 첫 앱 `src/apps/main`과 `domains: { localhost: { app: main } }`가 만들어진다. 앱을 더 만들 때:
11
+ The required plugins dokebi-web, dokebi-controller and dokebi-template-ejs are installed in the same change (result `autoInstalled`), and the first app `src/apps/main` and `domains: { localhost: { app: main } }` are created. template-ejs comes along at install time because the first app is an EJS skeleton. At run time app collects view engines (`ejs`, `inertia`) and realtime transports (`websocket`, `sse`) by name from @dokebi/web's contribution points and never imports those packages (D-0063 §5). Errors are `AppError` (`VIEW_ENGINE_MISSING`, `REALTIME_UNAVAILABLE` and so on, [AI.md](AI.md) §6). To add more apps:
12
12
 
13
13
  ```sh
14
14
  dokebi app add shop --domain a.com --domain www.a.com
15
- dokebi app link shop b.com --template christmas # 기존 앱에 도메인 더하기
15
+ dokebi app link shop b.com --template christmas # add a domain to an existing app
16
16
  dokebi app unlink b.com
17
17
  dokebi app list
18
- dokebi app remove shop # 그 앱을 가리키는 도메인을 먼저 지운다. 폴더는 남는다.
18
+ dokebi app remove shop # remove the domains pointing at the app first; the folder stays
19
19
  ```
20
20
 
21
- 도메인 연결은 dokebi.yaml과 dokebi.example.yaml에 함께 남는다. Inertia 화면이나 WebSocket을 쓰는 앱이 있으면 `dokebi add @dokebi/template-inertia`, `dokebi add @dokebi/websocket`을 따로 한다.
21
+ Domain links are recorded in both dokebi.yaml and dokebi.example.yaml. When an app uses Inertia pages, WebSocket or SSE, run `dokebi add @dokebi/template-inertia`, `dokebi add @dokebi/websocket` or `dokebi add @dokebi/sse` separately.
22
22
 
23
- ## 폴더 구조
23
+ ## Folder layout
24
24
 
25
- [D-0031](../../docs/decisions/D-0031-project-layout.md)을 따른다. 앱 폴더는 `dokebi app add`가 만든다.
25
+ It follows [D-0031](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0031-project-layout.md). `dokebi app add` creates the app folder.
26
26
 
27
27
  ```
28
- src/apps/<앱>/
28
+ src/apps/<app>/
29
29
  app.ts export default defineApp({ ... })
30
- routes.ts 라우트
31
- controllers/ defineController 토큰(이 앱 전용)
32
- models/ 일반 코드(플러그인 아님)
33
- views/default/ 기본 템플릿(필수). EJS 앱은 home.ejs, Inertia 앱은 Layout.vue·Pages/Home.vue
34
- views/<템플릿>/ 바꿀 파일만 둔다. 없으면 default → 공통 src/shared/views 순서로 찾는다.
35
- views/app.js (Inertia 앱만) Vite 진입: 템플릿별 페이지·레이아웃을 같은 순서로 찾는다
36
- sockets/ 이 앱의 WebSocket(defineSocket), 필요할 때 만든다
37
- src/shared/ 여러 앱이 같이 쓰는 컨트롤러·모델·모듈(dokebi-module)·공통 뷰
30
+ routes.ts routes
31
+ controllers/ defineController tokens (this app only)
32
+ models/ plain code (not plugins)
33
+ views/default/ the default template (required). EJS apps: home.ejs; Inertia apps: Layout.vue, Pages/Home.vue
34
+ views/<template>/ only the files that change; missing files are looked up in default, then shared src/shared/views
35
+ views/app.js (Inertia apps only) Vite entry: finds per-template pages and layouts in the same order
36
+ sockets/ this app's WebSocket routes (defineSocket), created when needed
37
+ src/shared/ controllers, models, modules (dokebi-module) and views shared by several apps
38
38
  ```
39
39
 
40
- - `dokebi app add <앱> --inertia`는 Inertia 골격을 만들고 빌드 준비(`vite.config.ts`, `build` 스크립트, Vite·Vue 개발 의존성, `.gitignore`의 `dist/`)도 한다. 그 뒤 `npm run build`를 한다.
41
- - `--ssr`을 더하면([D-0039](../../docs/decisions/D-0039-inertia-ssr.md)) 서버 진입 `views/ssr.js`, app.ts의 `inertia.ssr: { bundle: 'dist/ssr/<앱>/ssr.js' }`, 프로젝트의 `vite.ssr.config.ts`를 만들고 `build`가 브라우저·서버 빌드를 함께 한다(앞서 만든 `vite build`만 있던 스크립트는 둘 다로 바뀌고, 직접 쓴 스크립트는 `BUILD_SCRIPT_KEPT`로 남긴다). 브라우저 진입 `views/app.js`는 서버가 그린 페이지를 `createSSRApp`으로 hydration한다. 레이아웃은 페이지 모듈을 바꾸지 않고 `layout` 옵션으로 고른다(서버에서 템플릿이 다른 요청이 동시에 그려지므로).
42
- - 빌드 파일은 @dokebi/template-inertia가 `/build/`로 내보낸다. 자세한 내용은 [CLI 문서](../../docs/cli/README.md)에 있다.
40
+ - `dokebi app add <app> --inertia` creates an Inertia skeleton and prepares the build (`vite.config.ts`, the `build` script, Vite and Vue dev dependencies, `dist/` in `.gitignore`). Run `npm run build` afterwards.
41
+ - With `--ssr` ([D-0039](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0039-inertia-ssr.md)) it also creates the server entry `views/ssr.js`, `inertia.ssr: { bundle: 'dist/ssr/<app>/ssr.js' }` in app.ts and the project's `vite.ssr.config.ts`, and `build` runs both the browser and the server build (a previously generated script with only `vite build` becomes both; a script you wrote yourself is kept and reported as `BUILD_SCRIPT_KEPT`). The browser entry `views/app.js` hydrates the server-rendered page with `createSSRApp`. Layouts are chosen with the `layout` option instead of changing the page module (requests with different templates render on the server at the same time).
42
+ - @dokebi/template-inertia serves the build files under `/build/`. Details are in the [CLI docs](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/cli/README.md).
43
43
 
44
- 앱 이름은 폴더 이름이다. 생성 등록 코드(src/dokebi.generated.ts)가 `.dokebi/state.json`의 앱 목록대로 `./apps/<앱>/app.ts`를 가져와 이 플러그인의 entry `{ apps: { <앱>: ... } }`로 넘긴다.
44
+ The app name is the folder name. The generated registration code (src/dokebi.generated.ts) imports `./apps/<app>/app.ts` for every app listed in `.dokebi/state.json` and passes them to this plugin as entry `{ apps: { <app>: ... } }`.
45
45
 
46
- ## 설정
46
+ ## Configuration
47
47
 
48
48
  ```yaml
49
49
  dokebi-app:
50
50
  domains:
51
- a.com: { app: shop } # template 생략 = default
51
+ a.com: { app: shop } # no template = default
52
52
  b.com: { app: shop, template: christmas }
53
53
  c.com: { app: admin }
54
- unknownDomain: reject # 기본. 또는 domains의 키 하나(그 설정으로 응답)
54
+ s.com: { app: shop, seal: true } # seal every WebSocket frame of this host (below)
55
+ unknownDomain: reject # default; or a key of domains (answered with those settings)
56
+ apps: # optional; keys are defined app names (otherwise the start fails with UNKNOWN_APP)
57
+ shop: { realtime: { namespaces: [front] } } # default [<app>]
58
+ admin: { realtime: { namespaces: [admin, front] } } # see "Realtime namespaces" below
55
59
  ```
56
60
 
57
- dokebi-web `requestHost()`가 준 호스트(신뢰 프락시면 `X-Forwarded-Host`)에서 포트를 떼고 소문자로 정확히 비교한다. 프락시 뒤라면 dokebi-web `trustProxy`에 프락시 주소를 적는다. 와일드카드·경로 접두사는 아직 없다. 시작할 때 없는 앱, 없는 템플릿 폴더, `views/default/` 누락을 거부한다.
61
+ The host from dokebi-web's `requestHost()` (`X-Forwarded-Host` from a trusted proxy) is compared exactly, without the port and in lower case. Behind a proxy, list the proxy addresses in dokebi-web `trustProxy`. There are no wildcards or path prefixes yet. The start refuses unknown apps, missing template folders and a missing `views/default/`.
58
62
 
59
63
  ## defineApp
60
64
 
61
- ```ts
65
+ ```ts snippet
62
66
  import { defineApp } from '@dokebi/app';
63
67
  import { dependency as db } from '@dokebi/db';
64
68
 
65
69
  export default defineApp({
66
- requires: [db], // 이 앱이 쓰는 플러그인·공통 모듈
70
+ requires: [db], // plugins and shared modules this app uses
67
71
  controllers: [productController],
68
72
  views: new URL('./views/', import.meta.url),
69
73
  inertia: { vite: { manifest: 'dist/.vite/manifest.json', entry: 'src/apps/shop/views/app.js', base: '/build/' } },
70
- modules: { '/board': board }, // 기능 모듈을 접두사로 붙인다(D-0032)
71
- shared: (request, page) => ({ menu: MENU }), // 이 앱의 모든 EJS 페이지에 합칠 데이터
74
+ modules: { '/board': board }, // mounts a feature module under a prefix (D-0032)
75
+ shared: (request, page) => ({ menu: MENU }), // data merged into every EJS page of this app
72
76
  routes(route, app) {
73
77
  route.get('/', (request, reply, page) =>
74
78
  page.view.reply(reply, 'home', app.controller(productController).list(), { layout: 'layouts/main' }),
75
79
  );
76
80
  },
77
- sockets: (app) => [chatSocket(app)], // defineSocket(...) 결과
81
+ sockets: (app) => [chatSocket(app)], // results of defineSocket(...)
82
+ events: (app) => [ordersStream(app)], // @dokebi/sse routes (SseRoute)
78
83
  setup(app) {}, start(app) {}, drain(app) {},
79
84
  });
80
85
  ```
81
86
 
82
- - 핸들러의 `page`는 `{ app: { name, template, domain }, module, base, view, inertia }`다. 앱 라우트에서 `module`은 undefined, `base`는 `''`다. `view`는 `<앱>/<템플릿>` → `<앱>/default` → 공통 src/shared/views 순서로 찾는 EJS 렌더러이고, 레이아웃과 `$include`도 같은 순서를 따른다. `inertia`는 앱의 문서 설정(Vite 진입점 등)을 쓰고 공통 props에 `app`을 더한다.
83
- - **모듈 붙이기([D-0032](../../docs/decisions/D-0032-feature-modules.md)):** `modules: { '/접두사': 모듈 }`. 모듈은 `defineModule`로 만든 것이다.
84
- - 모듈의 `routes`는 이 앱의 라우트 제약과 접두사로 등록된다. 핸들러 `page.module`·`page.base`가 채워진다.
85
- - 모듈의 `sockets`는 접두사 아래 경로로 등록된다. tenant는 `<앱>:<tenant>`다.
86
- - 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
87
- - 접두사는 `/` 또는 `/a/b`(소문자·숫자·`.`·`_`·`~`·`-`)다.
88
- - 모듈 페이지의 화면 찾는 순서는 다음과 같다. 그래서 모듈 화면은 앱 레이아웃 안에 그려진다.
89
- 1. `<앱>/<템플릿>/<모듈>`
90
- 2. `<앱>/default/<모듈>`
91
- 3. 모듈의 `<템플릿>`
92
- 4. 모듈의 `default`
93
- 5. 앱 views
94
- 6. 공통
95
- - **`shared(request, { app })`:** 이 앱이 그리는 모든 EJS 페이지(앱 라우트와 모듈 라우트)의 데이터 밑에 합쳐진다. 겹치는 키는 페이지 데이터가 이긴다. 레이아웃이 쓰는 메뉴·사용자 같은 앱 데이터를 여기에 둔다. Inertia 공통 props에 해당한다.
96
- - 앱 문맥(`app`)의 `get`·`getDependency`는 `requires`에 넣은 플러그인만 허용한다. 컨트롤러 팩토리도 같은 제한을 받는다.
97
- - 앱 라우트는 Fastify 라우트 제약(`dokebiApp`)으로 등록되어 여러 앱이 같은 경로를 가질 수 있다. 제약 없는 공통 라우트(헬스 체크, 모듈 API)는 모든 도메인에서 응답한다.
98
- - 앱의 WebSocket 라우트도 같은 제약으로 등록된다. 허브의 tenant는 `<앱>:<tenant>`가 되어 접속자 목록·방송이 앱 밖으로 나가지 않는다. 세션의 `identity.tenant`도 이 값이다.
87
+ - A handler's `page` is `{ app: { name, template, domain }, module, base, view, inertia, sealed }`. In app routes `module` is undefined and `base` is `''`. `view` is an EJS renderer that looks in `<app>/<template>` → `<app>/default` → shared src/shared/views; layouts and `$include` follow the same order. `inertia` uses the app's document settings (Vite entry and so on) and adds `app` to the shared props.
88
+ - **Error pages ([D-0074](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0074-error-responses.md)):** errors on an app's hosts (unknown routes included) go through the app first. An Inertia app answers Inertia validation errors with the redirect back (`errors`) and other errors with `inertia.errorPage` (for example `Error`); for a browser page an EJS app renders `views/<template>/errors/<status>.ejs`, else `errors/error.ejs` (same lookup as pages, with `status`, `title`, `error`, `message`, `hint`, `fields`), else @dokebi/web's small page. JSON clients always get JSON. The `app add` skeletons include `errors/404.ejs` and `errors/error.ejs` (EJS) or `Pages/Error.vue` with `errorPage: 'Error'` (Inertia). Refuse input with `throw validationError({ name: 'Already taken' })` from @dokebi/web.
89
+ - **Mounting modules ([D-0032](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0032-feature-modules.md)):** `modules: { '/prefix': module }`, where the module was made with `defineModule`.
90
+ - The module's `routes` are registered with this app's route constraint and the prefix; handlers get `page.module` and `page.base`.
91
+ - The module's `sockets` are registered under the prefix. Their tenant is `<namespace>:<tenant>`, as for app sockets.
92
+ - Several apps can mount the same module under different prefixes. A mounted module's API is readable with `app.get(module)` without listing it in `requires`.
93
+ - The prefix is `/` or `/a/b` (lower-case letters, digits, `.`, `_`, `~`, `-`).
94
+ - Module pages look for views in this order, so module pages render inside the app layout:
95
+ 1. `<app>/<template>/<module>`
96
+ 2. `<app>/default/<module>`
97
+ 3. the module's `<template>`
98
+ 4. the module's `default`
99
+ 5. the app's views
100
+ 6. shared views
101
+ - **`shared(request, { app })`:** merged under the data of every EJS page this app renders (app routes and module routes). On overlapping keys the page data wins. Put app data the layout needs, such as the menu or the user, here. It corresponds to Inertia's shared props.
102
+ - `get` and `getDependency` of the app context (`app`) allow only the plugins listed in `requires`. Controller factories have the same limit.
103
+ - App routes are registered with a Fastify route constraint (`dokebiApp`), so several apps can own the same path. Shared routes without the constraint (health checks, module APIs) answer on every domain.
104
+ - The app's WebSocket routes (`sockets`) and SSE routes (`events`, @dokebi/sse) use the same constraint. The hub tenant is `<namespace>:<tenant>` and the default namespace is the app name, so without settings it stays `<app>:<tenant>`, one per app. The session's `identity.tenant` and `stream.tenant` hold this value.
105
+
106
+ ## Realtime namespaces (0.2.0, [D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md))
107
+
108
+ Presence lists, broadcasts and SSE publishing are divided by **namespace**, not by app. `apps.<app>.realtime.namespaces` (1 to 32, default `[<app>]`) are the spaces the app may use. Apps with the same namespace share presence, broadcasts and chat (this is not the `namespace` of the hub settings).
109
+
110
+ - **One connection = one namespace.** When a socket's or SSE route's `authenticate` returns `namespace`, the connection joins that space (it must be in the app's list), otherwise the first in the list. Outside the list: 401 and warn `NAMESPACE_FORBIDDEN`. `namespace` does not stay in the session identity.
111
+ - **Server code:** `app.realtime(namespace?)` gives the handle of that space (`NAMESPACE_FORBIDDEN` outside the list). A target's tenant is the authenticated tenant without the prefix; leaving it out means every tenant of the space.
112
+
113
+ ```ts snippet
114
+ const front = app.realtime('front');
115
+ await front.list(); // connections on every server (tenant, member, rooms…)
116
+ await front.list({ tenant: 'shop-1', room: 'vip' });
117
+ await front.send({ tenant: 'shop-1', member: 'u42' }, 'chat.message', { text: 'Hello' });
118
+ await front.send({}, 'notice', { text: 'Maintenance' }); // the whole space
119
+ await front.kick({ tenant: 'shop-1', member: 'u42' });
120
+ const stop = front.onPresence(({ tenant, joined, left }) => {});
121
+ await front.publish({ tenant: 'shop-1' }, 'order.changed', { id: 7 }); // @dokebi/sse
122
+ ```
123
+
124
+ - `send` uses the same `{ type, data }` frame as defineSocket broadcasts, at most once (D-0057), sealed per socket for sealed sockets. Without the needed plugin it throws `REALTIME_UNAVAILABLE`.
125
+ - The admin app example (watching two front spaces and chatting with users) is in [AI.md](AI.md) §4 "Realtime namespaces".
126
+
127
+ ## Seal hosts (0.2.0, [D-0059](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0059-seal-and-websocket-client.md) §4)
128
+
129
+ With `domains.<host>.seal: true` (default false), app sockets connected through that host seal every frame, and the host's HTTP data (REST JSON requests and responses, the Inertia first page and visits, SSE data) is sealed too (the dokebi-web seal slot, [D-0062](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0062-http-seal.md)). Route `seal: false` and dokebi-web `sealExclude` are plain exceptions; EJS HTML stays as it is. app fills a socket's `route.seal` from the request host; the actual sealing and the static files under `/dokebi/seal/*` (browser loader, socket bundle, wasm) are the **`@dokebi/seal` plugin**'s job. This public package looks that plugin up only by name (`dokebi-seal`).
130
+
131
+ - Pages get `sealed`: `page.sealed` in handlers, `sealed` in EJS data (the app's `shared` and page data win), `sealed` in Inertia shared props. A sealed page preloads the seal loader (wasm) and connects with the seal bridge. A client given the bridge offers both `dokebi.seal` and `dokebi.plain`, so on a plain host `dokebi.plain` is picked and it runs in plain text.
132
+ - Refused at start (fail closed): a `seal: true` domain without the `dokebi-seal` plugin is `SEAL_PROVIDER_MISSING`. An app on a sealed domain that has sockets with @dokebi/websocket older than 0.3 gets the same code. (The warn `SEAL_WITHOUT_SOCKETS` for sealed apps without sockets was removed by D-0062: HTTP is sealed too.)
133
+ - The rules of sealed connections (4415, 4400, hello, broadcasts) follow "Sealing per host" in the @dokebi/websocket README.
99
134
 
100
135
  ## API
101
136
 
102
- `createPlugin`이 돌려주는 API는 `{ names, resolve(request) }`다. `resolve`는 요청의 앱·템플릿·도메인을, 모르는 Host면 undefined를 돌려준다. `APP_CONSTRAINT`(`'dokebiApp'`)와 `hostOf(request)`도 공개한다.
137
+ `createPlugin` returns the API `{ names, resolve(request) }`. `resolve` returns the request's app, template and domain, or undefined for an unknown Host. `APP_CONSTRAINT` (`'dokebiApp'`), `hostOf(request)` and `withoutPort(host)` are public too.
@@ -0,0 +1,7 @@
1
+ import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
2
+ /** Codes of the errors this plugin throws (`AppError`, `plugin: 'dokebi-app'`). */
3
+ export type AppErrorCode = 'INVALID_DEFINITION' | 'INVALID_ENTRY' | 'UNKNOWN_APP' | 'SEAL_PROVIDER_MISSING' | 'VIEW_ENGINE_MISSING' | 'VIEWS_MISSING' | 'REALTIME_UNAVAILABLE' | 'NAMESPACE_FORBIDDEN' | 'INVALID_TARGET' | 'NOT_REQUIRED' | 'NOT_READY';
4
+ /** Errors of @dokebi/app; compare `code`, not the class (another installed copy may throw). */
5
+ export declare class AppError extends DokebiError<AppErrorCode> {
6
+ constructor(code: AppErrorCode, message: string, options?: DokebiErrorOptions);
7
+ }