@dokebi/web 0.4.9 → 0.4.11

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
@@ -10,6 +10,8 @@ npx dokebi add @dokebi/web # src/infra/web/extension.ts (the requires list
10
10
 
11
11
  > `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 …`.
12
12
 
13
+ **One fastify per project (0.4.10, D-0224).** `fastify` is a peer dependency of @dokebi/web at the exact version it is built and tested on (5.12.8); every other Dokebi plugin takes it as a peer range (`^5.12.7`). npm installs one copy at the project root, so the `FastifyRequest` of web's hooks (`routeHook`, `appOf`) carries the type augmentations of session, auth and i18n (`request.session`, `request.auth`, `request.i18n`). Do not add another `fastify` version to the project's own package.json; `npm ls fastify` shows one copy. Web 0.4.9 and earlier kept their own nested copy, so the types of web's hooks missed those augmentations (TS2339 / TS2345); upgrading web removes it.
14
+
13
15
  ```yaml
14
16
  dokebi-web:
15
17
  host: 127.0.0.1 # default; 0.0.0.0 to accept outside traffic (a front proxy is recommended)
@@ -139,7 +141,7 @@ http.route({ method: 'POST', url: '/import', handler: async (request, reply) =>
139
141
  | `formLimits` | `{ oldInputMaxChars, refererMaxLength }` of these options (`formOldInputMaxChars`, `formRefererMaxLength`, D-0114): pass it to `formOldInput` and `formBackTarget` (@dokebi/app and template-inertia do) |
140
142
  | `errorResponder(responder)` | adds an error responder (D-0074, §6): asked before web writes an error answer, the last added first; `(response) => boolean \| Promise<boolean>`, true when it sent the answer itself. @dokebi/app (HTML form redirect, error views) and template-inertia (validation redirect, error page) use it. Setup only |
141
143
  | `routeConfig({ key, plugin, check, routes? })` | declares a route `config` key this plugin reads (D-0076 §5, for example `auth`, `csrf`). Setup only. At start every route's value goes through `check(value) → string \| undefined` (a sentence when wrong), and a key in another case or at most two edits away from a declared key (`csfr`) is a likely typo; either fails the start with `INVALID_ROUTE_CONFIG` (`details.problems`, error log `WEB_ROUTE_CONFIG_INVALID`). When nothing is wrong, the optional `routes(list)` is called once with every route that sets the key (`{ method, url, value }`, `WebRouteConfigUse`; the HEAD twin of a GET left out), so the plugin can report them (@dokebi/csrf logs the routes with `csrf: false`). The plugin reads the value per request from `request.routeOptions.config[key]`. Keys of other Fastify plugins (`rateLimit`) are left alone |
142
- | `routeHook({ plugin, route })` | asks `route(info)` once per route what to add to that route only (D-0076 §3.8; dokebi-auth's route protection). `info` is `{ method, url, config, constraints, configFixed }` (`constraints.dokebiApp` names a dokebi-app app); return `undefined` (the route is left untouched: no cost per request) or `{ preValidation?, onResponse?, completed?, data? }`: an async preValidation hook that runs for that route only (after the body is parsed, before schema validation), a response observer (`onResponse` or the cheaper `completed`, below), and values under symbol keys merged into the route's config (`request.routeOptions.config[symbol]`). Routes added before the call are offered when it is made (`configFixed: true`: their config was already copied, so only `preValidation`/`onResponse`/`completed`); health routes are never offered. Setup only; a malformed result is `INVALID_ARGUMENT` |
144
+ | `routeHook({ plugin, route })` | asks `route(info)` once per route what to add to that route only (D-0076 §3.8; dokebi-auth's route protection). `info` is `{ method, url, config, constraints, configFixed }` (`constraints.dokebiApp` names a dokebi-app app); return `undefined` (the route is left untouched: no cost per request) or `{ preValidation?, onResponse?, completed?, sent?, data? }`: an async preValidation hook that runs for that route only (after the body is parsed, before schema validation), a response observer (`onResponse` or the cheaper `completed`, below), an observer of the body the route answered (`sent`, 0.4.11, below), and values under symbol keys merged into the route's config (`request.routeOptions.config[symbol]`). Routes added before the call are offered when it is made (`configFixed: true`: their config was already copied, so only `preValidation`/`onResponse`/`completed`); health routes are never offered. Setup only; a malformed result is `INVALID_ARGUMENT` |
143
145
  | `contentSecurityPolicy({ plugin, directives })` | adds CSP sources for the pages of a plugin (D-0149, §2.4): `{ plugin: 'dokebi-seal', directives: { 'script-src': ["'wasm-unsafe-eval'"] } }`, appended to each directive. Setup only; a malformed one is `INVALID_ARGUMENT` |
144
146
  | `route({ ..., config: { securityHeaders } })` · `route({ ..., config: { overload: false } })` · `route({ ..., config: { readiness: false } })` | per route: `securityHeaders: false` or the settings to change (D-0149, §2.4); `overload: false` serves the route while the server sheds load (D-0150, §2.5); `readiness: false` serves it while a required dependency is down and while the app drains (§3). Checked at start (`INVALID_ROUTE_CONFIG`) |
145
147
  | `route({ ..., config: { requestTimeoutMs } })` | this route's time to receive its body after the headers, in whole ms (1..2147483647), instead of the `requestTimeoutMs` option: give upload routes the time their largest file needs on a slow link. Checked at start (`INVALID_ROUTE_CONFIG`); past it 408 `REQUEST_TIMEOUT` (`data.timeoutMs`) |
@@ -450,3 +452,5 @@ References: `examples/29-extension` (errorBody, unavailable), `examples/22-web`
450
452
  `routeHook` can return `onResponse(request, reply, done)`: a callback hook appended after existing response hooks, including on routes registered earlier. Call `done` once. The response has completed and cannot be changed; `reply.elapsedTime` is milliseconds. Routes left untouched receive no hook.
451
453
 
452
454
  An observer that only reads the finished response returns `completed(request, reply, elapsedMs)` instead (type `WebRouteCompleted`): called synchronously once the response was written, from web's own response tracking, so the route gets no Fastify `onResponse` hook (Fastify adds response listeners and runs its hook chain on every request of a route that has one). Not called when the client left before the response was written (before its head or in its body). `elapsedMs` runs from the request's first `onRequest` step to the response's close. Several observers run in the order their route hooks were registered; a throw is logged at error level as `HTTP response hook failed` (`WEB_RESPONSE_HOOK_FAILED`, counted per route per `logRepeatWindowMs`) and the next observer still runs. Works on routes registered earlier, like `onResponse`. `@dokebi/metrics` uses it for bounded response collection (measured 2026-10-31: `web-metrics/web` 0.943 with `onResponse`, 0.972 with `completed`).
455
+
456
+ An observer of what a route answered returns `sent(request, reply, payload)` (type `WebRouteSent`, 0.4.11, D-0225): called synchronously from web's own `onSend` step with the body as the route answered it — before the seal, the sealed-form redirect and compression — and the final status in `reply.statusCode`. `payload` is what Fastify hands to `onSend`: a string (a serialized JSON answer), a Buffer, a stream (never read it: that would consume the answer) or null/undefined. When an error answer replaces the first one (a later `onSend` step failed), it is called again with that answer: the last call is what went out. It cannot change the payload; a throw is logged like a `completed` observer's (`WEB_RESPONSE_HOOK_FAILED`) and the answer is sent unchanged. Works on routes registered earlier. A request of a route without one costs one flag read. `@dokebi/audit` uses it to keep what a request answered with its audit rows (`requests.enabled`).
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ export { options, type WebOptions } from './options.js';
19
19
  export { APP_NAME, APP_NAMES_MAX, appOption, appUrlMatch, pluginRouteIds, ROUTE_ID, ROUTE_OWNER, routeIdsOption, routeNamespace, type WebAppRouting, type WebAppSetting, type WebAppUrlMatch, type WebPluginRouteIds, type WebRouteOwner, } from './points.js';
20
20
  export { errorFormat, FORM_SUBMISSION_HEADER, requestErrorFormat, SEALED_FETCH_HEADER, type WebErrorFormat, type WebErrorResponder, type WebErrorResponse, type WebFieldError, } from './responses.js';
21
21
  export type { WebRouteConfigKey, WebRouteConfigUse } from './route-config.js';
22
- export type { WebRouteAddition, WebRouteCompleted, WebRouteHook, WebRouteInfo, WebRouteOnResponse, WebRoutePreValidation, } from './route-hooks.js';
22
+ export type { WebRouteAddition, WebRouteCompleted, WebRouteHook, WebRouteInfo, WebRouteOnResponse, WebRoutePreValidation, WebRouteSent, } from './route-hooks.js';
23
23
  export type { WebDuplicateRouteId, WebRouteEntry } from './route-table.js';
24
24
  export { SEALED_LOCATION_HEADER, SEALED_PATH_HEADER, type WebSealCodec, type WebSealCodecProvider, type WebSealer, type WebSealRequest, type WebSealSetting, } from './seal.js';
25
25
  export { DEFAULT_DIRECTIVES, type WebCspContribution, type WebSecurityHeadersRoute, } from './security-headers.js';
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ import { options as declaration } from './options.js';
21
21
  import { errorTranslators, pluginRouteIds, } from './points.js';
22
22
  import { clientStatus, dokebiError, errorAnswer, errorPage, FORM_SUBMISSION_HEADER, productionBody, requestErrorFormat, sendableDetails, validAnswer, } from './responses.js';
23
23
  import { MAX_TIMEOUT_MS, RouteConfigKeys } from './route-config.js';
24
- import { COMPLETED, RouteHooks, } from './route-hooks.js';
24
+ import { COMPLETED, RouteHooks, SENT, } from './route-hooks.js';
25
25
  import { RouteTable } from './route-table.js';
26
26
  import { checkSealSetting, formMarkerRefusal, RECORDED, sealExclude, sealedFormRedirect, WebSealing, } from './seal.js';
27
27
  import { contributionProblem, SecurityHeaders, } from './security-headers.js';
@@ -734,6 +734,10 @@ class WebOwner {
734
734
  this.#overload(options.overload);
735
735
  this.server.addHook('onSend', (request, reply, payload, done) => {
736
736
  reply.raw[SENDING] = true;
737
+ // D-0225: the route's `sent` observers see the body as the route answered it (before the
738
+ // seal, the sealed-form redirect and compression). One flag read while no hook asked.
739
+ if (this.#routeHooks.sending)
740
+ this.#sent(reply, payload);
737
741
  if (!http1(request)) {
738
742
  // HTTP/2 has no connection header (RFC 9113 §8.2.2): one set by Fastify (its 413 and
739
743
  // every body parse error) or a plugin would only be dropped by Node with a process
@@ -1167,19 +1171,38 @@ class WebOwner {
1167
1171
  observe(reply.request, reply, elapsedMs);
1168
1172
  }
1169
1173
  catch (error) {
1170
- this.#responseHookFailures ??= new Repeats({ intervalMs: this.options.logRepeatWindowMs });
1171
- const route = reply.request.routeOptions.url ?? 'unmatched';
1172
- const repeated = this.#responseHookFailures.take(route);
1173
- if (repeated !== undefined)
1174
- this.context.logger.log('error', 'HTTP response hook failed', {
1175
- code: 'WEB_RESPONSE_HOOK_FAILED',
1176
- route,
1177
- repeated,
1178
- error: describeError(error),
1179
- });
1174
+ this.#responseHookFailed(reply, error);
1180
1175
  }
1181
1176
  }
1182
1177
  }
1178
+ /** The route's `sent` observers (route-hooks.ts, D-0225), from web's onSend step. */
1179
+ #sent(reply, payload) {
1180
+ const context = reply[ROUTE_CONTEXT];
1181
+ const observers = context?.config?.[SENT];
1182
+ if (observers === undefined || observers.length === 0)
1183
+ return;
1184
+ for (const observe of observers) {
1185
+ try {
1186
+ observe(reply.request, reply, payload);
1187
+ }
1188
+ catch (error) {
1189
+ this.#responseHookFailed(reply, error);
1190
+ }
1191
+ }
1192
+ }
1193
+ /** A response observer threw: logged (once per route and period), never answered. */
1194
+ #responseHookFailed(reply, error) {
1195
+ this.#responseHookFailures ??= new Repeats({ intervalMs: this.options.logRepeatWindowMs });
1196
+ const route = reply.request.routeOptions.url ?? 'unmatched';
1197
+ const repeated = this.#responseHookFailures.take(route);
1198
+ if (repeated !== undefined)
1199
+ this.context.logger.log('error', 'HTTP response hook failed', {
1200
+ code: 'WEB_RESPONSE_HOOK_FAILED',
1201
+ route,
1202
+ repeated,
1203
+ error: describeError(error),
1204
+ });
1205
+ }
1183
1206
  #responseClosed(response) {
1184
1207
  const incoming = response.req;
1185
1208
  if (incoming?.[BODY_TIMER] !== undefined)
@@ -1617,11 +1640,14 @@ class WebOwner {
1617
1640
  // info, with every bound address: `dokebi start` reads it to show where the app answers.
1618
1641
  // `localhost` binds both 127.0.0.1 and ::1, so there can be more than one.
1619
1642
  const scheme = this.#https ? 'https' : 'http';
1643
+ // fastify 5.12.8 types an entry as `AddressInfo | string` (a pipe or socket path, kept as is).
1620
1644
  const urls = this.server
1621
1645
  .addresses()
1622
- .map((bound) => bound.family === 'IPv6' || bound.family === 6
1623
- ? `${scheme}://[${bound.address}]:${bound.port}`
1624
- : `${scheme}://${bound.address}:${bound.port}`);
1646
+ .map((bound) => typeof bound === 'string'
1647
+ ? bound
1648
+ : bound.family === 'IPv6' || bound.family === 6
1649
+ ? `${scheme}://[${bound.address}]:${bound.port}`
1650
+ : `${scheme}://${bound.address}:${bound.port}`);
1625
1651
  this.context.logger.log('info', 'Web server listening', {
1626
1652
  address: this.#address,
1627
1653
  urls: urls.length ? urls : [this.#address],
@@ -2630,7 +2656,7 @@ class WebRuntime {
2630
2656
  }
2631
2657
  export const createPlugin = definePlugin({
2632
2658
  name: 'dokebi-web',
2633
- version: '0.4.9',
2659
+ version: '0.4.11',
2634
2660
  core: '^0.4.2',
2635
2661
  options: declaration,
2636
2662
  entry: (input) => new WebEntryInput(input),
@@ -26,12 +26,23 @@ export type WebRouteOnResponse = (request: FastifyRequest, reply: FastifyReply,
26
26
  * response's close. A throw is logged, never answered (the response is gone).
27
27
  */
28
28
  export type WebRouteCompleted = (request: FastifyRequest, reply: FastifyReply, elapsedMs: number) => void;
29
+ /**
30
+ * Observes the body a response of this route is about to send (D-0225), as the route answered it:
31
+ * synchronous, in dokebi-web's own onSend step before sealing, the sealed-form redirect and
32
+ * compression. `payload` is what Fastify hands to onSend — a string (a serialized JSON answer),
33
+ * a Buffer, a stream (never read it: that would consume the answer), or null/undefined. Called
34
+ * again when an error answer replaces the first (the last call is the answer that went out). A
35
+ * throw is logged, never answered; the payload is never changed.
36
+ */
37
+ export type WebRouteSent = (request: FastifyRequest, reply: FastifyReply, payload: unknown) => void;
29
38
  /**
30
39
  * The observers of one route under this key of its config, an array every route gets from
31
40
  * dokebi-web's onRoute (before Fastify copies the config), so hooks registered later still add
32
41
  * to it. Read per request through the route context.
33
42
  */
34
43
  export declare const COMPLETED: unique symbol;
44
+ /** The `sent` observers of one route, kept like COMPLETED. */
45
+ export declare const SENT: unique symbol;
35
46
  /** What a route hook adds to one route. */
36
47
  export interface WebRouteAddition {
37
48
  /**
@@ -46,6 +57,11 @@ export interface WebRouteAddition {
46
57
  * Cheaper than `onResponse` for an observer that only reads the reply (metrics).
47
58
  */
48
59
  readonly completed?: WebRouteCompleted;
60
+ /**
61
+ * Called with the body this route's response is about to send (before sealing and
62
+ * compression); also works on earlier registered routes (D-0225).
63
+ */
64
+ readonly sent?: WebRouteSent;
49
65
  /**
50
66
  * Values merged into the route's config under symbol keys (`request.routeOptions.config[key]`).
51
67
  * Not for a route whose `configFixed` is true.
@@ -66,6 +82,8 @@ export declare class RouteHooks {
66
82
  get size(): number;
67
83
  /** True once a hook gave some route a `completed` observer (final at start). */
68
84
  get completing(): boolean;
85
+ /** True once a hook gave some route a `sent` observer (final at start). */
86
+ get sending(): boolean;
69
87
  add(definition: WebRouteHook): number;
70
88
  /** From onRoute: every registered hook decides for this route, and later ones will too. */
71
89
  offer(fields: RouteFields): void;
@@ -15,10 +15,12 @@ import { WebError } from './errors.js';
15
15
  * to it. Read per request through the route context.
16
16
  */
17
17
  export const COMPLETED = Symbol('dokebi-web.completed');
18
+ /** The `sent` observers of one route, kept like COMPLETED. */
19
+ export const SENT = Symbol('dokebi-web.sent');
18
20
  const EMPTY = Object.freeze({});
19
21
  function invalid(plugin, what) {
20
22
  return new WebError('INVALID_ARGUMENT', `The route hook of ${plugin} returned ${what}`, {
21
- fix: `Return undefined or { preValidation?: async (request, reply) => …, onResponse?: (request, reply, done) => …, completed?: (request, reply, elapsedMs) => …, data?: { [symbol]: value } } from the route hook of ${plugin}.`,
23
+ fix: `Return undefined or { preValidation?: async (request, reply) => …, onResponse?: (request, reply, done) => …, completed?: (request, reply, elapsedMs) => …, sent?: (request, reply, payload) => …, data?: { [symbol]: value } } from the route hook of ${plugin}.`,
22
24
  });
23
25
  }
24
26
  export class RouteHooks {
@@ -37,6 +39,11 @@ export class RouteHooks {
37
39
  return this.#completing;
38
40
  }
39
41
  #completing = false;
42
+ /** True once a hook gave some route a `sent` observer (final at start). */
43
+ get sending() {
44
+ return this.#sending;
45
+ }
46
+ #sending = false;
40
47
  add(definition) {
41
48
  const { plugin, route } = (definition ?? {});
42
49
  if (typeof plugin !== 'string' || plugin === '' || typeof route !== 'function')
@@ -55,7 +62,7 @@ export class RouteHooks {
55
62
  /** From onRoute: every registered hook decides for this route, and later ones will too. */
56
63
  offer(fields) {
57
64
  // A fresh list per route: Fastify's HEAD twin starts from a copy of the GET's config.
58
- fields.config = { ...fields.config, [COMPLETED]: [] };
65
+ fields.config = { ...fields.config, [COMPLETED]: [], [SENT]: [] };
59
66
  this.#seen?.push(fields);
60
67
  for (const hook of this.#hooks)
61
68
  this.#apply(hook, fields, false);
@@ -78,13 +85,15 @@ export class RouteHooks {
78
85
  return;
79
86
  if (addition === null || typeof addition !== 'object')
80
87
  throw invalid(hook.plugin, 'a non-object');
81
- const { preValidation, onResponse, completed, data } = addition;
88
+ const { preValidation, onResponse, completed, sent, data } = addition;
82
89
  if (preValidation !== undefined && typeof preValidation !== 'function')
83
90
  throw invalid(hook.plugin, 'a preValidation that is not a function');
84
91
  if (onResponse !== undefined && typeof onResponse !== 'function')
85
92
  throw invalid(hook.plugin, 'an onResponse that is not a function');
86
93
  if (completed !== undefined && typeof completed !== 'function')
87
94
  throw invalid(hook.plugin, 'a completed that is not a function');
95
+ if (sent !== undefined && typeof sent !== 'function')
96
+ throw invalid(hook.plugin, 'a sent that is not a function');
88
97
  if (data !== undefined) {
89
98
  if (data === null || typeof data !== 'object' || Object.keys(data).length > 0)
90
99
  throw invalid(hook.plugin, 'data that is not an object of symbol keys');
@@ -99,6 +108,10 @@ export class RouteHooks {
99
108
  fields.config[COMPLETED].push(completed);
100
109
  this.#completing = true;
101
110
  }
111
+ if (sent) {
112
+ fields.config[SENT].push(sent);
113
+ this.#sending = true;
114
+ }
102
115
  if (onResponse) {
103
116
  const existing = fields.onResponse;
104
117
  const response = this.#wrapResponse(onResponse);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/web",
3
- "version": "0.4.9",
3
+ "version": "0.4.11",
4
4
  "description": "Fastify 5 HTTP server owned by a Dokebi app: 503 before ready, health routes, drain and cluster handover.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -45,7 +45,8 @@
45
45
  "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"
46
46
  },
47
47
  "peerDependencies": {
48
- "@dokebi/core": "^0.4.2"
48
+ "@dokebi/core": "^0.4.2",
49
+ "fastify": "5.12.8"
49
50
  },
50
51
  "devDependencies": {
51
52
  "@dokebi/health": "0.4.1"
@@ -97,8 +98,7 @@
97
98
  ]
98
99
  },
99
100
  "dependencies": {
100
- "@fastify/under-pressure": "9.2.0",
101
- "fastify": "5.12.7"
101
+ "@fastify/under-pressure": "9.2.0"
102
102
  },
103
103
  "publishConfig": {
104
104
  "access": "public",