@dokebi/app 0.4.2 → 0.4.5

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/dist/index.js CHANGED
@@ -4,11 +4,11 @@ import { types } from 'node:util';
4
4
  import { createControllers, } from '@dokebi/controller';
5
5
  import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
6
6
  import { formBackTarget, formFieldErrors, formOldInput, isFormSubmission, } from '@dokebi/web';
7
- import { realtime, viewEngines, } from '@dokebi/web/points';
7
+ import { collectViewData, realtime, viewData, viewEngines, } from '@dokebi/web/points';
8
8
  import Range from 'semver/classes/range.js';
9
- import intersects from 'semver/ranges/intersects.js';
10
9
  import minVersion from 'semver/ranges/min-version.js';
11
10
  import validRange from 'semver/ranges/valid.js';
11
+ import { appPages, describePoint } from './describe.js';
12
12
  import { AppError } from './errors.js';
13
13
  import { options as declaration } from './options.js';
14
14
  export { AppError } from './errors.js';
@@ -114,13 +114,14 @@ function parseEntry(input) {
114
114
  return apps;
115
115
  }
116
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
117
+ * dokebi-web 0.4.3 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) and
119
+ * the view data point (`viewData`, `collectViewData`, D-0076 §5, 0.4.3). A local descriptor instead of '@dokebi/web/dependency' (whose range stays ^0.4.0
119
120
  * for the plugins that need nothing newer).
120
121
  */
121
122
  const web = providerDependency({
122
123
  name: 'dokebi-web',
123
- version: '^0.4.2',
124
+ version: '^0.4.3',
124
125
  packageName: '@dokebi/web',
125
126
  load: () => import('@dokebi/web'),
126
127
  });
@@ -144,6 +145,13 @@ function viewFlash(taken) {
144
145
  * HTTP seal slot of @dokebi/web).
145
146
  */
146
147
  const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.4.0' });
148
+ /** Optional: without it an app's `public/` folder is not served (warn APP_PUBLIC_UNSERVED). */
149
+ const files = optionalDependency({ name: 'dokebi-static', version: '^0.1.0' });
150
+ /** The import map and the forms module of a page on a seal host (served by @dokebi/seal). */
151
+ const SEAL_HEAD = '<script type="importmap">{"imports":{"@dokebi/seal/http":"/dokebi/seal/http.mjs","@dokebi/seal/forms":"/dokebi/seal/forms.mjs"}}</script>' +
152
+ '<script type="module" src="/dokebi/seal/forms.mjs"></script>';
153
+ const SEALED_VIEW = Object.freeze({ head: SEAL_HEAD });
154
+ const PLAIN_VIEW = Object.freeze({ head: '' });
147
155
  /** Packages that offer an engine or transport, for the fix of a missing one. */
148
156
  const PROVIDERS = {
149
157
  ejs: '@dokebi/template-ejs',
@@ -190,12 +198,14 @@ function realtimeHandle(app, namespace, sockets, streams) {
190
198
  throw new AppError('INVALID_TARGET', 'Invalid presence listener');
191
199
  return websocket().onPresence(listener);
192
200
  },
193
- publish: async (target, event, data) => {
201
+ publish: async (target, event, data, options) => {
194
202
  if (!streams)
195
203
  throw unavailable(app, 'realtime publish', 'sse');
196
204
  const checked = checkTarget(target);
197
205
  streamHandle ??= streams.handle(namespace);
198
- return streamHandle.publish(checked, event, data);
206
+ return options === undefined
207
+ ? streamHandle.publish(checked, event, data)
208
+ : streamHandle.publish(checked, event, data, options);
199
209
  },
200
210
  });
201
211
  }
