@dokebi/app 0.4.0 → 0.4.2

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,6 +1,6 @@
1
- # AI guide — @dokebi/app 0.4.0
1
+ # AI guide — @dokebi/app 0.4.2
2
2
 
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).
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.2; @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
5
  ## 1. Install and what it creates
6
6
 
@@ -29,7 +29,7 @@ src/apps/<app>/
29
29
  routes.ts routes
30
30
  controllers/ this app's defineController tokens
31
31
  models/ plain code
32
- views/default/ the default template (required). EJS: home.ejs / Inertia: Layout.vue, Pages/*.vue
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
33
  views/<template>/errors/404.ejs, errors/error.ejs (EJS, optional) error pages for browser pages (D-0074)
34
34
  views/<template>/Pages/Error.vue (Inertia, with inertia.errorPage) the error page component
35
35
  views/<template>/ only the files that change
@@ -81,10 +81,10 @@ export default defineApp({
81
81
 
82
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
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).
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
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
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.
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. When several apps require the same plugin, dokebi-app declares it once to core with every distinct range joined (`^1.0.0 ^1.2.0`, so the provider must satisfy each app), required when any app requires it, with the first factory (`create`) given. Ranges that cannot meet (`^1.0.0` and `^2.0.0`) are refused at `createPlugin` with `DEPENDENCY_CONFLICT` naming both apps.
88
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
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
90
 
@@ -93,10 +93,43 @@ export default defineApp({
93
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
94
 
95
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.
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 (0.4.2: also one whose path reads as another host, such as `//other.host/…`), 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.
98
99
 
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
+ 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).
101
+
102
+ ### Forms: `errors`, `old` and `flash` in every view (0.4.1)
103
+
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:
105
+
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).
109
+
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
+ ```
131
+
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`.
100
133
 
101
134
  ### Mounting modules (D-0032)
102
135
 
@@ -236,6 +269,7 @@ The API of `createPlugin` is `{ names, resolve(request) }` (`AppGroupApi`). `res
236
269
  | Code | When |
237
270
  |---|---|
238
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
+ | `DEPENDENCY_CONFLICT` | at `createPlugin`: two apps (or an app and dokebi-app) require one plugin with version ranges no release satisfies together; the message names both apps and ranges, `details.needs` lists every requirement |
239
273
  | `INVALID_ENTRY` | the entry is not `{ apps: { <name>: defineApp(...) } }` (the cause of `INVALID_PLUGIN_INPUT`) |
240
274
  | `UNKNOWN_APP` | a domain pointing at an undefined app, or `apps.<app>` naming an undefined app |
241
275
  | `SEAL_PROVIDER_MISSING` | a `seal: true` domain exists but the `dokebi-seal` plugin does not (even without sockets) |
@@ -260,7 +294,7 @@ Debug logs (D-0047): `App domains configured` (domain → app/template, `(sealed
260
294
  - Apps do not import each other. Shared code goes into `src/shared/` (models, views) or a module.
261
295
  - 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
296
  - 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).
297
+ - 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).
264
298
 
265
299
  ## 8. References
266
300
 
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @dokebi/app 0.4.0
1
+ # @dokebi/app 0.4.2
2
2
 
3
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
 
@@ -86,6 +86,7 @@ export default defineApp({
86
86
 
87
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
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
+ - **HTML forms come back (0.4.1, D-0074 addendum 1):** with [@dokebi/session](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-session/README.md) registered, an HTML form post refused with 422 `VALIDATION_FAILED` flashes `errors` and `old` (without password-like fields) and answers 303 to the `Referer` of the same host, and every EJS page gets `data.errors`, `data.old` and `data.flash` (always objects, the flash read once per request), so the form shows `<%= data.old.title ?? '' %>` and `data.errors.title`. Without a session, or without a same-host Referer, the refused form gets `errors/422.ejs` (else `errors/error.ejs`) with `fields`, `errors` and `old`. A Referer whose path reads as another host (`//other.host/…`) is no way back (0.4.2). Scripts (`fetch`, XHR, Bearer, JSON, Inertia) keep their JSON. Needs @dokebi/web ^0.4.2.
89
90
  - **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
91
  - The module's `routes` are registered with this app's route constraint and the prefix; handlers get `page.module` and `page.base`.
91
92
  - The module's `sockets` are registered under the prefix. Their tenant is `<namespace>:<tenant>`, as for app sockets.
@@ -100,6 +101,7 @@ export default defineApp({
100
101
  6. shared views
101
102
  - **`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
103
  - `get` and `getDependency` of the app context (`app`) allow only the plugins listed in `requires`. Controller factories have the same limit.
104
+ - A plugin several apps require is checked against every app's version range (the ranges are joined for core); ranges that cannot meet stop `createPlugin` with `DEPENDENCY_CONFLICT`, naming both apps.
103
105
  - 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
106
  - 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
107
 
package/dist/errors.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
2
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';
3
+ export type AppErrorCode = 'INVALID_DEFINITION' | 'INVALID_ENTRY' | 'DEPENDENCY_CONFLICT' | 'UNKNOWN_APP' | 'SEAL_PROVIDER_MISSING' | 'VIEW_ENGINE_MISSING' | 'VIEWS_MISSING' | 'REALTIME_UNAVAILABLE' | 'NAMESPACE_FORBIDDEN' | 'INVALID_TARGET' | 'NOT_REQUIRED' | 'NOT_READY';
4
4
  /** Errors of @dokebi/app; compare `code`, not the class (another installed copy may throw). */
