@dokebi/app 0.2.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI.md +170 -100
- package/README.md +75 -73
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +21 -0
- package/dist/index.d.ts +128 -26
- package/dist/index.js +427 -232
- package/dist/options.d.ts +16 -0
- package/dist/options.js +55 -0
- package/options.schema.json +26 -16
- package/package.json +54 -42
- package/templates/app/views/default/errors/404.ejs +7 -0
- package/templates/app/views/default/errors/error.ejs +17 -0
- package/templates/app-inertia/app.ts +3 -0
- package/templates/app-inertia/views/app.js +1 -1
- package/templates/app-inertia/views/default/Pages/Error.vue +12 -0
- package/templates/app-inertia-ssr/app.ts +3 -0
- package/templates/app-inertia-ssr/views/ssr.js +1 -1
package/AI.md
CHANGED
|
@@ -1,104 +1,158 @@
|
|
|
1
|
-
# AI
|
|
1
|
+
# AI guide — @dokebi/app 0.4.1
|
|
2
2
|
|
|
3
|
-
|
|
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, web ^0.4.1; @dokebi/session optional (0.4.1: a refused HTML form goes back to its page, §4). 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
|
|
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 #
|
|
13
|
+
npx dokebi app remove shop # unlink the domains that point at the app first; the folder stays
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
|
|
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
|
-
|
|
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/
|
|
27
|
-
models/
|
|
28
|
-
views/default/
|
|
29
|
-
views
|
|
30
|
-
views/
|
|
31
|
-
|
|
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 (subfolders work: `Posts/Show` is Pages/Posts/Show.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
|
-
|
|
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.
|
|
42
|
+
## 3. Options `options.dokebi-app`
|
|
37
43
|
|
|
38
|
-
|
|
|
39
|
-
|
|
40
|
-
| `domains`
|
|
41
|
-
| `
|
|
42
|
-
| `
|
|
43
|
-
| `
|
|
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
|
-
|
|
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], //
|
|
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
|
|
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 }, //
|
|
61
|
-
shared: (request, page) => ({ menu: MENU }), //
|
|
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
|
|
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
|
|
74
|
-
- `page`: `{ app: { name, template, domain }, module, base, view, inertia, sealed }`.
|
|
75
|
-
- `view`: EJS
|
|
76
|
-
- `inertia`:
|
|
77
|
-
- `sealed`:
|
|
78
|
-
- `app`(AppContext): `name
|
|
79
|
-
- `inertia.ssr: { bundle: 'dist/ssr
|
|
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). Every page's data also has `errors`, `old` and `flash` (0.4.1, below), always objects.
|
|
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. **HTML form back** (0.4.1, D-0074 addendum 1): an HTML form post (body `application/x-www-form-urlencoded` or `multipart/form-data`, answered with HTML — not `fetch`, XHR, Bearer, JSON or Inertia) refused with 422 `VALIDATION_FAILED` (a route schema or `validationError()`) goes **back to its page** when the request has a session (@dokebi/session registered) and a `Referer` of the same host: `errors` (`{ field: message }`) and `old` (the body's top-level values without password-like fields such as `password`, `token`, `secret`, `api_key`, `card`, `cvc`, `otp`, `pin`; nothing when larger than 8 KB) are flashed and the answer is **303 to the Referer** (its path and query). Without a session, or with a missing or foreign Referer, it is the 422 error view below (no redirect, so no loop).
|
|
97
|
+
3. **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), errors ({ field: message } of a 422), old (the refused form's input, 422 only), fix, stack }` — `fix` and `stack` (5xx) only outside production, otherwise null. An `errors/422.ejs` can therefore show the form again without a session (`<%- await data.$include('posts/form') %>` with the same `data.errors`/`data.old`).
|
|
98
|
+
4. Otherwise dokebi-web's own answer: JSON for scripts (Inertia, `fetch`, XHR, Bearer, JSON bodies), a small HTML page for browser pages.
|
|
80
99
|
|
|
81
|
-
|
|
100
|
+
JSON clients never get a view, and are never redirected. 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), `App form validation redirect` (app, method, route, fields, old count, target path), `App form validation answered with the error view` (app, reason `no-session` or `no-way-back`, method, route).
|
|
82
101
|
|
|
83
|
-
|
|
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. 공통
|
|
102
|
+
### Forms: `errors`, `old` and `flash` in every view (0.4.1)
|
|
92
103
|
|
|
93
|
-
|
|
104
|
+
With @dokebi/session registered, the first render of a request **takes the session flash once** (`takeFlash()`, shared by every render of that request) and every EJS page of the app (its own and its modules') gets:
|
|
94
105
|
|
|
95
|
-
-
|
|
96
|
-
-
|
|
97
|
-
-
|
|
106
|
+
- `data.errors` — `{ field: message }` of the form this request was sent back from (`{}` otherwise);
|
|
107
|
+
- `data.old` — that form's input (`{}` otherwise);
|
|
108
|
+
- `data.flash` — the rest of the flash, for example `data.flash.notice` after `await request.session.flash('notice', 'Saved')` (`{}` otherwise).
|
|
98
109
|
|
|
99
|
-
|
|
110
|
+
Without the session plugin all three are `{}`, so templates need no checks. The handler's own `errors` and `old` win field by field; the app's `shared` data and the page data win over `flash`. Error views do not take the flash (it is for the next page). If a handler calls `request.session.takeFlash()` itself before rendering, it takes `errors` and `old` too (pass them on, or read `data.flash` instead). A write form:
|
|
111
|
+
|
|
112
|
+
```ejs
|
|
113
|
+
<form method="post" action="/posts">
|
|
114
|
+
<input name="title" value="<%= data.old.title ?? '' %>">
|
|
115
|
+
<% if (data.errors.title) { %><small class="error"><%= data.errors.title %></small><% } %>
|
|
116
|
+
<textarea name="body"><%= data.old.body ?? '' %></textarea>
|
|
117
|
+
<% if (data.errors.body) { %><small class="error"><%= data.errors.body %></small><% } %>
|
|
118
|
+
<button>Save</button>
|
|
119
|
+
</form>
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
```ts snippet
|
|
123
|
+
import { validationError } from '@dokebi/web';
|
|
124
|
+
route.post('/posts', async (request, reply, page) => {
|
|
125
|
+
const { title } = request.body as { title: string; body: string };
|
|
126
|
+
if (await titleTaken(title)) throw validationError({ title: 'Already taken' }); // back to the form, 303
|
|
127
|
+
await request.session.flash('notice', 'Saved');
|
|
128
|
+
return reply.redirect('/posts', 303);
|
|
129
|
+
}, { schema: { body: { type: 'object', required: ['title', 'body'], properties: { title: { type: 'string', minLength: 1, maxLength: 120 }, body: { type: 'string', minLength: 1 } } } } });
|
|
130
|
+
```
|
|
100
131
|
|
|
101
|
-
|
|
132
|
+
HTML forms need `dokebi-web.formBody: true` (urlencoded bodies). The flow needs `npx dokebi add @dokebi/session`; without it the refused form shows `errors/422.ejs` (or `errors/error.ejs`) with `fields`, `errors` and `old`.
|
|
133
|
+
|
|
134
|
+
### Mounting modules (D-0032)
|
|
135
|
+
|
|
136
|
+
- `modules: { '/prefix': module }`. The prefix is `/` or `/a/b` (lower-case letters, digits, `.`, `_`, `~`, `-`).
|
|
137
|
+
- 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`.
|
|
138
|
+
- 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).
|
|
139
|
+
- 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>/`.
|
|
140
|
+
1. `<app>/<template>/<module>`
|
|
141
|
+
2. `<app>/default/<module>`
|
|
142
|
+
3. the module's `<template>`
|
|
143
|
+
4. the module's `default`
|
|
144
|
+
5. the app's views
|
|
145
|
+
6. shared views
|
|
146
|
+
|
|
147
|
+
### Routing and WebSocket
|
|
148
|
+
|
|
149
|
+
- 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.
|
|
150
|
+
- 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`.
|
|
151
|
+
- 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`).
|
|
152
|
+
|
|
153
|
+
### Realtime namespaces (0.2.0, [D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md))
|
|
154
|
+
|
|
155
|
+
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
156
|
|
|
103
157
|
```yaml
|
|
104
158
|
dokebi-app:
|
|
@@ -108,22 +162,22 @@ dokebi-app:
|
|
|
108
162
|
admin.a.com: { app: admin }
|
|
109
163
|
apps:
|
|
110
164
|
shop: { realtime: { namespaces: [front] } }
|
|
111
|
-
mobile: { realtime: { namespaces: [front] } } #
|
|
112
|
-
admin: { realtime: { namespaces: [admin, front] } } #
|
|
165
|
+
mobile: { realtime: { namespaces: [front] } } # the same space as shop
|
|
166
|
+
admin: { realtime: { namespaces: [admin, front] } } # the first is the default for its own sockets
|
|
113
167
|
```
|
|
114
168
|
|
|
115
|
-
-
|
|
116
|
-
-
|
|
117
|
-
- `list(filter?)` →
|
|
118
|
-
- `send(target, type, data?)` →
|
|
119
|
-
- `kick(target, code?, reason?)` →
|
|
120
|
-
- `onPresence(listener)` →
|
|
121
|
-
- `publish(target, event, data?)` → @dokebi/sse
|
|
122
|
-
-
|
|
123
|
-
-
|
|
124
|
-
-
|
|
169
|
+
- **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`).
|
|
170
|
+
- **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**.
|
|
171
|
+
- `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).
|
|
172
|
+
- `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.
|
|
173
|
+
- `kick(target, code?, reason?)` → closes those connections on every server (4000–4999, default 4403).
|
|
174
|
+
- `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`.
|
|
175
|
+
- `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.
|
|
176
|
+
- 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).
|
|
177
|
+
- **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.
|
|
178
|
+
- 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
179
|
|
|
126
|
-
####
|
|
180
|
+
#### Example: an admin app that watches two front spaces and chats with users
|
|
127
181
|
|
|
128
182
|
```yaml
|
|
129
183
|
dokebi-app:
|
|
@@ -133,7 +187,7 @@ dokebi-app:
|
|
|
133
187
|
admin: { realtime: { namespaces: [admin, shop, blog] } }
|
|
134
188
|
```
|
|
135
189
|
|
|
136
|
-
```ts
|
|
190
|
+
```ts snippet
|
|
137
191
|
// src/apps/admin/app.ts
|
|
138
192
|
import { type AppContext, defineApp } from '@dokebi/app';
|
|
139
193
|
import { defineSocket } from '@dokebi/websocket';
|
|
@@ -143,30 +197,30 @@ const WATCHED = ['shop', 'blog'] as const;
|
|
|
143
197
|
type Watched = (typeof WATCHED)[number];
|
|
144
198
|
|
|
145
199
|
export default defineApp({
|
|
146
|
-
//
|
|
200
|
+
// The admin screens join the admin space only (they do not appear in the front presence list).
|
|
147
201
|
sockets: (app) => [
|
|
148
202
|
defineSocket({
|
|
149
203
|
path: '/ws',
|
|
150
204
|
authenticate: async (request) => {
|
|
151
|
-
const staff = await staffOf(request); //
|
|
205
|
+
const staff = await staffOf(request); // check the staff session; undefined → 401
|
|
152
206
|
return staff && { tenant: 'staff', member: staff.id, namespace: 'admin' };
|
|
153
207
|
},
|
|
154
208
|
on: {
|
|
155
|
-
//
|
|
209
|
+
// When a screen opens, read the current users of both spaces at once.
|
|
156
210
|
'users.list': async () =>
|
|
157
211
|
Object.fromEntries(
|
|
158
212
|
await Promise.all(WATCHED.map(async (space) => [space, await app.realtime(space).list()])),
|
|
159
213
|
),
|
|
160
|
-
//
|
|
214
|
+
// Admin → one front user (all of that person's tabs).
|
|
161
215
|
'chat.send': async (data, socket) => {
|
|
162
216
|
const { space, tenant, member, text } = data as { space: Watched; tenant: string; member: string; text: string };
|
|
163
217
|
if (!WATCHED.includes(space)) throw Object.assign(new Error('bad space'), { code: 'BAD_SPACE' });
|
|
164
218
|
const receipt = await app.realtime(space).send({ tenant, member }, 'chat.message', {
|
|
165
219
|
from: socket.identity.member, text,
|
|
166
220
|
});
|
|
167
|
-
return { recipients: receipt.recipients.length }; // 0
|
|
221
|
+
return { recipients: receipt.recipients.length }; // 0: the user already left
|
|
168
222
|
},
|
|
169
|
-
//
|
|
223
|
+
// Notice: every tenant of that space.
|
|
170
224
|
'notice.send': async (data) => {
|
|
171
225
|
const { space, text } = data as { space: Watched; text: string };
|
|
172
226
|
await app.realtime(space).send({}, 'notice', { text });
|
|
@@ -174,7 +228,7 @@ export default defineApp({
|
|
|
174
228
|
},
|
|
175
229
|
}),
|
|
176
230
|
],
|
|
177
|
-
//
|
|
231
|
+
// Forward the front's joins and leaves to the admin screens in real time.
|
|
178
232
|
start(app) {
|
|
179
233
|
for (const space of WATCHED) {
|
|
180
234
|
const stop = app.realtime(space).onPresence((change) =>
|
|
@@ -186,45 +240,61 @@ export default defineApp({
|
|
|
186
240
|
});
|
|
187
241
|
```
|
|
188
242
|
|
|
189
|
-
-
|
|
190
|
-
-
|
|
243
|
+
- 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.
|
|
244
|
+
- 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
245
|
|
|
192
|
-
###
|
|
246
|
+
### Seal hosts (0.2.0, D-0059 §4)
|
|
193
247
|
|
|
194
248
|
```yaml
|
|
195
249
|
dokebi-app:
|
|
196
250
|
domains:
|
|
197
|
-
secure.example.com: { app: shop, seal: true } #
|
|
198
|
-
www.example.com: { app: shop } #
|
|
251
|
+
secure.example.com: { app: shop, seal: true } # every frame of this host's sockets is sealed
|
|
252
|
+
www.example.com: { app: shop } # plain, even for the same app and socket path
|
|
199
253
|
```
|
|
200
254
|
|
|
201
|
-
-
|
|
202
|
-
-
|
|
203
|
-
-
|
|
204
|
-
- **HTTP(D-0062)**:
|
|
255
|
+
- 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.
|
|
256
|
+
- 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.
|
|
257
|
+
- Same app = same hub tenant, so a broadcast sent on a seal host reaches plain-host sockets in plain text and sealed sockets sealed.
|
|
258
|
+
- **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
259
|
|
|
206
260
|
## 5. API
|
|
207
261
|
|
|
208
|
-
`createPlugin
|
|
262
|
+
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.
|
|
263
|
+
|
|
264
|
+
## 6. Errors and what is refused at start
|
|
209
265
|
|
|
210
|
-
|
|
266
|
+
<!-- docs-check: complete-error-codes AppErrorCode -->
|
|
267
|
+
`AppError` (`plugin: 'dokebi-app'`, all with a `fix`):
|
|
211
268
|
|
|
212
|
-
|
|
269
|
+
| Code | When |
|
|
270
|
+
|---|---|
|
|
271
|
+
| `INVALID_DEFINITION` | unknown fields or bad values in `defineApp`, a bad module prefix, a module not made with `defineModule`, a bad requires item |
|
|
272
|
+
| `INVALID_ENTRY` | the entry is not `{ apps: { <name>: defineApp(...) } }` (the cause of `INVALID_PLUGIN_INPUT`) |
|
|
273
|
+
| `UNKNOWN_APP` | a domain pointing at an undefined app, or `apps.<app>` naming an undefined app |
|
|
274
|
+
| `SEAL_PROVIDER_MISSING` | a `seal: true` domain exists but the `dokebi-seal` plugin does not (even without sockets) |
|
|
275
|
+
| `VIEW_ENGINE_MISSING` | an app's `views` or module views without the `ejs` engine, or `inertia` without the `inertia` engine |
|
|
276
|
+
| `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 |
|
|
277
|
+
| `REALTIME_UNAVAILABLE` | `sockets` without the `websocket` transport, `events` without the `sse` transport, or that call on a `realtime()` handle |
|
|
278
|
+
| `NAMESPACE_FORBIDDEN` | `realtime(namespace)` outside the app's list |
|
|
279
|
+
| `INVALID_TARGET` | a realtime target that is not `{ tenant?, member?, room? }` (1 to 256 characters) |
|
|
280
|
+
| `NOT_REQUIRED` | reading a plugin that is not in `requires` |
|
|
281
|
+
| `NOT_READY` | `controller()` before setup |
|
|
213
282
|
|
|
214
|
-
(
|
|
283
|
+
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
284
|
|
|
216
|
-
warn:
|
|
285
|
+
warn: authentication picked a namespace outside the list (`Realtime namespace refused`, code `NAMESPACE_FORBIDDEN`, 401).
|
|
217
286
|
|
|
218
|
-
|
|
287
|
+
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
288
|
|
|
220
|
-
## 7.
|
|
289
|
+
## 7. Cautions
|
|
221
290
|
|
|
222
|
-
-
|
|
223
|
-
- `views/default
|
|
224
|
-
-
|
|
225
|
-
-
|
|
226
|
-
- Inertia
|
|
291
|
+
- Do not branch on the Host header in code. Keep domain → app/template in dokebi.yaml only; handlers read `page.app`.
|
|
292
|
+
- Do not delete `views/default/`. Template folders hold only the files that change.
|
|
293
|
+
- Apps do not import each other. Shared code goes into `src/shared/` (models, views) or a module.
|
|
294
|
+
- 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).
|
|
295
|
+
- An Inertia app without its build files fails to start. Run `npm run build` first.
|
|
296
|
+
- Do not answer validation with `reply.code(422).send(…)` by hand: `throw validationError({ field: 'message' })` so Inertia and HTML forms get the redirect with `errors` (with a session) and other clients the standard `fields`/`errors` body (D-0074).
|
|
227
297
|
|
|
228
|
-
## 8.
|
|
298
|
+
## 8. References
|
|
229
299
|
|
|
230
|
-
`examples/25-playground`(vue
|
|
300
|
+
`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.
|