@dokebi/app 0.2.0 → 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,104 +1,125 @@
1
- # AI 작업 안내 — @dokebi/app 0.2.0
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·SSE를 쓰는 앱이 있으면 `@dokebi/template-inertia`, `@dokebi/websocket`, `@dokebi/sse`를 따로 add한다(없으면 시작 실패: `App <앱> uses Inertia; add @dokebi/template-inertia`, `has sockets; add @dokebi/websocket`, `has event streams; add @dokebi/sse`).
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?, seal? } }`, 최대 1024 | 호스트 → 앱·템플릿(생략은 default). `seal: true`면 그 호스트의 WebSocket 프레임과 HTTP 데이터(JSON 본문·Inertia 페이지·SSE data)를 봉인(§4 봉인 호스트, 기본 false) |
41
- | `unknownDomain` | `reject`(기본) 또는 domains의 키 하나 | 모르는 호스트: 404, 또는 그 도메인의 설정으로 응답 |
42
- | `apps` | `{ <앱>: { realtime?: { namespaces } } }` | 앱별 설정. **키는 정의된 앱 이름**이어야 한다(없는 앱이면 시작 실패 `UNKNOWN_APP`) |
43
- | `apps.<앱>.realtime.namespaces` | 이름 1~32개(`^[a-z][a-z0-9-]{0,31}$`, 중복 금지), 기본 `[<앱>]` | 이 앱의 실시간 공간(§4 실시간 네임스페이스, D-0061) |
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) |
44
53
 
45
- 호스트는 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`.
46
55
 
47
56
  ## 4. defineApp
48
57
 
49
- ```ts
58
+ ```ts snippet
50
59
  import { defineApp } from '@dokebi/app';
51
60
  import { dependency as db } from '@dokebi/db';
52
61
  import board from '../../shared/modules/board/module.ts';
53
62
  import { productController } from './controllers/product.ts';
54
63
 
55
64
  export default defineApp({
56
- requires: [db], // 이 앱이 쓰는 플러그인·모듈. 이 밖은 get 불가
65
+ requires: [db], // plugins and modules this app uses; nothing else can be read
57
66
  controllers: [productController],
58
- 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
59
68
  inertia: { title: 'Shop', vite: { manifest: 'dist/.vite/manifest.json', entry: 'src/apps/shop/views/app.js', base: '/build/' } },
60
- modules: { '/board': board }, // 모듈의 routes·sockets·views를 이 앱 도메인에 붙임
61
- 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)
62
71
  routes(route, app) {
63
72
  route.get('/', async (request, reply, page) =>
64
73
  page.view.reply(reply, 'home', { items: await app.controller(productController).list() }, { layout: 'layouts/main' }),
65
74
  );
66
75
  },
67
76
  sockets: (app) => [chatSocket(app)],
68
- events: (app) => [orderStream(app)], // @dokebi/sse 라우트(SseRoute). 소켓과 같은 제약·네임스페이스
77
+ events: (app) => [orderStream(app)], // @dokebi/sse routes (SseRoute); same constraint and namespaces as sockets
69
78
  setup(app) {}, start(app) {}, drain(app) {},
70
79
  });
71
80
  ```
72
81
 
73
- - `route`: `get`·`post`·`put`·`patch`·`delete(url, handler, options?)`, `route(options)`. 핸들러는 `(request, reply, page)`.
74
- - `page`: `{ app: { name, template, domain }, module, base, view, inertia, sealed }`. 앱 라우트에서 `module`은 undefined, `base`는 `''`.
75
- - `view`: EJS 렌더러. 찾는 순서 `<앱>/<템플릿>` → `<앱>/default` → `src/shared/views`(레이아웃·`$include`도 같음).
76
- - `inertia`: 앱의 문서 설정을 쓰는 Inertia 렌더러(앱에 `inertia`가 있을 때). 공통 props에 `app`(`{ name, template, domain }`)과 `sealed`를 더한다.
77
- - `sealed`: 요청 호스트가 `seal: true`인가. EJS 데이터에도 `sealed`로 들어간다(앱 `shared`·페이지 데이터가 이김).
78
- - `app`(AppContext): `name`·`logger`·`signal`·`get`·`getDependency`·`getOptionalDependency`·`controller`·`defer`·`realtime(namespace?)`(§4 실시간 네임스페이스). **`requires`에 없는 것을 꺼내면 오류**(`App <앱> does not list <플러그인> in requires`). 컨트롤러 팩토리도 같은 제한을 받는다.
79
- - `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):
80
94
 