5
5
  export declare class AppError extends DokebiError<AppErrorCode> {
6
6
  constructor(code: AppErrorCode, message: string, options?: DokebiErrorOptions);
package/dist/errors.js CHANGED
@@ -2,6 +2,7 @@ import { DokebiError } from '@dokebi/core';
2
2
  const FIX = {
3
3
  INVALID_DEFINITION: 'defineApp takes requires, controllers, views (a file: URL), inertia, modules ({ "/prefix": defineModule(...) }), shared, routes, sockets, events, setup, start and drain; hooks are functions.',
4
4
  INVALID_ENTRY: 'Pass { apps: { <name>: defineApp(...) } } (src/dokebi.generated.ts does); names match ^[a-z][a-z0-9-]{0,31}$.',
5
+ DEPENDENCY_CONFLICT: 'Two apps (or an app and dokebi-app) require one plugin with version ranges no release satisfies together: align requires of defineApp in src/apps/<app>/app.ts, or update the app that needs the older major.',
5
6
  UNKNOWN_APP: 'Every app named in options.dokebi-app.domains.<host>.app and options.dokebi-app.apps must be defined (npx dokebi app add <name>, or remove the entry from dokebi.yaml).',
6
7
  SEAL_PROVIDER_MISSING: 'Register the dokebi-seal plugin (npx dokebi add @dokebi/seal), or remove seal: true from options.dokebi-app.domains.',
7
8
  VIEW_ENGINE_MISSING: 'Install the view plugin the app uses: npx dokebi add @dokebi/template-ejs (views) or npx dokebi add @dokebi/template-inertia (inertia).',
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type ControllerDefinition } from '@dokebi/controller';
2
2
  import { type Awaitable, type Plugin, type PluginContext, type PluginDependency } from '@dokebi/core';
3
- import type { WebErrorResponse, WebRoute } from '@dokebi/web';
3
+ import { type WebErrorResponse, type WebRoute } from '@dokebi/web';
4
4
  import type { FastifyReply, FastifyRequest } from 'fastify';
5
5
  export { AppError, type AppErrorCode } from './errors.js';
6
6
  export { type AppPluginOptions, options } from './options.js';
@@ -287,3 +287,10 @@ export interface AppGroupApi {
287
287
  resolve(request: FastifyRequest): AppInfo | undefined;
288
288
  }
289
289
  export declare const createPlugin: import("@dokebi/core").PluginFactory<AppGroupApi>;
290
+ /**
291
+ * The semver AND of two ranges, `||` included: every pair of alternatives joined with a space,
292
+ * unsatisfiable pairs left out. Joining whole ranges with a space is wrong for `||`
293
+ * (`^1 || ^2` and `^2` would read as `^1 || (^2 ^2)` and accept 1.x; ISSUE-0006 recheck).
294
+ * An empty string: no version satisfies both.
295
+ */
296
+ export declare function andRanges(a: string, b: string): string;
package/dist/index.js CHANGED
@@ -2,9 +2,13 @@ import { stat } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { types } from 'node:util';
4
4
  import { createControllers, } from '@dokebi/controller';
5
- import { definePlugin, dependencyOf, optionalDependency, } from '@dokebi/core';
6
- import { dependency as web } from '@dokebi/web/dependency';
5
+ import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
6
+ import { formBackTarget, formFieldErrors, formOldInput, isFormSubmission, } from '@dokebi/web';
7
7
  import { realtime, viewEngines, } from '@dokebi/web/points';
8
+ import Range from 'semver/classes/range.js';
9
+ import intersects from 'semver/ranges/intersects.js';
10
+ import minVersion from 'semver/ranges/min-version.js';
11
+ import validRange from 'semver/ranges/valid.js';
8
12
  import { AppError } from './errors.js';
9
13
  import { options as declaration } from './options.js';
10
14
  export { AppError } from './errors.js';
@@ -109,6 +113,31 @@ function parseEntry(input) {
109
113
  }
110
114
  return apps;
111
115
  }