@@ -221,14 +231,35 @@ function requirement(value) {
221
231
  /** A host without its port, lower case; IPv6 literals keep their brackets. */
222
232
  export function withoutPort(host) {
223
233
  const raw = host.toLowerCase();
224
- if (raw.startsWith('['))
225
- return raw.slice(0, raw.indexOf(']') + 1);
234
+ if (raw.startsWith('[')) {
235
+ // An unclosed bracket is no host: kept as it is, so it never reads as an empty Host.
236
+ const close = raw.indexOf(']');
237
+ return close < 0 ? raw : raw.slice(0, close + 1);
238
+ }
226
239
  const colon = raw.lastIndexOf(':');
227
240
  return colon === -1 ? raw : raw.slice(0, colon);
228
241
  }
229
- /** The Host header without port. Apps use dokebi-web `requestHost`, which honours trustProxy. */
242
+ /**
243
+ * A host as domains are matched: without the port and the one trailing dot of a fully qualified
244
+ * name (`a.com.` is `a.com`, as DNS reads it), lower case.
245
+ */
246
+ function matchedHost(host) {
247
+ const bare = withoutPort(host);
248
+ return bare.endsWith('.') ? bare.slice(0, -1) : bare;
249
+ }
250
+ /**
251
+ * What an unknown host must look like to be answered by `unknownDomain`: a host name (letters,
252
+ * digits, `.`, `-`, `_`), an IPv4 or a bracketed IPv6 literal, or nothing (HTTP/1.0). Any other
253
+ * Host header is no host (RFC 9110 §7.2) and never reaches an app as `page.app.domain`.
254
+ */
255
+ const HOST_SYNTAX = /^(?:[a-z0-9_](?:[a-z0-9_.-]{0,251}[a-z0-9_])?|\[[0-9a-f:.]{2,45}\])?$/;
256
+ /**
257
+ * The Host header without port, or an HTTP/2 request's `:authority`, which stands for it, usually
258
+ * comes without a Host and wins when both are there (RFC 9113 §8.3.1; dokebi-web `requestHost`
259
+ * reads them in this order). Apps use `requestHost`, which honours trustProxy.
260
+ */
230
261
  export function hostOf(request) {
231
- return withoutPort(String(request.headers.host ?? ''));
262
+ return withoutPort(String(request.headers[':authority'] ?? request.headers.host ?? ''));
232
263
  }
233
264
  /** The host entry of a request, kept on the raw request: the host is worked out once. */
234
265
  const HOST_ENTRY = Symbol('dokebi.app.host');
@@ -299,6 +330,44 @@ class AppRuntime {
299
330
  throw new AppError('NOT_REQUIRED', `Plugin ${name} is not declared by dokebi-app`);
300
331
  return dependency;
301
332
  }
333
+ /**
334
+ * R1 (user instruction 2026-10-28): an app's own browser files (CSS, images, fonts, scripts)
335
+ * live in `src/apps/<app>/public/`, next to its views, and answer `/assets/<path>` on the
336
+ * app's hosts through @dokebi/static (ETag, 304, Range, no listing, never outside the folder).
337
+ * R1 builders put them in views/ and served them with readFile routes of their own.
338
+ */
339
+ async #servePublic(context, name, views) {
340
+ const base = views.href.endsWith('/') ? views : new URL(`${views.href}/`);
341
+ const folder = new URL('../public/', base);
342
+ try {
343
+ if (!(await stat(folder)).isDirectory())
344
+ return;
345
+ }
346
+ catch (error) {
347
+ if (error?.code === 'ENOENT')
348
+ return;
349
+ throw error;
350
+ }
351
+ const root = fileURLToPath(folder);
352
+ const statics = context.getOptionalDependency(this.#declaredFor(files.name));
353
+ if (!statics) {
354
+ context.logger.log('warn', 'App public folder is not served', {
355
+ code: 'APP_PUBLIC_UNSERVED',
356
+ app: name,
357
+ folder: root,
358
+ fix: 'npx dokebi add @dokebi/static: it serves src/apps/<app>/public/ at /assets/ on the app hosts',
359
+ });
360
+ return;
361
+ }
362
+ // A mount name is a letter, then letters and digits (D-0147).
363
+ const mount = `app${name.replace(/-/g, '')}`.slice(0, 32);
364
+ statics.mount(mount, { prefix: '/assets', root, app: name });
365
+ context.logger.log('debug', 'App public folder served', {
366
+ app: name,
367
+ prefix: '/assets',
368
+ mount,
369
+ });
370
+ }
302
371
  #hosts = new Map();
303
372
  #unknownHosts = 0;
304
373
  /** AppInfo and seal flag of a host (without port), cached per host. */
@@ -330,8 +399,13 @@ class AppRuntime {
330
399
  return this.entry(host)?.info;
331
400
  }
332
401
  #target(host) {
333
- const domain = this.options.domains.has(host) ? host : this.options.unknownDomain;
334
- return domain === undefined ? undefined : this.options.domains.get(domain);
402
+ const configured = this.options.domains.get(host);
403
+ if (configured)
404
+ return configured;
405
+ const fallback = this.options.unknownDomain;
406
+ return fallback === undefined || !HOST_SYNTAX.test(host)
407
+ ? undefined
408
+ : this.options.domains.get(fallback);
335
409
  }