81
- ### 모듈 붙이기(D-0032)
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.
82
98
 
83
- - `modules: { '/접두사': 모듈 }`. 접두사는 `/` 또는 `/a/b`(소문자·숫자·`.`·`_`·`~`·`-`).
84
- - 모듈의 라우트·소켓·SSE 라우트(`events`, @dokebi/module 0.1.3)가 이 앱의 도메인·접두사로 등록되고 `page.module`·`page.base`가 채워진다. 같은 모듈을 여러 앱이 다른 접두사로 붙일 수 있다. 붙인 모듈은 `requires`에 넣지 않아도 `app.get(모듈)`로 API를 읽는다.
85
- - 모듈 화면 찾는 순서는 다음과 같다. 그래서 모듈 화면이 앱 레이아웃 안에 그려진다. 앱이 모듈 화면을 바꾸려면 `views/<템플릿>/<모듈>/`에 같은 파일을 둔다.
86
- 1. `<앱>/<템플릿>/<모듈>`
87
- 2. `<앱>/default/<모듈>`
88
- 3. 모듈의 `<템플릿>`
89
- 4. 모듈의 `default`
90
- 5. 앱 views
91
- 6. 공통
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).
92
100
 
93
- ### 라우팅과 WebSocket
101
+ ### Mounting modules (D-0032)
94
102
 
95
- - 앱 라우트는 Fastify 제약 `dokebiApp`(`APP_CONSTRAINT`)으로 등록된다. 여러 앱이 같은 경로를 가질 수 있다. 제약 없는 라우트(헬스 체크, `@dokebi/router` API)는 모든 도메인에서 응답한다.
96
- - 앱 소켓도 같은 제약을 쓴다. 허브 tenant는 `<네임스페이스>:<tenant>`(기본 네임스페이스는 앱 이름이라 설정이 없으면 `<앱>:<tenant>`)이며 세션 `identity.tenant`도 그 값이다. 메시지는 `defineSocket`의 `{ type, data, id? }` 형식.
97
- - 앱 `events`(SSE, @dokebi/sse)도 같은 제약·같은 tenant 규칙으로 붙는다(`stream.tenant`가 `<네임스페이스>:<tenant>`). @dokebi/sse가 없으면 시작 실패 `App <앱> has event streams; add @dokebi/sse`. 붙인 모듈의 `events`(@dokebi/module 0.1.3)도 모듈 접두사 아래에 같은 규칙으로 붙는다(`Module <모듈> (app <앱>) has event streams; add @dokebi/sse`).
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
98
113
 
99
- ### 실시간 네임스페이스 (0.2.0, [D-0061](../../docs/decisions/D-0061-realtime-namespaces.md))
114
+ ### Routing and WebSocket
100
115
 
101
- 접속자 목록·방송·SSE 발행이 갈리는 단위는 **앱이 아니라 네임스페이스**다. 같은 네임스페이스를 가진 앱끼리 접속자·방송·채팅을 함께 쓴다. 허브의 `namespace`(Redis 키 접두, 클러스터 단위)와는 다른 것이다.
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).
102
123
 
103
124
  ```yaml
104
125
  dokebi-app:
@@ -108,22 +129,22 @@ dokebi-app:
108
129
  admin.a.com: { app: admin }
109
130
  apps:
110
131
  shop: { realtime: { namespaces: [front] } }
111
- mobile: { realtime: { namespaces: [front] } } # shop과 같은 공간
112
- admin: { realtime: { namespaces: [admin, 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
113
134
  ```
114
135
 