116
+ /**
117
+ * dokebi-web 0.4.2 or later: the HTML form validation redirect uses its form helpers (D-0074
118
+ * addendum 1; 0.4.2 never answers a Referer path that reads as another host, ISSUE-0006 A02). A local descriptor instead of '@dokebi/web/dependency' (whose range stays ^0.4.0
119
+ * for the plugins that need nothing newer).
120
+ */
121
+ const web = providerDependency({
122
+ name: 'dokebi-web',
123
+ version: '^0.4.2',
124
+ packageName: '@dokebi/web',
125
+ load: () => import('@dokebi/web'),
126
+ });
127
+ const session = optionalDependency({ name: 'dokebi-session', version: '^0.4.0' });
128
+ const plainRecord = (value) => value !== null &&
129
+ typeof value === 'object' &&
130
+ !Array.isArray(value) &&
131
+ [Object.prototype, null].includes(Object.getPrototypeOf(value));
132
+ /** Splits a taken flash into the view data; fresh objects for every request. */
133
+ function viewFlash(taken) {
134
+ const { errors, old, ...rest } = taken ?? {};
135
+ return {
136
+ errors: plainRecord(errors) ? { ...errors } : {},
137
+ old: plainRecord(old) ? { ...old } : {},
138
+ flash: rest,
139
+ };
140
+ }
112
141
  /**
113
142
  * The seal plugin (D-0059 §4, D-0062), looked up by name only: a host with `seal: true` needs it
114
143
  * (it serves `/dokebi/seal/*`, seals the sockets through the websocket transport and fills the
@@ -315,8 +344,65 @@ class AppRuntime {
315
344
  for (const app of this.options.apps.keys())
316
345
  if (!this.apps.has(app))
317
346
  throw new AppError('UNKNOWN_APP', `dokebi-app apps.${app} names an app that is not defined (defined: ${[...this.apps.keys()].join(', ') || 'none'})`);
318
- const http = context.getDependency(web);
347
+ const http = context.getDependency(this.#declaredFor(web.name));
319
348
  const logger = context.logger;
349
+ const sessions = context.getOptionalDependency(this.#declaredFor(session.name));
350
+ // D-0074 addendum 1: the flash of a request, taken once (every render of the request shares
351
+ // it). Paths the session plugin excludes have no session (`request.session` is null).
352
+ const flashes = new WeakMap();
353
+ const sessionOf = (request) => sessions && request.session ? sessions.of(request) : undefined;
354
+ const flashOf = (request) => {
355
+ const current = sessionOf(request);
356
+ if (!current)
357
+ return undefined;
358
+ let taken = flashes.get(request);
359
+ if (!taken) {
360
+ taken = current.takeFlash().then(viewFlash);
361
+ flashes.set(request, taken);
362
+ }
363
+ return taken;
364
+ };
365
+ /**
366
+ * D-0074 addendum 1: an HTML form (urlencoded or multipart body) refused with 422
367
+ * VALIDATION_FAILED goes back to the page it came from — `errors` and `old` flashed in the
368
+ * session, 303 to the Referer of this host — when the request has a session and a way back.
369
+ * False otherwise: the error view (errors/422.ejs, errors/error.ejs) or dokebi-web's page.
370
+ */
371
+ const formBack = async (response, app) => {
372
+ const { request, reply, status, body } = response;
373
+ if (status !== 422 || !isFormSubmission(request.headers))
374
+ return false;
375
+ const errors = formFieldErrors(body);
376
+ if (!errors)
377
+ return false;
378
+ const current = sessionOf(request);
379
+ const target = current ? formBackTarget(request, http.requestHost(request)) : undefined;
380
+ if (!current || target === undefined) {
381
+ if (logger.isEnabled('debug'))
382
+ logger.log('debug', 'App form validation answered with the error view', {
383
+ app,
384
+ reason: current ? 'no-way-back' : 'no-session',
385
+ method: request.method,
386
+ route: request.routeOptions.url ?? 'unmatched',
387
+ });
388
+ return false;
389
+ }
390
+ await current.flash('errors', errors);
391
+ const old = formOldInput(request.body);
392
+ if (old)
393
+ await current.flash('old', old);
394
+ if (logger.isEnabled('debug'))
395
+ logger.log('debug', 'App form validation redirect', {
396
+ app,
397
+ method: request.method,
398
+ route: request.routeOptions.url ?? 'unmatched',
399
+ fields: Object.keys(errors).slice(0, 32),
400
+ old: old ? Object.keys(old).length : 0,
401
+ target: target.split('?', 1)[0]?.slice(0, 200),
402
+ });
403
+ reply.redirect(target, 303);
404
+ return true;
405
+ };
320
406
  // D-0063 §5: view engines and realtime transports by name, whoever contributes them.
