@dokebi/app 0.4.6 → 0.4.8

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
@@ -138,6 +138,8 @@ HTML forms need `dokebi-web.formBody: true` (urlencoded bodies). The flow needs
138
138
  ### Mounting modules (D-0032)
139
139
 
140
140
  - `modules: { '/prefix': module }`. The prefix is `/` or `/a/b` (lower-case letters, digits, `.`, `_`, `~`, `-`).
141
+ - A module that declares its pages as named sets (@dokebi/module 0.4.5, [D-0216](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0216-module-sets.md)) is mounted with the sets this app shows: `modules: { '/board': { module: board, use: 'admin' } }` (or `use: ['site', 'admin']`). Only those sets' routes, sockets and event streams are registered here. Mounting such a module whole, an unknown set, an empty or repeated choice, and `use` on a module without sets are `INVALID_DEFINITION`. One app may mount two sets of a module at two prefixes. Debug log `Module sets mounted` (app, module, prefix, use); `App set up` lists `/board -> board [admin]`; describe lists `use` per module.
142
+ - A module with a switch (`enabled`, @dokebi/module 0.4.5, D-0216) that is off answers on this app like an unknown path: its routes get the 404 (this app's `errors/404` page for a browser) as their first onRequest step, before login checks and body parsing, and its new socket upgrades and SSE streams are 404 too. Open connections stay open.
141
143
  - The module's routes, sockets and SSE routes (`events`, since @dokebi/module 0.1.3) are registered on this app's domains under the prefix, and `page.module` and `page.base` are filled in. Several apps can mount the same module under different prefixes. A mounted module's API is readable with `app.get(module)` without listing it in `requires`.
142
144
  - The module's root route (`route.get('/')`) answers both `/prefix` and `/prefix/`, so links and form actions may use either. Other paths match exactly (`/prefix/items/7/` is 404).
143
145
  - Module views are looked up in this order, so module pages render inside the app layout. To change a module page, an app puts the same file into `views/<template>/<module>/`.
package/dist/errors.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { DokebiError } from '@dokebi/core';
2
2
  const FIX = {
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.',
3
+ INVALID_DEFINITION: 'defineApp takes requires, controllers, views (a file: URL), inertia, modules ({ "/prefix": defineModule(...) }, or { "/prefix": { module, use: "<set>" } } for a module of named sets), 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
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.',
6
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).',
package/dist/index.d.ts CHANGED
@@ -4,6 +4,14 @@ 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';
7
+ /**
8
+ * A module of `defineApp({ modules })`: mounted whole, or `{ module, use }` (D-0216) to show only
9
+ * the named sets of a module that declares its routes, sockets and events as sets.
10
+ */
11
+ export type AppModuleMount = Plugin<unknown> | {
12
+ readonly module: Plugin<unknown>;
13
+ readonly use: string | readonly string[];
14
+ };
7
15
  /** The Fastify route constraint that selects an app by request host. */
8
16
  export declare const APP_CONSTRAINT = "dokebiApp";
9
17
  /** Which app answered a request, with the template and the host it came in on. */
@@ -291,9 +299,10 @@ export interface AppDefinition {
291
299
  readonly inertia?: AppInertiaOptions;
292
300
  /**
293
301
  * Modules (D-0032) mounted under a prefix: `{ '/board': boardModule }`. Their routes and
294
- * sockets answer on this app's domains only; they need not be listed in `requires`.
302
+ * sockets answer on this app's domains only; they need not be listed in `requires`. A module
303
+ * that declares named sets is mounted as `{ module, use: 'admin' }` (D-0216).
295
304
  */
296
- readonly modules?: Readonly<Record<string, Plugin<unknown>>>;
305
+ readonly modules?: Readonly<Record<string, AppModuleMount>>;
297
306
  /**
298
307
  * Data merged under the data of every EJS page this app renders, its own and its modules'
299
308
  * (like Inertia shared props): what the app layout needs, such as the menu. Page data wins.
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { stat } from 'node:fs/promises';
2
3
  import { fileURLToPath } from 'node:url';
3
4
  import { types } from 'node:util';
@@ -26,6 +27,18 @@ function mountOf(plugin) {
26
27
  ? plugin[MODULE_MOUNT]
27
28
  : undefined;
28
29
  }
30
+ function mountedPlugin(value) {
31
+ return mountOf(value)
32
+ ? value
33
+ : value.module;
34
+ }
35
+ /** The sets an app chose for a mount (checked by defineApp), or undefined for a whole module. */
36
+ function chosenSets(value) {
37
+ if (mountOf(value))
38
+ return undefined;
39
+ const use = value.use;
40
+ return typeof use === 'string' ? [use] : use;
41
+ }
29
42
  /** `/board` + `/` → `/board`, `/board` + `/x` → `/board/x`, `/` + `/x` → `/x`. */
30
43
  function joinPath(base, path) {
31
44
  if (!base)
@@ -68,11 +81,33 @@ export function defineApp(definition) {
68
81
  if (definition.modules !== undefined) {
69
82
  if (!plain(definition.modules))
70
83
  throw invalidDefinition('App modules must be a plain object');
71
- for (const [prefix, plugin] of Object.entries(definition.modules)) {
84
+ for (const [prefix, value] of Object.entries(definition.modules)) {
72
85
  if (!PREFIX.test(prefix))
73
86
  throw invalidDefinition('Invalid module prefix: ' + prefix);
74
- if (!mountOf(plugin))
87
+ const whole = mountOf(value);
88
+ const given = value;
89
+ const mount = whole ?? mountOf(given?.module);
90
+ if (!mount)
75
91
  throw invalidDefinition('App modules must be made with defineModule');
92
+ const sets = mount.sets;
93
+ if (whole) {
94
+ // A module of named sets is never mounted whole: the app says which pages it shows.
95
+ if (sets)
96
+ throw invalidDefinition(`Module ${mount.name} at ${prefix} has the sets ${sets.join(', ')}: mount it as { module, use: '<set>' }`);
97
+ continue;
98
+ }
99
+ const use = typeof given?.use === 'string' ? [given.use] : given?.use;
100
+ if (!Array.isArray(use) ||
101
+ !use.length ||
102
+ Object.keys(given).some((key) => key !== 'module' && key !== 'use') ||
103
+ new Set(use).size !== use.length)
104
+ throw invalidDefinition(`Module mount at ${prefix} is { module, use: '<set>' | ['<set>', …] }`);
105
+ // An older @dokebi/module has neither sets nor hooks.
106
+ if (!sets || typeof mount.hooks !== 'function')
107
+ throw invalidDefinition(`Module ${mount.name} at ${prefix} has no sets: mount the module itself`);
108
+ const unknown = use.filter((set) => !sets.includes(set));
109
+ if (unknown.length)
110
+ throw invalidDefinition(`Module ${mount.name} at ${prefix} has no set ${unknown.join(', ')} (it has ${sets.join(', ')})`);
76
111
  }
77
112
  }
78
113
  for (const hook of ['shared', 'routes', 'sockets', 'events', 'setup', 'start', 'drain'])
@@ -330,6 +365,8 @@ class AppRuntime {
330
365
  throw new AppError('NOT_REQUIRED', `Plugin ${name} is not declared by dokebi-app`);
331
366
  return dependency;
332
367
  }
368
+ /** The @dokebi/static mount names given to app public folders so far. */
369
+ #publicMounts = new Set();
333
370
  /**
334
371
  * R1 (user instruction 2026-10-28): an app's own browser files (CSS, images, fonts, scripts)
335
372
  * live in `src/apps/<app>/public/`, next to its views, and answer `/assets/<path>` on the
@@ -359,8 +396,16 @@ class AppRuntime {
359
396
  });
360
397
  return;
361
398
  }
362
- // A mount name is a letter, then letters and digits (D-0147).
363
- const mount = `app${name.replace(/-/g, '')}`.slice(0, 32);
399
+ // A mount name is a letter, then letters and digits, at most 32 (D-0147): `app` and the app
400
+ // name without its hyphens. Two app names can give the same one (`shop-admin` and
401
+ // `shopadmin`, or names alike in their first 29 characters), and a second mount of a name
402
+ // stops the start (INVALID_MOUNT): the later app then gets a name with a hash of its own
403
+ // name (audit R9-g13-2). Every app that started before keeps the mount it always had.
404
+ const plain = `app${name.replace(/-/g, '')}`;
405
+ let mount = plain.slice(0, 32);
406
+ if (this.#publicMounts.has(mount))
407
+ mount = `${plain.slice(0, 24)}${createHash('sha256').update(name).digest('hex').slice(0, 8)}`;
408
+ this.#publicMounts.add(mount);
364
409
  statics.mount(mount, { prefix: '/assets', root, app: name });
365
410
  context.logger.log('debug', 'App public folder served', {
366
411
  app: name,
@@ -610,6 +655,30 @@ class AppRuntime {
610
655
  let ejsRoot;
611
656
  /** Each app's error answer (D-0074), by app name. */
612
657
  const answers = new Map();
658
+ /**
659
+ * D-0216: the switch of each module socket and event stream route, by `<app> <path>`. The
660
+ * transports register those routes themselves, so the gate comes in through a route hook (a
661
+ * module's own HTTP routes get it as their first onRequest step instead, below).
662
+ */
663
+ const switches = new Map();
664
+ http.routeHook({
665
+ plugin: 'dokebi-app',
666
+ route: (route) => {
667
+ const app = route.constraints[APP_CONSTRAINT];
668
+ const on = typeof app === 'string' ? switches.get(`${app} ${route.url}`) : undefined;
669
+ if (!on)
670
+ return undefined;
671
+ return {
672
+ preValidation: async (_request, reply) => {
673
+ if (on())
674
+ return undefined;
675
+ // The 404 of an unknown path on this app's host (its error page, JSON for an API).
676
+ reply.callNotFound();
677
+ return reply;
678
+ },
679
+ };
680
+ },
681
+ });
613
682
  for (const [name, definition] of this.apps) {
614
683
  context.signal.throwIfAborted();
615
684
  const begin = performance.now();
@@ -653,7 +722,10 @@ class AppRuntime {
653
722
  });
654
723
  return { ...rest, tenant: `${chosen}:${identity.tenant}` };
655
724
  };
656
- const allowed = new Set([...(definition.requires ?? []), ...Object.values(definition.modules ?? {})].map((item) => requirement(item).name));
725
+ const allowed = new Set([
726
+ ...(definition.requires ?? []),
727
+ ...Object.values(definition.modules ?? {}).map(mountedPlugin),
728
+ ].map((item) => requirement(item).name));
657
729
  let controllers;
658
730
  const appContext = Object.freeze({
659
731
  name,
@@ -715,7 +787,7 @@ class AppRuntime {
715
787
  });
716
788
  controllers = await createControllers(factoryContext, definition.controllers ?? []);
717
789
  const templates = new Set();
718
- const hasModuleViews = Object.values(definition.modules ?? {}).some((module) => mountOf(module)?.views);
790
+ const hasModuleViews = Object.values(definition.modules ?? {}).some((module) => mountOf(mountedPlugin(module))?.views);
719
791
  if (definition.views) {
720
792
  // The app's folder is loaded as `<app>/…`; the engine's root renderer serves every scope.
721
793
  ejsRoot = await engine('ejs', name).scope({
@@ -824,13 +896,32 @@ class AppRuntime {
824
896
  return new RequestPage(info, entry?.sealed === true, moduleName, base, inertiaApi, request, viewOf);
825
897
  };
826
898
  };
827
- const routerFor = (page, base) => {
899
+ const routerFor = (page, base, on) => {
900
+ /**
901
+ * D-0216: a switched-off module answers the 404 of an unknown path before anything else
902
+ * of the request runs (login checks, body parsing): its first onRequest step.
903
+ */
904
+ const gate = on
905
+ ? async (_request, reply) => {
906
+ if (on())
907
+ return undefined;
908
+ reply.callNotFound();
909
+ return reply;
910
+ }
911
+ : undefined;
828
912
  const add = (options) => {
829
913
  const { handler, ...rest } = options;
830
914
  routeCount++;
831
915
  const url = joinPath(base, rest.url);
916
+ const own = rest.onRequest;
917
+ const onRequest = (gate
918
+ ? own === undefined || own === null
919
+ ? [gate]
920
+ : [gate, ...(Array.isArray(own) ? own : [own])]
921
+ : own);
832
922
  const register = (path) => http.route({
833
923
  ...rest,
924
+ ...(onRequest === undefined ? {} : { onRequest }),
834
925
  url: path,
835
926
  constraints: { [APP_CONSTRAINT]: name },
836
927
  handler(request, reply) {
@@ -953,17 +1044,44 @@ class AppRuntime {
953
1044
  mountSockets((await definition.sockets?.(appContext)) ?? [], '', `App ${name}`);
954
1045
  mountEvents((await definition.events?.(appContext)) ?? [], '', `App ${name}`);
955
1046
  // Mounted modules (D-0032): their routes, sockets and SSE routes under the prefix, here only.
956
- for (const [prefix, plugin] of Object.entries(definition.modules ?? {})) {
957
- const mount = mountOf(plugin);
1047
+ for (const [prefix, value] of Object.entries(definition.modules ?? {})) {
1048
+ const mount = mountOf(mountedPlugin(value));
958
1049
  const base = prefix === '/' ? '' : prefix;
959
1050
  const module = mount.context();
960
1051
  const page = pageFor({ name: mount.name, views: mount.views, base });
961
- await mount.routes?.(routerFor(page, base), module);
962
- mountSockets(
963
- // defineSocket results; the module types them by shape only.
964
- ((await mount.sockets?.(module)) ?? []), base, `Module ${mount.name} (app ${name})`);
1052
+ // D-0216: only the chosen sets of a module of sets; a whole module as before.
1053
+ const chosen = chosenSets(value);
1054
+ const hooks = chosen && mount.hooks
1055
+ ? mount.hooks(chosen)
1056
+ : {
1057
+ routes: mount.routes ? [mount.routes] : [],
1058
+ sockets: mount.sockets ? [mount.sockets] : [],
1059
+ events: mount.events ? [mount.events] : [],
1060
+ };
1061
+ // D-0216: the module's switch (older module packages have none: always on).
1062
+ const on = typeof mount.enabled === 'function' ? () => mount.enabled?.() ?? true : undefined;
1063
+ for (const routes of hooks.routes)
1064
+ await routes(routerFor(page, base, on), module);
1065
+ const gateRealtime = (routes) => {
1066
+ if (on)
1067
+ for (const route of routes)
1068
+ switches.set(`${name} ${joinPath(base, route.path)}`, on);
1069
+ return routes;
1070
+ };
1071
+ if (chosen && logger.isEnabled('debug'))
1072
+ logger.log('debug', 'Module sets mounted', {
1073
+ app: name,
1074
+ module: mount.name,
1075
+ prefix,
1076
+ use: chosen,
1077
+ });
1078
+ for (const sockets of hooks.sockets)
1079
+ mountSockets(
1080
+ // defineSocket results; the module types them by shape only.
1081
+ gateRealtime(((await sockets(module)) ?? [])), base, `Module ${mount.name} (app ${name})`);
965
1082
  // SSE routes of the module (@dokebi/module 0.1.3; older modules have no `events`).
966
- mountEvents(((await mount.events?.(module)) ?? []), base, `Module ${mount.name} (app ${name})`);
1083
+ for (const events of hooks.events)
1084
+ mountEvents(gateRealtime(((await events(module)) ?? [])), base, `Module ${mount.name} (app ${name})`);
967
1085
  }
968
1086
  this.#mounted.push({ name, definition, context: appContext });
969
1087
  logger.log('debug', 'App set up', {
@@ -972,7 +1090,7 @@ class AppRuntime {
972
1090
  controllers: definition.controllers?.length ?? 0,
973
1091
  templates: [...templates],
974
1092
  inertia: Boolean(inertiaApi),
975
- modules: Object.entries(definition.modules ?? {}).map(([prefix, plugin]) => `${prefix} -> ${mountOf(plugin).name}`),
1093
+ modules: Object.entries(definition.modules ?? {}).map(([prefix, value]) => `${prefix} -> ${mountOf(mountedPlugin(value)).name}${chosenSets(value) ? ` [${chosenSets(value)?.join(', ')}]` : ''}`),
976
1094
  routes: routeCount,
977
1095
  sockets: socketCount,
978
1096
  events: eventCount,
@@ -1012,9 +1130,10 @@ class AppRuntime {
1012
1130
  engine: definition.inertia ? 'inertia' : definition.views ? 'ejs' : null,
1013
1131
  views: found.folder,
1014
1132
  templates: found.templates,
1015
- modules: Object.entries(definition.modules ?? {}).map(([prefix, plugin]) => ({
1133
+ modules: Object.entries(definition.modules ?? {}).map(([prefix, value]) => ({
1016
1134
  prefix,
1017
- module: mountOf(plugin)?.name ?? plugin.metadata.name,
1135
+ module: mountOf(mountedPlugin(value))?.name ?? mountedPlugin(value).metadata.name,
1136
+ ...(chosenSets(value) ? { use: chosenSets(value) } : {}),
1018
1137
  })),
1019
1138
  requires: (definition.requires ?? []).map((item) => requirement(item).name),
1020
1139
  namespaces: [...(this.options.apps.get(name)?.namespaces ?? [name])],
@@ -1112,7 +1231,7 @@ function missingViews(name) {
1112
1231
  }
1113
1232
  export const createPlugin = definePlugin({
1114
1233
  name: 'dokebi-app',
1115
- version: '0.4.6',
1234
+ version: '0.4.8',
1116
1235
  core: '^0.4.0',
1117
1236
  options: declaration,
1118
1237
  entry: parseEntry,
@@ -1144,7 +1263,10 @@ function mergeRequirements(apps) {
1144
1263
  for (const dependency of [web, seal, session, files])
1145
1264
  add('dokebi-app', dependency);
1146
1265
  for (const [name, app] of apps)
1147
- for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})])
1266
+ for (const item of [
1267
+ ...(app.requires ?? []),
1268
+ ...Object.values(app.modules ?? {}).map(mountedPlugin),
1269
+ ])
1148
1270
  add(name, requirement(item));
1149
1271
  const merged = [];
1150
1272
  for (const [name, list] of needs) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/app",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
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",