115
- - **연결 하나 = 네임스페이스 하나**: 소켓·SSE 스트림의 허브 tenant는 `<네임스페이스>:<인증 tenant>`. `authenticate`가 `namespace`를 돌려주면 그 공간(앱 목록 안이어야 함)으로, 없으면 목록의 첫째로 들어간다. 목록 밖이면 401과 warn `Realtime namespace refused`(code `NAMESPACE_FORBIDDEN`, `app`·`kind`(socket·stream)·`path`·`namespace`·`allowed`). `namespace`는 앱이 지우므로 세션 `identity`·`stream.identity`에는 없다(공간은 `identity.tenant`의 접두로 안다).
116
- - **서버 코드의 핸들** `app.realtime(namespace?)`(생략하면 첫째, 목록 밖이면 즉시 `NAMESPACE_FORBIDDEN`). 대상 `{ tenant?, member?, room? }`의 tenant는 접두 없는 인증 tenant다. **tenant를 빼면 그 네임스페이스의 모든 tenant**.
117
- - `list(filter?)` → 연결 목록(`tenant`(접두 없음)·`member`·`connection`·`ownerEpoch`·`clientId?`·`rooms`·`metadata`). tenant가 있으면 허브에 묻고(클러스터 전체, 실패는 허브 code), 없으면 이 서버가 받은 presence(모든 서버, 조금 늦을 수 있음, start 전에는 빈 목록)에서 읽는다.
118
- - `send(target, type, data?)` → defineSocket 방송과 같은 `{ type, data }` 텍스트 프레임을 허브로(많아야 한 번, 봉인 소켓은 소켓마다 봉인). 영수증 `{ ids, recipients }`. tenant를 빼면 tenant마다 방송 하나.
119
- - `kick(target, code?, reason?)` → 모든 서버에서 그 연결을 닫음(4000~4999, 기본 4403).
120
- - `onPresence(listener)` → 그 공간 tenant의 입·퇴장(`{ tenant, joined, left }`, tenant 접두 없음). 돌려준 함수로 끊는다. 던지거나 거부한 listener는 websocket이 error `PRESENCE_LISTENER_FAILED`로 남긴다.
121
- - `publish(target, event, data?)` → @dokebi/sse 발행(그 공간의 스트림, 버스가 있으면 모든 프로세스). tenant를 빼면 모든 프로세스가 자기 스트림 중 접두가 맞는 tenant에 쓴다.
122
- - 필요한 플러그인이 없으면 `REALTIME_UNAVAILABLE`(소켓 쪽은 @dokebi/websocket 0.3 이상, publish는 @dokebi/sse).
123
- - **권한은 앱이 정한다**: 같은 공간 안에서 누가 누구를 볼지는 rooms·역할·앱 코드로 정한다. 네임스페이스는 공간을 나누는 것만 한다. 관리자 앱이 프론트 공간에 접속자로 보이지 않으려면 자기 소켓을 자기 공간(`admin`)에 두고 서버 코드에서 `realtime('front')`로 모아 본다.
124
- - 모듈 소켓·SSE 라우트(`events`)는 붙인 앱의 네임스페이스 규칙을 그대로 따른다. 모듈 문맥(ModuleContext)에는 `realtime`이 없다(모듈은 여러 앱에 붙으므로 앱 문맥이 아니다).
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).
125
146
 
126
- #### 예: 프론트 두 공간을 지켜보고 사용자와 채팅하는 관리자 앱
147
+ #### Example: an admin app that watches two front spaces and chats with users
127
148
 
128
149
  ```yaml
129
150
  dokebi-app:
@@ -133,7 +154,7 @@ dokebi-app:
133
154
  admin: { realtime: { namespaces: [admin, shop, blog] } }
134
155
  ```
135
156
 
136
- ```ts
157
+ ```ts snippet
137
158
  // src/apps/admin/app.ts
138
159
  import { type AppContext, defineApp } from '@dokebi/app';
139
160
  import { defineSocket } from '@dokebi/websocket';
@@ -143,30 +164,30 @@ const WATCHED = ['shop', 'blog'] as const;
143
164
  type Watched = (typeof WATCHED)[number];
144
165
 