321
407
  const engines = byKey(context, viewEngines, 'name');
322
408
  const transports = byKey(context, realtime, 'kind');
@@ -337,7 +423,8 @@ class AppRuntime {
337
423
  transports: [...transports.keys()],
338
424
  });
339
425
  // Fail closed (D-0059 §4): a sealed host without the seal plugin would talk plain text.
340
- if (sealedDomains.length && context.getOptionalDependency(seal) === undefined)
426
+ if (sealedDomains.length &&
427
+ context.getOptionalDependency(this.#declaredFor(seal.name)) === undefined)
341
428
  throw new AppError('SEAL_PROVIDER_MISSING', `Domains ${sealedDomains.slice(0, 8).join(', ')} set seal: true; register the dokebi-seal plugin`);
342
429
  /** The engine an app needs, or VIEW_ENGINE_MISSING naming the package that offers it. */
343
430
  const engine = (name, app) => {
@@ -542,13 +629,25 @@ class AppRuntime {
542
629
  ...appChain(template),
543
630
  ];
544
631
  };
545
- // `sealed` and the app's shared data under the page data, computed once per render call.
546
- const withShared = (view, request, info, sealed) => {
547
- const data = async (own) => ({
548
- sealed,
549
- ...(await definition.shared?.(request, { app: info })),
550
- ...own,
551
- });
632
+ // `sealed`, the session flash (`errors`, `old`, `flash`; D-0074 addendum 1) and the app's
633
+ // shared data under the page data, computed once per render call. An error view passes
634
+ // its own `errors` and `old` and leaves the flash to the next page.
635
+ const withShared = (view, request, info, sealed, pageFlash = true) => {
636
+ const data = async (own) => {
637
+ const taken = (pageFlash ? await flashOf(request) : undefined) ?? viewFlash(undefined);
638
+ const result = {
639
+ sealed,
640
+ ...taken,
641
+ ...(await definition.shared?.(request, { app: info })),
642
+ ...own,
643
+ };
644
+ // The handler's own `errors` and `old` win field by field.
645
+ if (plainRecord(own.errors))
646
+ result.errors = { ...taken.errors, ...own.errors };
647
+ if (plainRecord(own.old))
648
+ result.old = { ...taken.old, ...own.old };
649
+ return result;
650
+ };
552
651
  return Object.freeze({
553
652
  render: async (name, own, options) => view.render(name, await data(own), options),
554
653
  reply: async (reply, name, own, options) => view.reply(reply, name, await data(own), options),
@@ -637,15 +736,20 @@ class AppRuntime {
637
736
  }
638
737
  };
639
738
  // D-0074 §3-4: the error answers of this app's hosts. Inertia first (the validation
640
- // redirect, the app's error page component), then for an HTML answer the app's error view:
641
- // `errors/<status>` → `errors/error` in <app>/<template> → <app>/default → shared views.
739
+ // redirect, the app's error page component), then for an HTML answer the form redirect
740
+ // (addendum 1) and the app's error view: `errors/<status>` → `errors/error` in
741
+ // <app>/<template> → <app>/default → shared views.
642
742
  const errorViews = new Map();
643
743
  answers.set(name, async (response, entry) => {
644
744
  if (inertiaApi && typeof inertiaApi.answerError === 'function') {
645
745
  if (await inertiaApi.answerError(response))
646
746
  return true;
647
747
  }
648
- if (response.format !== 'html' || !ejsRoot)
748
+ if (response.format !== 'html')
749
+ return false;
750
+ if (await formBack(response, name))
751
+ return true;
752
+ if (!ejsRoot)
649
753
  return false;
650
754
  const { info, sealed } = entry;
651
755
  let view = errorViews.get(info.template);
@@ -662,13 +766,17 @@ class AppRuntime {
662
766
  if (!page)
663
767
  return false;
664
768
  const fields = Array.isArray(body.fields) ? body.fields : [];
665
- await withShared(view, request, info, sealed).reply(reply, page, {
769
+ await withShared(view, request, info, sealed, false).reply(reply, page, {
666
770
  status,
667
771
  title: `${status} ${STATUS_CODES[status] ?? 'Error'}`,
668
772
  error: body.error,
669
773
  message: typeof body.message === 'string' ? body.message : null,
670
774
  hint: typeof body.hint === 'string' ? body.hint : null,
671
775
  fields,
776
+ // A refused form without a way back (no session, no Referer of this host): an
777
+ // errors/422.ejs can show the form again with these (D-0074 addendum 1).
778
+ errors: formFieldErrors(body) ?? {},
779
+ old: (status === 422 && formOldInput(request.body)) || {},
672
780
  // Development only (dokebi-web already cut `fix` from a production body).
673
781
  fix: typeof body.fix === 'string' ? body.fix : null,
674
782
  stack: !production && status >= 500 && error instanceof Error ? (error.stack ?? null) : null,
@@ -785,22 +893,105 @@ function missingViews(name) {
785
893
  }
786
894
  export const createPlugin = definePlugin({
787
895
  name: 'dokebi-app',
788
- version: '0.4.0',
896
+ version: '0.4.2',
789
897
  core: '^0.4.0',
790
898
  options: declaration,
791
899
  entry: parseEntry,
792
900
  // Template and realtime plugins are found through these points, not by name (D-0063 §5).
793
901
  collects: [viewEngines, realtime],
794
- dependencies: ({ entry }) => {
795
- const apps = [...(entry ?? new Map()).values()];
796
- const list = [web, seal];
797
- for (const app of apps)
798
- for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})]) {
799
- const dependency = requirement(item);
800
- if (!list.some((existing) => existing.name === dependency.name))
801
- list.push(dependency);
802
- }
803
- return list;
804
- },
902
+ dependencies: ({ entry }) => mergeRequirements(entry ?? new Map()),
805
903
  instance: ({ options, entry, dependencies }) => new AppRuntime(settings(options), entry ?? new Map(), dependencies),
806
904
  });
905
+ /**
906
+ * Core takes one requirement per plugin name, so the requirements of every app (and dokebi-app's
907
+ * own web, seal and session) are merged per name (ISSUE-0006 A12): the version is every distinct
908
+ * range joined with a space (semver AND, so core checks the provider against each app's range),
909
+ * the result is optional only when every consumer is optional, and the factory (`create`) of the
910
+ * first consumer that has one is kept. Ranges that cannot meet are refused here, before start,
911
+ * with `DEPENDENCY_CONFLICT` naming the apps: no provider version could satisfy both.
912
+ */
913
+ function mergeRequirements(apps) {
914
+ const needs = new Map();
915
+ const add = (consumer, dependency) => {
916
+ if (!validRange(dependency.version))
917
+ throw new AppError('INVALID_DEFINITION', `${consumer === 'dokebi-app' ? 'dokebi-app' : `App ${consumer}`} requires ${dependency.name} with an invalid version range: ${JSON.stringify(dependency.version)}`);
918
+ const list = needs.get(dependency.name);
919
+ if (list)
920
+ list.push({ consumer, dependency });
921
+ else
922
+ needs.set(dependency.name, [{ consumer, dependency }]);
923
+ };
924
+ for (const dependency of [web, seal, session])
925
+ add('dokebi-app', dependency);
926
+ for (const [name, app] of apps)
927
+ for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})])
928
+ add(name, requirement(item));
929
+ const merged = [];
930
+ for (const [name, list] of needs) {
931
+ const first = list[0];
932
+ const ranges = [];
933
+ // The AND of every distinct range; `||` alternatives are combined pairwise (andRanges).
934
+ let combined = '';
935
+ for (const need of list) {
936
+ if (ranges.includes(need.dependency.version))
937
+ continue;
938
+ const next = ranges.length
939
+ ? andRanges(combined, need.dependency.version)
940
+ : need.dependency.version;
941
+ if (!next) {
942
+ // Name the consumer it clashes with; when only the combination fails, name them all.
943
+ const earlier = list.slice(0, list.indexOf(need));
944
+ const clash = earlier.find((other) => !intersects(other.dependency.version, need.dependency.version));
945
+ const others = clash ? [clash] : earlier;
946
+ throw new AppError('DEPENDENCY_CONFLICT', `No version of ${name} satisfies both ${others.map(label).join(' and ')} and ${label(need)}`, {
947
+ details: {
948
+ plugin: name,
949
+ needs: list.map((each) => ({
950
+ consumer: each.consumer,
951
+ version: each.dependency.version,
952
+ optional: each.dependency.optional === true,
953
+ })),
954
+ },
955
+ });
956
+ }
957
+ ranges.push(need.dependency.version);
958
+ combined = next;
959
+ }
960
+ const optional = list.every((need) => need.dependency.optional);
961
+ const create = list.find((need) => need.dependency.create)?.dependency.create;
962
+ // One consumer, or all the same: keep the descriptor object itself.
963
+ const same = list.every((need) => need.dependency.version === first.dependency.version &&
964
+ Boolean(need.dependency.optional) === optional);
965
+ if (same && (first.dependency.create || !create)) {
966
+ merged.push(first.dependency);
967
+ continue;
968
+ }
969
+ merged.push(Object.freeze({
970
+ name,
971
+ version: combined,
972
+ ...(optional ? { optional: true } : {}),
973
+ ...(create ? { create } : {}),
974
+ }));
975
+ }
976
+ return merged;
977
+ }
978
+ /**
979
+ * The semver AND of two ranges, `||` included: every pair of alternatives joined with a space,
980
+ * unsatisfiable pairs left out. Joining whole ranges with a space is wrong for `||`
981
+ * (`^1 || ^2` and `^2` would read as `^1 || (^2 ^2)` and accept 1.x; ISSUE-0006 recheck).
982
+ * An empty string: no version satisfies both.
983
+ */
984
+ export function andRanges(a, b) {
985
+ const parts = [];
986
+ for (const left of new Range(a).set)
987
+ for (const right of new Range(b).set) {
988
+ const combo = [...left, ...right]
989
+ .map((comparator) => comparator.value)
990
+ .filter(Boolean)
991
+ .join(' ') || '*';
992
+ if (minVersion(combo) !== null && !parts.includes(combo))
993
+ parts.push(combo);
994
+ }
995
+ return parts.join(' || ');
996
+ }
997
+ const label = (need) => `${need.consumer === 'dokebi-app' ? 'dokebi-app' : `app ${need.consumer}`} (${need.dependency.version})`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/app",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "Multiple apps per project for Dokebi: pick the app and template by request domain, with EJS and Inertia skeletons.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -37,12 +37,15 @@
37
37
  "typecheck": "tsc -p tsconfig.test.json --noEmit",
38
38
  "test": "node -e \"require('node:fs').rmSync('.tmp/tests',{recursive:true,force:true})\" && tsc -p tsconfig.test.json && node --test .tmp/tests/tests/*.test.js"
39
39
  },
40
+ "dependencies": {
41
+ "semver": "7.8.5"
42
+ },
40
43
  "peerDependencies": {
41
44
  "@dokebi/controller": "^0.4.0",
42
45
  "@dokebi/core": "^0.4.0",
43
46
  "@dokebi/module": "^0.4.0",
44
47
  "@dokebi/template-ejs": "^0.4.0",
45
- "@dokebi/web": "^0.4.0",
48
+ "@dokebi/web": "^0.4.2",
46
49
  "fastify": "^5.12.7"
47
50
  },
48
51
  "peerDependenciesMeta": {
@@ -52,11 +55,13 @@
52
55
  },
53
56
  "devDependencies": {
54
57
  "@dokebi/module": "^0.4.0",
58
+ "@dokebi/session": "^0.4.0",
55
59
  "@dokebi/sse": "^0.4.0",
56
60
  "@dokebi/template-ejs": "^0.4.0",
57
61
  "@dokebi/template-inertia": "^0.4.0",
58
62
  "@dokebi/websocket": "^0.4.0",
59
63
  "@dokebi/websocket-hub": "^0.4.0",
64
+ "@types/semver": "7.8.0",
60
65
  "ws": "8.22.0"
61
66
  },
62
67
  "dokebi": {
@@ -66,7 +71,7 @@
66
71
  "dependencies": [
67
72
  {
68
73
  "name": "dokebi-web",
69
- "version": "^0.4.0",
74
+ "version": "^0.4.2",
70
75
  "package": "@dokebi/web"
71
76
  },
72
77
  {
@@ -83,6 +88,11 @@
83
88
  "name": "dokebi-seal",
84
89
  "version": "^0.4.0",
85
90
  "optional": true
91
+ },
92
+ {
93
+ "name": "dokebi-session",
94
+ "version": "^0.4.0",
95
+ "optional": true
86
96
  }
87
97
  ],
88
98
  "collects": [
@@ -1,5 +1,8 @@
1
1
  <%# Every other error page of this app (D-0074): 403, 500, an HTML form refused with 422 (the
2
- fields are listed). Make errors/<status>.ejs for a status that needs its own page. %>
2
+ fields are listed). Make errors/<status>.ejs for a status that needs its own page.
3
+ With @dokebi/session (npx dokebi add @dokebi/session) a refused form goes back to its own
4
+ page instead, which shows data.errors.<field> and data.old.<field>; this page is the
5
+ fallback (no session, no Referer of this host). Data also has errors and old. %>
3
6
  <main>
4
7
  <h1><%= data.title %></h1>
5
8
  <p><% if (data.message) { %><%= data.message %><% } %></p>
@@ -10,7 +10,7 @@ import { createApp, createSSRApp, h } from 'vue';
10
10
  if (document.querySelector('script[data-page][data-sealed="true"]'))
11
11
  await (await import(/* @vite-ignore */ '/dokebi/seal/http.mjs')).sealInertia(http);
12
12
 
13
- const files = import.meta.glob('./*/{Layout,Pages/*}.vue', { eager: true });
13
+ const files = import.meta.glob('./*/{Layout,Pages/**/*}.vue', { eager: true });
14
14
  const first = JSON.parse(document.querySelector('script[data-page]')?.textContent || '{}');
15
15
  const template = first.props?.app?.template ?? 'default';
16
16
  const pick = (path) => files[`./${template}/${path}.vue`] ?? files[`./default/${path}.vue`];
@@ -5,7 +5,7 @@
5
5
  import { createInertiaApp } from '@inertiajs/vue3';
6
6
  import { renderToString } from 'vue/server-renderer';
7
7
 
8
- const files = import.meta.glob('./*/{Layout,Pages/*}.vue', { eager: true });
8
+ const files = import.meta.glob('./*/{Layout,Pages/**/*}.vue', { eager: true });
9
9
 
10
10
  export async function render(page) {
11
11
  const template = page.props?.app?.template ?? 'default';