336
410
  /** The host's `seal` flag (an unknown host answered by `unknownDomain` takes that entry's). */
337
411
  sealed(host) {
@@ -366,17 +440,21 @@ class AppRuntime {
366
440
  * D-0074 addendum 1: an HTML form (urlencoded or multipart body) refused with 422
367
441
  * VALIDATION_FAILED goes back to the page it came from — `errors` and `old` flashed in the
368
442
  * session, 303 to the Referer of this host — when the request has a session and a way back.
443
+ * So does any other 4xx whose `data.formErrors` asks for it (D-0076 §2.5: dokebi-csrf's
444
+ * expired token, `errors._form`; `formFieldErrors` of dokebi-web reads both).
369
445
  * False otherwise: the error view (errors/422.ejs, errors/error.ejs) or dokebi-web's page.
370
446
  */
371
447
  const formBack = async (response, app) => {
372
448
  const { request, reply, status, body } = response;
373
- if (status !== 422 || !isFormSubmission(request.headers))
449
+ if (status < 400 || status > 499 || !isFormSubmission(request.headers))
374
450
  return false;
375
451
  const errors = formFieldErrors(body);
376
452
  if (!errors)
377
453
  return false;
378
454
  const current = sessionOf(request);
379
- const target = current ? formBackTarget(request, http.requestHost(request)) : undefined;
455
+ const target = current
456
+ ? formBackTarget(request, http.requestHost(request), undefined, http.formLimits)
457
+ : undefined;
380
458
  if (!current || target === undefined) {
381
459
  if (logger.isEnabled('debug'))
382
460
  logger.log('debug', 'App form validation answered with the error view', {
@@ -388,7 +466,7 @@ class AppRuntime {
388
466
  return false;
389
467
  }
390
468
  await current.flash('errors', errors);
391
- const old = formOldInput(request.body);
469
+ const old = formOldInput(request.body, http.formLimits);
392
470
  if (old)
393
471
  await current.flash('old', old);
394
472
  if (logger.isEnabled('debug'))
@@ -406,6 +484,11 @@ class AppRuntime {
406
484
  // D-0063 §5: view engines and realtime transports by name, whoever contributes them.
407
485
  const engines = byKey(context, viewEngines, 'name');
408
486
  const transports = byKey(context, realtime, 'kind');
487
+ // D-0076 §5: what plugins add to every EJS page (dokebi-csrf `csrf`, dokebi-auth `auth`).
488
+ const pageData = collectViewData(context.collect(viewData), {
489
+ plugin: 'dokebi-app',
490
+ reserved: ['sealed', 'seal', 'errors', 'old', 'flash'],
491
+ });
409
492
  const sockets = transports.get('websocket');
410
493
  const streams = transports.get('sse');
411
494
  const sealedDomains = [...this.options.domains]
@@ -421,6 +504,7 @@ class AppRuntime {
421
504
  sealed: sealedDomains.length,
422
505
  viewEngines: [...engines.keys()],
423
506
  transports: [...transports.keys()],
507
+ viewData: pageData.keys,
424
508
  });
425
509
  // Fail closed (D-0059 §4): a sealed host without the seal plugin would talk plain text.
426
510
  if (sealedDomains.length &&
@@ -434,10 +518,12 @@ class AppRuntime {
434
518
  return found;
435
519
  };
436
520
  // Behind a trusted proxy (dokebi-web trustProxy) the forwarded host picks the app.
437
- const host = (request) => withoutPort(http.requestHost(request));
521
+ const host = (request) => matchedHost(http.requestHost(request));
438
522
  /** The host entry of a raw or Fastify request, worked out once per request. */
439
- // Raw Host header → entry, so the usual request skips trimming, lower-casing and the port
440
- // cut. Only when no X-Forwarded-Host is present (with one, trustProxy decides). Client input:
523
+ // Raw host header → entry, so the usual request skips trimming, lower-casing and the port
524
+ // cut. Only when no X-Forwarded-Host is present (with one, trustProxy decides). The key is
525
+ // the header requestHost reads then: `:authority` before Host (an HTTP/2 request may carry
526
+ // both, and a Host that differs must never file another app under its name). Client input:
441
527
  // bounded like the unknown hosts.
442
528
  const byHeader = new Map();
443
529
  const hostEntry = (request) => {
@@ -445,7 +531,9 @@ class AppRuntime {
445
531
  const known = raw[HOST_ENTRY];
446
532
  if (known !== undefined)
447
533
  return known;
448
- const header = raw.headers['x-forwarded-host'] === undefined ? raw.headers.host : undefined;
534
+ const header = raw.headers['x-forwarded-host'] === undefined
535
+ ? (raw.headers[':authority'] ?? raw.headers.host)
536
+ : undefined;
449
537
  let entry = typeof header === 'string' ? byHeader.get(header) : undefined;
450
538
  if (entry === undefined) {
451
539
  entry = this.entry(host(request));
@@ -462,14 +550,29 @@ class AppRuntime {
462
550
  // the Inertia page, SSE data), except routes with seal: false and dokebi-web sealExclude.
463
551
  if (sealedDomains.length)
464
552
  http.sealRequests((request) => hostEntry(request)?.sealed === true);
553
+ // D-0181: the app of a request's host, for plugins that answer per app (dokebi-i18n layers).
554
+ if (typeof http.requestApps === 'function')
555
+ http.requestApps((request) => hostEntry(request)?.info.name);
465
556
  http.constraint({
466
557
  name: APP_CONSTRAINT,
467
558
  storage() {
468
559
  const values = new Map();
469
560
  return {
470
- get: (key) => (values.get(key) ?? null),
561
+ // A list (a plugin route bound to several apps, D-0132) is looked up by its apps.
562
+ get: (key) => (typeof key === 'string' ? (values.get(key) ?? null) : null),
471
563
  set: (key, value) => {
472
- values.set(key, value);
564
+ if (typeof key === 'string') {
565
+ values.set(key, value);
566
+ return;
567
+ }
568
+ // find-my-way keeps, per value, the bit mask of the handlers it matches, built by
569
+ // get → OR its bit → set. A list adds its handler's bits to each app's mask.
570
+ if (typeof value !== 'number')
571
+ throw new AppError('INVALID_DEFINITION', 'A route bound to several apps needs the bit mask store of find-my-way 9', {
572
+ fix: 'Report this with the installed fastify and find-my-way versions; bind the route to one app meanwhile.',
573
+ });
574
+ for (const app of key)
575
+ values.set(app, (values.get(app) ?? 0) | value);
473
576
  },
474
577
  };
475
578
  },
@@ -483,6 +586,26 @@ class AppRuntime {
483
586
  // Requests of a known app may still reach shared (unconstrained) routes.
484
587
  mustMatchWhenDerived: false,
485
588
  });
589
+ // D-0132: routes of other plugins bound to apps (`app` of a route, `<plugin>.app`) get this
590
+ // constraint from dokebi-web, checked against these names and hosts.
591
+ const domainsByApp = new Map();
592
+ for (const [domain, target] of this.options.domains) {
593
+ const list = domainsByApp.get(target.app);
594
+ if (list)
595
+ list.push(domain);
596
+ else
597
+ domainsByApp.set(target.app, [domain]);
598
+ }
599
+ const fallback = this.options.unknownDomain === undefined
600
+ ? undefined
601
+ : this.options.domains.get(this.options.unknownDomain)?.app;
602
+ http.appRouting(Object.freeze({
603
+ constraint: APP_CONSTRAINT,
604
+ names: Object.freeze([...this.apps.keys()]),
605
+ domainApp: (domain) => this.options.domains.get(domain)?.app,
606
+ domainsOf: (app) => domainsByApp.get(app) ?? [],
607
+ fallback,
608
+ }));
486
609
  /** The shared EJS renderer (the engine's own), loaded once on first need. */
487
610
  let ejsRoot;
488
611
  /** Each app's error answer (D-0074), by app name. */
@@ -499,7 +622,7 @@ class AppRuntime {
499
622
  const namespaces = this.options.apps.get(name)?.namespaces ?? [name];
500
623
  const handles = new Map();
501
624
  /** The namespace an authenticated connection joins, or undefined (401) for one not listed. */
502
- const namespaceOf = (wanted, kind, path) => {
625
+ const namespaceOf = (wanted, kind, path, routeId) => {
503
626
  if (wanted === undefined)
504
627
  return namespaces[0];
505
628
  if (typeof wanted === 'string' && namespaces.includes(wanted))
@@ -509,14 +632,15 @@ class AppRuntime {
509
632
  app: name,
510
633
  kind,
511
634
  path,
635
+ routeId,
512
636
  namespace: typeof wanted === 'string' ? wanted.slice(0, 64) : null,
513
637
  allowed: [...namespaces],
514
638
  });
515
639
  return undefined;
516
640
  };
517
641
  /** `identity` in the chosen namespace: tenant prefixed, `namespace` removed. */
518
- const scoped = (kind, path) => (identity) => {
519
- const chosen = namespaceOf(identity.namespace, kind, path);
642
+ const scoped = (kind, path, routeId) => (identity) => {
643
+ const chosen = namespaceOf(identity.namespace, kind, path, routeId);
520
644
  if (chosen === undefined)
521
645
  return undefined;
522
646
  const { namespace: _namespace, ...rest } = identity;
@@ -580,6 +704,10 @@ class AppRuntime {
580
704
  logger: context.logger,
581
705
  signal: context.signal,
582
706
  drainSignal: context.drainSignal,
707
+ // Set when the drain phase starts (a spread would freeze the value of setup time).
708
+ get drainDeadline() {
709
+ return context.drainDeadline;
710
+ },
583
711
  get: appContext.get,
584
712
  getDependency: appContext.getDependency,
585
713
  getOptionalDependency: appContext.getOptionalDependency,
@@ -598,10 +726,14 @@ class AppRuntime {
598
726
  }
599
727
  else if (hasModuleViews && !ejsRoot)
600
728
  ejsRoot = await engine('ejs', name).scope({});
729
+ if (definition.views)
730
+ await this.#servePublic(context, name, definition.views);
601
731
  let inertiaApi;
602
732
  if (definition.inertia) {
603
733
  inertiaApi = await engine('inertia', name).scope({
604
734
  ...definition.inertia,
735
+ // Named in the scope's log records (INERTIA_VERSION_DEFAULT says which app).
736
+ app: name,
605
737
  // SSR would write the props of a sealed host as plain HTML: refused (D-0062).
606
738
  ...(appSealed ? { sealed: true } : {}),
607
739
  shared: (request) => {
@@ -629,16 +761,22 @@ class AppRuntime {
629
761
  ...appChain(template),
630
762
  ];
631
763
  };
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) => {
764
+ // `sealed` and `seal` (D-0092), the session flash (`errors`, `old`, `flash`; D-0074
765
+ // addendum 1), the plugins' view data (D-0076 §5) and the app's shared data under the page data, computed once per
766
+ // render call. An error view passes its own `errors` and `old` and leaves the flash to the
767
+ // next page.
768
+ const withShared = (view, request, info, sealed, pageFlash = true,
769
+ /** The view data of plugins and the app's `shared` (false for a 503 error view, D-0102). */
770
+ withData = true) => {
636
771
  const data = async (own) => {
637
772
  const taken = (pageFlash ? await flashOf(request) : undefined) ?? viewFlash(undefined);
638
773
  const result = {
639
774
  sealed,
775
+ // D-0092 §1.5: the layout's `<%- data.seal.head %>` (empty on a plain host).
776
+ seal: sealed ? SEALED_VIEW : PLAIN_VIEW,
640
777
  ...taken,
641
- ...(await definition.shared?.(request, { app: info })),
778
+ ...(withData && pageData.keys.length ? await pageData.values(request) : undefined),
779
+ ...(withData ? await definition.shared?.(request, { app: info }) : undefined),
642
780
  ...own,
643
781
  };
644
782
  // The handler's own `errors` and `old` win field by field.
@@ -710,21 +848,26 @@ class AppRuntime {
710
848
  });
711
849
  };
712
850
  /** The scope of one realtime route: the full path, the app constraint and tenant rule. */
713
- const scopeOf = (path, kind) => Object.freeze({
714
- path,
715
- constraints: Object.freeze({ [APP_CONSTRAINT]: name }),
716
- identity: scoped(kind, path),
717
- // The request's host decides (D-0059 §4); only when a host of this app seals.
718
- ...(appSealed
719
- ? { seal: (request) => hostEntry(request)?.sealed === true }
720
- : {}),
721
- });
851
+ const scopeOf = (route, base, kind) => {
852
+ const path = joinPath(base, route.path);
853
+ // D-0140: the route id, for the refusal log; the transport hands `config` to dokebi-web.
854
+ const id = route.config?.id;
855
+ return Object.freeze({
856
+ path,
857
+ constraints: Object.freeze({ [APP_CONSTRAINT]: name }),
858
+ identity: scoped(kind, path, typeof id === 'string' ? id : null),
859
+ // The request's host decides (D-0059 §4); only when a host of this app seals.
860
+ ...(appSealed
861
+ ? { seal: (request) => hostEntry(request)?.sealed === true }
862
+ : {}),
863
+ });
864
+ };
722
865
  const mountSockets = (routes, base, owner) => {
723
866
  for (const route of routes) {
724
867
  if (!sockets)
725
868
  throw new AppError('REALTIME_UNAVAILABLE', `${owner} has sockets; add @dokebi/websocket`);
726
869
  socketCount++;
727
- sockets.mount(route, scopeOf(joinPath(base, route.path), 'socket'));
870
+ sockets.mount(route, scopeOf(route, base, 'socket'));
728
871
  }
729
872
  };
730
873
  const mountEvents = (routes, base, owner) => {
@@ -732,7 +875,7 @@ class AppRuntime {
732
875
  if (!streams)
733
876
  throw new AppError('REALTIME_UNAVAILABLE', `${owner} has event streams; add @dokebi/sse`);
734
877
  eventCount++;
735
- streams.mount(route, scopeOf(joinPath(base, route.path), 'stream'));
878
+ streams.mount(route, scopeOf(route, base, 'stream'));
736
879
  }
737
880
  };
738
881
  // D-0074 §3-4: the error answers of this app's hosts. Inertia first (the validation
@@ -766,7 +909,16 @@ class AppRuntime {
766
909
  if (!page)
767
910
  return false;
768
911
  const fields = Array.isArray(body.fields) ? body.fields : [];
769
- await withShared(view, request, info, sealed, false).reply(reply, page, {
912
+ // D-0102: a 503 (a store, database or Redis down or overloaded) renders from the error
913
+ // alone: the view data (auth, csrf, i18n) and `shared` may read the store that failed.
914
+ const bare = status === 503;
915
+ if (bare && logger.isEnabled('debug'))
916
+ logger.log('debug', 'App error view without view data', {
917
+ app: name,
918
+ view: page,
919
+ status,
920
+ });
921
+ await withShared(view, request, info, sealed, false, !bare).reply(reply, page, {
770
922
  status,
771
923
  title: `${status} ${STATUS_CODES[status] ?? 'Error'}`,
772
924
  error: body.error,
@@ -776,7 +928,7 @@ class AppRuntime {
776
928
  // A refused form without a way back (no session, no Referer of this host): an
777
929
  // errors/422.ejs can show the form again with these (D-0074 addendum 1).
778
930
  errors: formFieldErrors(body) ?? {},
779
- old: (status === 422 && formOldInput(request.body)) || {},
931
+ old: (status === 422 && formOldInput(request.body, http.formLimits)) || {},
780
932
  // Development only (dokebi-web already cut `fix` from a production body).
781
933
  fix: typeof body.fix === 'string' ? body.fix : null,
782
934
  stack: !production && status >= 500 && error instanceof Error ? (error.stack ?? null) : null,
@@ -830,9 +982,60 @@ class AppRuntime {
830
982
  const answer = entry ? answers.get(entry.info.name) : undefined;
831
983
  return entry && answer ? answer(response, entry) : false;
832
984
  });
985
+ // D-0077 B: only `dokebi describe` (runtime.describing) asks; a normal start adds nothing.
986
+ if (context.runtime.describing)
987
+ this.#describe(context);
833
988
  return Object.freeze({
834
989
  names: Object.freeze([...this.apps.keys()]),
835
990
  resolve: (request) => hostEntry(request)?.info,
991
+ seal: (request) => hostEntry(request)?.sealed === true ? SEALED_VIEW : PLAIN_VIEW,
992
+ });
993
+ }
994
+ /** The apps, domains and pages of describe mode (D-0077 B), read once when asked. */
995
+ #describe(context) {
996
+ let read;
997
+ const described = () => {
998
+ read ??= (async () => {
999
+ const apps = [];
1000
+ const pages = [];
1001
+ for (const [name, definition] of this.apps) {
1002
+ const found = await appPages(name, definition.views, definition.inertia !== undefined);
1003
+ pages.push(...found.pages);
1004
+ apps.push({
1005
+ name,
1006
+ engine: definition.inertia ? 'inertia' : definition.views ? 'ejs' : null,
1007
+ views: found.folder,
1008
+ templates: found.templates,
1009
+ modules: Object.entries(definition.modules ?? {}).map(([prefix, plugin]) => ({
1010
+ prefix,
1011
+ module: mountOf(plugin)?.name ?? plugin.metadata.name,
1012
+ })),
1013
+ requires: (definition.requires ?? []).map((item) => requirement(item).name),
1014
+ namespaces: [...(this.options.apps.get(name)?.namespaces ?? [name])],
1015
+ });
1016
+ }
1017
+ return { apps, pages };
1018
+ })();
1019
+ return read;
1020
+ };
1021
+ context.contribute(describePoint, {
1022
+ section: 'app',
1023
+ describe: async () => ({
1024
+ // Routes of an app carry this Fastify constraint with the app's name.
1025
+ constraint: APP_CONSTRAINT,
1026
+ apps: (await described()).apps,
1027
+ domains: [...this.options.domains].map(([host, target]) => ({
1028
+ host,
1029
+ app: target.app,
1030
+ template: target.template,
1031
+ seal: target.seal,
1032
+ })),
1033
+ unknownDomain: this.options.unknownDomain ?? 'reject',
1034
+ }),
1035
+ });
1036
+ context.contribute(describePoint, {
1037
+ section: 'pages',
1038
+ describe: async () => (await described()).pages,
836
1039
  });
837
1040
  }
838
1041
  /** Every template a domain selects must exist as a folder, and `default` always must. */
@@ -867,7 +1070,8 @@ class AppRuntime {
867
1070
  }
868
1071
  }
869
1072
  async drain() {
870
- await Promise.all(this.#mounted.map(async ({ name, definition, context }) => {
1073
+ // Every app drains; each failure reaches the stop (Promise.all kept only the first, D-0047).
1074
+ const results = await Promise.allSettled(this.#mounted.map(async ({ name, definition, context }) => {
871
1075
  if (!definition.drain)
872
1076
  return;
873
1077
  const begin = performance.now();
@@ -877,6 +1081,15 @@ class AppRuntime {
877
1081
  ms: Math.round(performance.now() - begin),
878
1082
  });
879
1083
  }));
1084
+ const failed = [];
1085
+ results.forEach((result, index) => {
1086
+ if (result.status === 'rejected')
1087
+ failed.push({ app: this.#mounted[index]?.name ?? 'unknown', reason: result.reason });
1088
+ });
1089
+ if (failed.length === 1)
1090
+ throw failed[0]?.reason;
1091
+ if (failed.length)
1092
+ throw new AggregateError(failed.map((failure) => failure.reason), `Drain of apps ${failed.map((failure) => failure.app).join(', ')} failed`);
880
1093
  }
881
1094
  }
882
1095
  function missingViews(name) {
@@ -893,20 +1106,21 @@ function missingViews(name) {
893
1106
  }
894
1107
  export const createPlugin = definePlugin({
895
1108
  name: 'dokebi-app',
896
- version: '0.4.2',
1109
+ version: '0.4.5',
897
1110
  core: '^0.4.0',
898
1111
  options: declaration,
899
1112
  entry: parseEntry,
900
1113
  // Template and realtime plugins are found through these points, not by name (D-0063 §5).
901
- collects: [viewEngines, realtime],
1114
+ collects: [viewEngines, realtime, viewData],
1115
+ contributes: [describePoint],
902
1116
  dependencies: ({ entry }) => mergeRequirements(entry ?? new Map()),
903
1117
  instance: ({ options, entry, dependencies }) => new AppRuntime(settings(options), entry ?? new Map(), dependencies),
904
1118
  });
905
1119
  /**
906
1120
  * 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
1121
+ * own web, seal and session) are merged per name (ISSUE-0006 A12): the version is the semver AND
1122
+ * of every distinct range (`andRanges`: satisfied by exactly the versions that satisfy each app's
1123
+ * range, prerelease rules included, so core's check is the check of every app), the result is optional only when every consumer is optional, and the factory (`create`) of the
910
1124
  * first consumer that has one is kept. Ranges that cannot meet are refused here, before start,
911
1125
  * with `DEPENDENCY_CONFLICT` naming the apps: no provider version could satisfy both.
912
1126
  */
@@ -921,7 +1135,7 @@ function mergeRequirements(apps) {
921
1135
  else
922
1136
  needs.set(dependency.name, [{ consumer, dependency }]);
923
1137
  };
924
- for (const dependency of [web, seal, session])
1138
+ for (const dependency of [web, seal, session, files])
925
1139
  add('dokebi-app', dependency);
926
1140
  for (const [name, app] of apps)
927
1141
  for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})])
@@ -941,7 +1155,7 @@ function mergeRequirements(apps) {
941
1155
  if (!next) {
942
1156
  // Name the consumer it clashes with; when only the combination fails, name them all.
943
1157
  const earlier = list.slice(0, list.indexOf(need));
944
- const clash = earlier.find((other) => !intersects(other.dependency.version, need.dependency.version));
1158
+ const clash = earlier.find((other) => !andRanges(other.dependency.version, need.dependency.version));
945
1159
  const others = clash ? [clash] : earlier;
946
1160
  throw new AppError('DEPENDENCY_CONFLICT', `No version of ${name} satisfies both ${others.map(label).join(' and ')} and ${label(need)}`, {
947
1161
  details: {
@@ -976,22 +1190,52 @@ function mergeRequirements(apps) {
976
1190
  return merged;
977
1191
  }
978
1192
  /**
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).
1193
+ * The semver AND of two ranges, `||` included: every pair of alternatives (comparator sets)
1194
+ * joined with a space, unsatisfiable pairs left out. Joining whole ranges with a space is wrong
1195
+ * for `||` (`^1 || ^2` and `^2` would read as `^1 || (^2 ^2)` and accept 1.x; ISSUE-0006 recheck).
982
1196
  * An empty string: no version satisfies both.
1197
+ *
1198
+ * Joining two sets must also keep each side's prerelease rule (ISSUE-0006 recheck R03): semver
1199
+ * admits a prerelease only when a comparator of its set carries a prerelease of the same
1200
+ * major.minor.patch, so a joined set would let one side's `>=1.1.0-beta.1` admit `1.1.0-beta.2`
1201
+ * for a side (`>=1.0.0 <2.0.0`) that refuses it. A prerelease comparator whose major.minor.patch
1202
+ * is not carried by both sides is therefore written as its release form (`>=X-p` and `>X-p` as
1203
+ * `>=X`, `<X-p` and `<=X-p` as `<X`, `=X-p` as no version): the same answer for every version
1204
+ * outside X, and no prerelease of X is admitted any more. The result is satisfied by exactly the
1205
+ * versions that satisfy both `a` and `b` (default semver options, as core checks).
983
1206
  */
984
1207
  export function andRanges(a, b) {
985
1208
  const parts = [];
986
1209
  for (const left of new Range(a).set)
987
1210
  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))
1211
+ const theirs = prereleaseTuples(right);
1212
+ const both = [...prereleaseTuples(left)].filter((tuple) => theirs.has(tuple));
1213
+ const comparators = [];
1214
+ let possible = true;
1215
+ for (const comparator of [...left, ...right]) {
1216
+ if (!comparator.value)
1217
+ continue; // `*`
1218
+ const version = comparator.semver;
1219
+ const tuple = `${version.major}.${version.minor}.${version.patch}`;
1220
+ if (!version.prerelease.length || both.includes(tuple))
1221
+ comparators.push(comparator.value);
1222
+ else if (comparator.operator === '>=' || comparator.operator === '>')
1223
+ comparators.push(`>=${tuple}`);
1224
+ else if (comparator.operator === '<' || comparator.operator === '<=')
1225
+ comparators.push(`<${tuple}`);
1226
+ else
1227
+ possible = false; // exactly one prerelease the other side never admits
1228
+ }
1229
+ const combo = comparators.join(' ') || '*';
1230
+ if (possible && minVersion(combo) !== null && !parts.includes(combo))
993
1231
  parts.push(combo);
994
1232
  }
995
1233
  return parts.join(' || ');
996
1234
  }
1235
+ /** The major.minor.patch of every prerelease comparator in one comparator set. */
1236
+ function prereleaseTuples(set) {
1237
+ return new Set(set
1238
+ .filter((comparator) => comparator.value && comparator.semver.prerelease.length)
1239
+ .map(({ semver: v }) => `${v.major}.${v.minor}.${v.patch}`));
1240
+ }
997
1241
  const label = (need) => `${need.consumer === 'dokebi-app' ? 'dokebi-app' : `app ${need.consumer}`} (${need.dependency.version})`;