145
166
  export default defineApp({
146
- // 관리자 화면들은 admin 공간 하나에 붙는다(프론트 접속자 목록에 보이지 않음).
167
+ // The admin screens join the admin space only (they do not appear in the front presence list).
147
168
  sockets: (app) => [
148
169
  defineSocket({
149
170
  path: '/ws',
150
171
  authenticate: async (request) => {
151
- const staff = await staffOf(request); // 직원 세션 확인. 아니면 undefined → 401
172
+ const staff = await staffOf(request); // check the staff session; undefined → 401
152
173
  return staff && { tenant: 'staff', member: staff.id, namespace: 'admin' };
153
174
  },
154
175
  on: {
155
- // 화면이 열릴 때 두 공간의 현재 접속자를 한 번에 읽는다.
176
+ // When a screen opens, read the current users of both spaces at once.
156
177
  'users.list': async () =>
157
178
  Object.fromEntries(
158
179
  await Promise.all(WATCHED.map(async (space) => [space, await app.realtime(space).list()])),
159
180
  ),
160
- // 관리자 → 프론트 사용자 한 명(그 사람의 모든 탭).
181
+ // Admin → one front user (all of that person's tabs).
161
182
  'chat.send': async (data, socket) => {
162
183
  const { space, tenant, member, text } = data as { space: Watched; tenant: string; member: string; text: string };
163
184
  if (!WATCHED.includes(space)) throw Object.assign(new Error('bad space'), { code: 'BAD_SPACE' });
164
185
  const receipt = await app.realtime(space).send({ tenant, member }, 'chat.message', {
165
186
  from: socket.identity.member, text,
166
187
  });
167
- return { recipients: receipt.recipients.length }; // 0이면 이미 나간 사용자
188
+ return { recipients: receipt.recipients.length }; // 0: the user already left
168
189
  },
169
- // 공지: 그 공간의 모든 tenant.
190
+ // Notice: every tenant of that space.
170
191
  'notice.send': async (data) => {
171
192
  const { space, text } = data as { space: Watched; text: string };
172
193
  await app.realtime(space).send({}, 'notice', { text });
@@ -174,7 +195,7 @@ export default defineApp({
174
195
  },
175
196
  }),
176
197
  ],
177
- // 프론트의 입·퇴장을 관리자 화면들에 실시간으로 넘긴다.
198
+ // Forward the front's joins and leaves to the admin screens in real time.
178
199
  start(app) {
179
200
  for (const space of WATCHED) {
180
201
  const stop = app.realtime(space).onPresence((change) =>
@@ -186,45 +207,61 @@ export default defineApp({
186
207
  });
187
208
  ```
188
209
 
189
- - 프론트 앱(shop·blog)의 소켓은 바꿀 것이 없다. 사용자의 답장을 직원 화면에 보내려면 shop의 namespaces를 `[shop, admin]`으로 하고 shop 핸들러가 `app.realtime('admin').send({ tenant: 'staff' }, 'chat.reply', …)`를 부른다(첫째가 shop이라 사용자 소켓은 그대로 shop 공간). 그러면 shop 서버 코드가 관리자 공간에 쓸 수 있으므로 무엇을 보낼지는 앱 코드로 제한한다.
190
- - 관리자 화면이 프론트 사용자로도 보여야 하면(대화방에 함께 있는 직원) 그 화면의 소켓이 `namespace: 'shop'`으로 붙으면 된다.
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'`.
191
212
 
192
- ### 봉인 호스트 (0.2.0, D-0059 §4)
213
+ ### Seal hosts (0.2.0, D-0059 §4)
193
214
 
194
215
  ```yaml
195
216
  dokebi-app:
196
217
  domains:
197
- secure.example.com: { app: shop, seal: true } # 이 호스트의 소켓은 모든 프레임을 봉인
198
- www.example.com: { app: shop } # 같은 앱·같은 소켓 경로라도 평문
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
199
220
  ```
200
221
 
201
- - 앱 소켓의 `route.seal`을 요청 호스트로 채운다(그 앱의 호스트 중 하나라도 봉인일 때만; 라우트 자신의 `seal`은 평문 호스트에서도 유지). 알고리즘·`/dokebi/seal/*` 정적 파일은 **`@dokebi/seal` 플러그인**(`dokebi-seal`)이 맡는다. 이 공개 패키지는 이름으로만 찾는다.
202
- - 페이지: `sealed`가 true면 `/dokebi/seal/seal.mjs`·`socket.mjs`를 불러 `initSeal()` 뒤 `connectChannel({ path, seal: sealBridge })`로 붙는다. (다리를 늘 줘도 된다: 클라이언트가 `dokebi.seal`·`dokebi.plain`을 함께 제안하고 평문 호스트는 `dokebi.plain`을 골라 평문으로 돈다. `sealed`는 wasm을 미리 받을지 정하는 데 쓴다.) 봉인 호스트에 다리 없이 붙으면 4415(재접속 안 함), 열리지 않는 프레임은 4400. 세부는 @dokebi/websocket AI.md §4a·@dokebi/seal README.
203
- - 같은 앱 = 같은 허브 tenant라서 봉인 호스트에서 보낸 방송도 평문 호스트 소켓에는 평문으로, 봉인 소켓에는 봉인되어 간다.
204
- - **HTTP(D-0062)**: 봉인 도메인이 있으면 dokebi-web에 `sealRequests(호스트가 봉인인가)`를 등록한다. 그 호스트의 모든 HTTP 요청(앱 라우트든 모듈이 web에 직접 단 `/api/*`든): JSON 응답 봉인, 평문 JSON 본문 415, Inertia 첫 화면 봉인, SSE data 봉인. 앱 라우트 옵션 `seal: false`(`route.post('/hook', handler, { seal: false })`)면 평문(웹훅·서버 사이), dokebi-web `sealExclude`도 같다. EJS HTML은 그대로이고, 네이티브 폼을 받는 라우트는 `seal: false`로 둔다. 봉인 도메인 앱의 Inertia 범위에는 `sealed: true`를 넘겨 SSR과 겹치면 시작 실패(`SEAL_SSR_CONFLICT`). 브라우저: `@dokebi/seal/http`의 `sealInertia`·`sealedFetch`·`currentSealBridge`(CLI 템플릿 `views/app.js`가 봉인 페이지일 때 `/dokebi/seal/http.mjs`를 불러 `sealInertia(http)`를 부른다).
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).
205
226
 
206
227
  ## 5. API
207
228
 
208
- `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
209
232
 
210
- ## 6. 시작 때 거절되는 것
233
+ <!-- docs-check: complete-error-codes AppErrorCode -->
234
+ `AppError` (`plugin: 'dokebi-app'`, all with a `fix`):
211
235
 
212
- 없는 앱을 가리키는 도메인, 등록 안 된 앱, 정의되지 않은 앱 이름의 `apps.<앱>`(`UNKNOWN_APP`), 잘못된 `realtime.namespaces`(빈 목록·중복·형식·33개 이상), `seal: true` 도메인이 있는데 `dokebi-seal` 플러그인이 없음(`SEAL_PROVIDER_MISSING`, 소켓이 없어도), 봉인 도메인의 앱이 소켓을 붙이는데 @dokebi/websocket이 봉인을 모르는 옛 판(0.3 미만, 같은 code), 잘못된 `seal` 값(boolean 아님), `views` 폴더나 `views/default/`·도메인이 고른 `views/<템플릿>/` 누락(원래 파일 오류는 `cause`), `defineApp`의 모르는 필드, 잘못된 모듈 접두사, `defineModule`로 만들지 않은 모듈.
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 |
213
249
 
214
- (0.2.0 안에서 바뀜: 소켓 없는 봉인 앱의 warn `SEAL_WITHOUT_SOCKETS`는 없앴다 — 이제 HTTP도 봉인되므로 소켓이 없어도 봉인할 것이 있다, D-0062.)
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`.
215
251
 
216
- warn: 인증이 목록 밖 네임스페이스를 고름(`Realtime namespace refused`, code `NAMESPACE_FORBIDDEN`, 401).
252
+ warn: authentication picked a namespace outside the list (`Realtime namespace refused`, code `NAMESPACE_FORBIDDEN`, 401).
217
253
 
218
- debug 로그(D-0047): `App domains configured`(도메인 → 앱/템플릿, 봉인 표시 `(sealed)`·봉인 도메인 수 `sealed`, 64개까지)·`App set up`(requires·템플릿·inertia·모듈·라우트·소켓·SSE 라우트 수 `events`·`namespaces`·ms)·`App realtime handle created`(앱·네임스페이스·websocket/sse 유무, 네임스페이스마다 한 번)·연결마다 `Realtime namespace chosen`(debug가 켜졌을 때만)·`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).
219
255
 
220
- ## 7. 주의 사항
256
+ ## 7. Cautions
221
257
 
222
- - 코드에서 Host 헤더로 분기하지 않는다. 도메인 → 앱·템플릿은 dokebi.yaml에만 두고 핸들러는 `page.app`을 읽는다.
223
- - `views/default/`를 지우지 않는다. 템플릿 폴더에는 바꿀 파일만 둔다.
224
- - 앱끼리 서로 import하지 않는다. 공통 코드는 `src/shared/`(모델·뷰) 또는 모듈.
225
- - 생성 등록 코드와 `.dokebi/state.json`을 고치지 않는다. 앱·도메인 변경은 `dokebi app` 명령으로 한다(dokebi.example.yaml에도 같이 남는다).
226
- - 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).
227
264
 
228
- ## 8. 근거
265
+ ## 8. References
229
266
 
230
- `examples/25-playground`(vue·ejs·admin 앱, 도메인·템플릿, 모듈, 소켓, 네임스페이스: admin이 vue·ejs 접속자를 보고 채팅·SSE 발행), `examples/26-scaffold`(CLI 생성 반복 검증), D-0030·D-0031·D-0032·D-0039·D-0059(봉인 호스트 — 플레이그라운드 `sealed.localhost`, 실제 서버·Chromium 검사는 @dokebi/seal의 `seal:test`·`seal:browser-check`).
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.