@dokebi/module 0.4.3 → 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/AI.md CHANGED
@@ -52,7 +52,7 @@ export default defineModule({
52
52
  });
53
53
  ```
54
54
 
55
- - `module` (ModuleContext) = PluginContext + `module` (the name) + `controller(token)`. Only what `requires` declares can be read with `get` or `getDependency`. When a controller factory passes a freshly built descriptor object, the declared descriptor with that name is found.
55
+ - `module` (ModuleContext) = PluginContext + `module` (the name) + `controller(token)` + `enabled()` (the switch, §2b). Only what `requires` declares can be read with `get` or `getDependency`. When a controller factory passes a freshly built descriptor object, the declared descriptor with that name is found.
56
56
  - `page` (ModulePage) = `{ app: { name, template, domain }, module, base, view, inertia }`. Build links with `page.base` (each app may use a different prefix).
57
57
  - `version` is an exact semver (default `'0.1.0'`). Requires with duplicate names are refused.
58
58
  - `views`: adds a template-ejs dependency automatically; the start fails without `views/default/`. Template names get the prefix `module.<name>`.
@@ -61,6 +61,73 @@ export default defineModule({
61
61
  - Route options are `WebRoute` options without `handler` and `constraints` (`ModuleRouteOptions`, so `seal` works).
62
62
  - `contributes`: the points of other plugins this module contributes to (§3a). Without it `module.contribute` is `UNDECLARED_POINT`.
63
63
 
64
+ ## 2a. Pages for each audience: named sets (0.4.5)
65
+
66
+ One feature often has pages for several audiences: a board has the members' list and writing, and the operators' moderation. Keep them in **one module** and declare its routes as **named sets**; each app says which set it shows when it mounts the module ([D-0216](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0216-module-sets.md)).
67
+
68
+ ```ts snippet
69
+ import { defineModule } from '@dokebi/module';
70
+ import { Posts } from './services/posts.ts';
71
+
72
+ const posts = new Posts();
73
+
74
+ export default defineModule({
75
+ name: 'board',
76
+ views: new URL('./views/', import.meta.url), // views/default/site/…, views/default/admin/…
77
+ routes: {
78
+ site(route) { // members, resellers: the list and writing
79
+ route.get('/', (request, reply, page) => page.view.reply(reply, 'site/list', { posts: posts.visible() }));
80
+ route.post('/', (request) => posts.write((request.body as { title: string }).title));
81
+ },
82
+ admin(route) { // operators: moderation
83
+ route.get('/', (request, reply, page) => page.view.reply(reply, 'admin/manage', { posts: posts.all() }));
84
+ route.post('/:id/hide', (request) => posts.hide(Number((request.params as { id: string }).id)));
85
+ },
86
+ },
87
+ sockets: { admin: () => [] }, // sockets and events take the same sets
88
+ });
89
+ ```
90
+
91
+ The apps (@dokebi/app 0.4.8 or later):
92
+
93
+ ```ts snippet
94
+ import { defineApp } from '@dokebi/app';
95
+ import board from '../../shared/modules/board/module.ts';
96
+
97
+ export const member = defineApp({ modules: { '/board': { module: board, use: 'site' } } });
98
+ export const admin = defineApp({ modules: { '/board': { module: board, use: 'admin' }, '/preview': { module: board, use: 'site' } } });
99
+ ```
100
+
101
+ - **A set an app does not choose is not a route, socket or event stream of that app**: the moderation page is not a route of the member site (404, and absent from its route table and from `npx dokebi describe`). Never guard pages by `page.app.name` instead: every page would be a route of every app, and one forgotten check opens it.
102
+ - **One shape for the three hooks**: `routes`, `sockets` and `events` are all functions (the module is mounted whole, as before) or all named sets; a hook may leave a set out (`sockets: { admin }` only). Set names are lower-case (`a-z`, `0-9`, `.`, `_`, `-`), 1 to 16 per hook (`INVALID_DEFINITION`).
103
+ - **The app chooses**: `{ module, use: 'admin' }` or `use: ['site', 'admin']` (both in one mount, in that order). A module of sets mounted whole, an unknown set, an empty or repeated choice and `use` on a module without sets fail `defineApp` (`INVALID_DEFINITION` of @dokebi/app). One app may mount two sets of one module at two prefixes; route ids must still be unique in the app, so give each set's routes ids of their own.
104
+ - **One module, one service**: every set runs in the same module context, with the same controllers, views folder and `setup` API. Lay the views out per set (`views/default/site/list.ejs`) and render `'site/list'`. App overrides work as for any module page (`src/apps/<app>/views/<template>/board/site/list.ejs`).
105
+ - **An older app package**: an @dokebi/app before 0.4.8 does not know sets; mounting a module of sets there fails the start with `INVALID_DEFINITION` (`fix`: update @dokebi/app) instead of mounting nothing.
106
+ - **Splitting instead**: a feature can also be one module per audience over a shared core module (`requires: [boardCore]`). It works with any version, at the cost of a folder and a module per audience; prefer sets when the audiences share one service.
107
+
108
+ ## 2b. Switching a module on and off while the app runs (0.4.5)
109
+
110
+ An instance may run a feature or not, decided while it runs (the center switches modules per tenant instance). Give the module `enabled`; it is asked on every request to the module's routes, sockets and event streams, in every app that mounts it.
111
+
112
+ ```ts snippet
113
+ import { defineModule } from '@dokebi/module';
114
+ import { dependency as settings } from '@dokebi/runtime-settings/dependency';
115
+
116
+ export default defineModule({
117
+ name: 'board',
118
+ requires: [settings],
119
+ // Synchronous, from memory: runtime-settings keeps its values in every worker and refreshes them.
120
+ enabled: (module) => module.getDependency(settings).get<string[]>('modules.enabled').includes('board'),
121
+ routes: { site(route) { /* … */ }, admin(route) { /* … */ } },
122
+ });
123
+ ```
124
+
125
+ - **Off** means: the module's routes answer the 404 of an unknown path of that app (its own `errors/404` page for a browser, the JSON 404 otherwise), as their **first step**: before login checks, body parsing and the route's own hooks. New WebSocket upgrades and SSE streams of the module are 404 too. `enabled` returns true again and they answer again, without a restart.
126
+ - **What it does not close**: a WebSocket or an SSE stream opened while the module was on stays open; background work of the module (job handlers, event subscriptions, timers) and its API to other modules (`get(board)`) keep running. The module reads `module.enabled()` itself where that work must stop.
127
+ - **Synchronous and cheap**: it runs per request. Read a value in memory (a @dokebi/runtime-settings `get`, an option), never a database. A throw, a value that is not a boolean and a Promise count as **off** and are logged at error once per window (`MODULE_SWITCH_FAILED`); a change seen between two requests is logged once at info (`MODULE_SWITCHED_OFF`, `MODULE_SWITCHED_ON`). Before the module has set up it is off.
128
+ - **Menus and permission lists**: `modules()` of the group plugin (`createPlugin({ app, entry: { modules } })`, the API of `dokebi-module`) answers `[{ name, enabled }]` now; `module.enabled()` answers for one module. An app builds its menu from them so a switched-off feature leaves the menu too.
129
+ - A module without `enabled` is always on, as before. The switch works with or without named sets; with sets it closes every set of the module in every app at once.
130
+
64
131
  ## 3. Mounting on apps and shared APIs
65
132
 
66
133
  - App: `defineApp({ modules: { '/board': board } })`. Routes, sockets and SSE routes answer **only on that app's domains and prefix**. Several apps can mount the same module under different prefixes. The root route (`'/'`) answers `/board` and `/board/`; other paths match exactly. Build links with `page.base` (for example `${page.base}/new`).
@@ -111,20 +178,20 @@ To change a module page, an app never edits the module file; it puts a file with
111
178
 
112
179
  ## 5. Group plugin and lifecycle
113
180
 
114
- - `createPlugin({ app, entry: { modules } })`: groups several modules into a dependency graph. The API is `{ names }` (`ModuleGroupApi`). It accepts only what `defineModule` made; duplicates are `INVALID_PLUGIN_INPUT`. A single module may also be registered directly with `app.register`.
181
+ - `createPlugin({ app, entry: { modules } })`: groups several modules into a dependency graph. The API is `{ names, modules() }` (`ModuleGroupApi`; `modules()` lists each module with its switch, §2b). It accepts only what `defineModule` made; duplicates are `INVALID_PLUGIN_INPUT`. A single module may also be registered directly with `app.register`.
115
182
  - Hooks: setup (register routes, return the API) → start → drain (stop new input, wait for work in progress) → deferred cleanup. Drain runs in reverse dependency order (modules that depend on this one first); unrelated modules drain at the same time.
116
183
  - A module instance is used by one Application only. There is no automatic discovery, dynamic import or hot reload while running.
117
184
  - Options of the group plugin are an empty object.
118
- - Debug logs (D-0047): `Modules registered` (the group), `Module set up` (requires, number of controllers, contributes, views prefix, whether routes, sockets and events exist, ms), `Module start finished`, `Module drain finished`. A missing or unreadable `views/default/` fails the start, with the original file error kept as `cause`.
185
+ - Debug logs (D-0047): `Modules registered` (the group), `Module set up` (requires, number of controllers, contributes, views prefix, whether routes, sockets and events exist, `sets`, `switch`, ms), `Module start finished`, `Module drain finished`. A missing or unreadable `views/default/` fails the start, with the original file error kept as `cause`.
119
186
 
120
187
  ## 6. Errors
121
188
 
122
189
  <!-- docs-check: complete-error-codes ModuleErrorCode -->
123
- `DokebiError` (`plugin: 'dokebi-module'`, a `fix` that says how to repair it): `INVALID_DEFINITION` (arguments of `defineModule`), `INVALID_REQUIREMENT` (shape of requires, duplicate names), `INVALID_ENTRY` (the group entry file; at registration the cause of `INVALID_PLUGIN_INPUT`), `ALREADY_SET_UP` (one instance in two apps), `NOT_SET_UP` (context used before setup), `NO_CONTROLLERS`, `VIEWS_MISSING` (no `views/default/`; the file error is the `cause`), `INVALID_CONTRIBUTION` (`contributes` is not a list of distinct points made by `definePoint`, or has more than 64), `UNDECLARED_POINT` (`module.contribute` to a point missing from `contributes`, or `module.collect`; the `fix` names the module). Warn log `POINT_NOT_COLLECTED` (core): values no registered plugin collects were dropped. Options of the group plugin other than an empty object are `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`). The `defineOptions` declaration in `src/options.ts` is the parser, and the build writes `options.schema.json` from it (D-0063 §3; never edit it by hand). Before 0.4.0 the codes had a `MODULE_` prefix (D-0071).
190
+ `DokebiError` (`plugin: 'dokebi-module'`, a `fix` that says how to repair it): `INVALID_DEFINITION` (arguments of `defineModule`, named sets outside their rule, a module of sets mounted by an app package that does not know sets), `INVALID_REQUIREMENT` (shape of requires, duplicate names), `INVALID_ENTRY` (the group entry file; at registration the cause of `INVALID_PLUGIN_INPUT`), `ALREADY_SET_UP` (one instance in two apps), `NOT_SET_UP` (context used before setup), `NO_CONTROLLERS`, `VIEWS_MISSING` (no `views/default/`; the file error is the `cause`), `INVALID_CONTRIBUTION` (`contributes` is not a list of distinct points made by `definePoint`, or has more than 64), `UNDECLARED_POINT` (`module.contribute` to a point missing from `contributes`, or `module.collect`; the `fix` names the module). Warn log `POINT_NOT_COLLECTED` (core): values no registered plugin collects were dropped. Options of the group plugin other than an empty object are `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`). The `defineOptions` declaration in `src/options.ts` is the parser, and the build writes `options.schema.json` from it (D-0063 §3; never edit it by hand). Before 0.4.0 the codes had a `MODULE_` prefix (D-0071).
124
191
 
125
192
  ## 7. Cautions
126
193
 
127
- - A module does not depend on apps (never branch on an app name). Handle per-app differences with `page.app` and the app's view overrides.
194
+ - A module does not depend on apps (never branch on an app name). Pages of different audiences are named sets the app chooses (§2a); smaller per-app differences use `page.app` and the app's view overrides.
128
195
  - `moduleMount` and `MODULE_MOUNT` are the internal link @dokebi/app uses. App code does not use them.
129
196
  - Socket and SSE route types (`ModuleSocketRoute`, `ModuleEventRoute`) are defined by shape only, so projects that do not use them need neither @dokebi/websocket nor @dokebi/sse. When used, add that package (otherwise the app start fails: `has sockets; add @dokebi/websocket`, `has event streams; add @dokebi/sse`). Both take `config: { id }`, the route id (D-0140), like the module's routes: it must be unique among the routes, sockets and streams of each app that mounts the module (`DUPLICATE_ROUTE_ID` at start otherwise).
130
197
  - Do not treat the end of a response or a dropped connection as the work being done. Work detached from the request is awaited in the module's `drain`.
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
- # @dokebi/module 0.4.1
1
+ # @dokebi/module 0.4.5
2
2
 
3
3
  An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). A module is **one feature as an MVC unit of business code** ([D-0022](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0022-plugin-boundaries-and-db.md), [D-0032](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0032-feature-modules.md)). It keeps controllers, services, models, views, routes and sockets in one folder, and apps mount it under a prefix. It is not an HTTP-only bundle, so business code without a web side (job processing, event subscriptions) is a module too.
4
4
 
5
+ Since 0.4.5 a module may declare its routes, sockets and event streams as named sets (one per audience: `site`, `admin`), and each app mounts the sets it shows: `{ module, use: 'admin' }` with @dokebi/app 0.4.8 ([D-0216](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0216-module-sets.md)).
6
+
5
7
  ## Folder
6
8
 
7
9
  ```
package/dist/index.d.ts CHANGED
@@ -13,6 +13,12 @@ export interface ModuleContext extends PluginContext {
13
13
  /** The module name (the folder name under src/shared/modules). */
14
14
  readonly module: string;
15
15
  controller<T>(definition: ControllerDefinition<T>): T;
16
+ /**
17
+ * D-0216 (0.4.5): whether the module is switched on now (its `enabled`; true without one). Its
18
+ * own background work (job handlers, subscriptions) reads it: the switch closes only routes,
19
+ * sockets and event streams by itself.
20
+ */
21
+ enabled(): boolean;
16
22
  }
17
23
  /** What a module route handler receives besides the Fastify request and reply (D-0032). */
18
24
  export interface ModulePage {
@@ -83,6 +89,15 @@ export interface ModuleEventRoute {
83
89
  readonly namespace?: string;
84
90
  } | undefined>;
85
91
  }
92
+ export type ModuleRoutesHook = (route: ModuleRouter, module: ModuleContext) => Awaitable<void>;
93
+ export type ModuleSocketsHook = (module: ModuleContext) => Awaitable<readonly ModuleSocketRoute[]>;
94
+ export type ModuleEventsHook = (module: ModuleContext) => Awaitable<readonly ModuleEventRoute[]>;
95
+ /**
96
+ * D-0216: one hook, mounted whole by every app, or **named sets** of it (`{ site, admin }`): an
97
+ * app that mounts the module names the sets it shows (`{ module, use: 'admin' }`), and only
98
+ * their routes, sockets and event streams are registered on that app's domains.
99
+ */
100
+ export type ModuleHook<H> = H | Readonly<Record<string, H>>;
86
101
  export interface ModuleDefinition<T> {
87
102
  readonly name: string;
88
103
  /** Exact plugin version of this module. Default '0.1.0'. */
@@ -99,12 +114,22 @@ export interface ModuleDefinition<T> {
99
114
  readonly contributes?: readonly Pick<ContributionPoint<unknown>, 'name'>[];
100
115
  /** Folder with one sub-folder per template (`default/` is required). */
101
116
  readonly views?: URL;
102
- /** Routes registered by every app that mounts this module (`defineApp({ modules })`). */
103
- routes?(route: ModuleRouter, module: ModuleContext): Awaitable<void>;
104
- /** WebSocket routes registered by every app that mounts this module, under its prefix. */
105
- sockets?(module: ModuleContext): Awaitable<readonly ModuleSocketRoute[]>;
106
- /** SSE routes (@dokebi/sse) registered by every app that mounts this module, under its prefix. */
107
- events?(module: ModuleContext): Awaitable<readonly ModuleEventRoute[]>;
117
+ /**
118
+ * Routes registered by every app that mounts this module (`defineApp({ modules })`), or named
119
+ * sets of them (D-0216): `{ site(route, module) {…}, admin(route, module) {…} }`.
120
+ */
121
+ readonly routes?: ModuleHook<ModuleRoutesHook>;
122
+ /** WebSocket routes under the mount's prefix; named sets as `routes` (one shape for all three). */
123
+ readonly sockets?: ModuleHook<ModuleSocketsHook>;
124
+ /** SSE routes (@dokebi/sse) under the mount's prefix; named sets as `routes`. */
125
+ readonly events?: ModuleHook<ModuleEventsHook>;
126
+ /**
127
+ * D-0216 (0.4.5): whether the module is switched on, asked on every request to its routes,
128
+ * sockets and event streams in every app that mounts it. Synchronous and cheap (a value in
129
+ * memory, such as a @dokebi/runtime-settings `get`). False: they answer the 404 of an unknown
130
+ * path. A throw or a value that is not a boolean counts as off (error MODULE_SWITCH_FAILED).
131
+ */
132
+ enabled?(module: ModuleContext): boolean;
108
133
  /** Optional; the result is the API of this module for plugins and modules that require it. */
109
134
  setup?(module: ModuleContext): Awaitable<T>;
110
135
  start?(module: ModuleContext): Awaitable<void>;
@@ -118,12 +143,29 @@ export interface ModuleMount {
118
143
  readonly name: string;
119
144
  /** Template prefix of the module views (`module.<name>`), when the module has views. */
120
145
  readonly views: string | undefined;
121
- readonly routes: ModuleDefinition<unknown>['routes'];
122
- readonly sockets: ModuleDefinition<unknown>['sockets'];
146
+ /**
147
+ * The hooks of a module mounted whole. For a module of named sets these are guards that fail
148
+ * the start: an app package older than the sets (before @dokebi/app 0.4.8) would call them.
149
+ */
150
+ readonly routes: ModuleRoutesHook | undefined;
151
+ readonly sockets: ModuleSocketsHook | undefined;
123
152
  /** SSE routes (0.1.3); undefined for a module without them (and in older module packages). */
124
- readonly events: ModuleDefinition<unknown>['events'];
153
+ readonly events: ModuleEventsHook | undefined;
154
+ /**
155
+ * D-0216 (0.4.5): the set names of a module that declares named sets, in declaration order;
156
+ * undefined for a module mounted whole (and in older module packages).
157
+ */
158
+ readonly sets?: readonly string[] | undefined;
159
+ /** D-0216 (0.4.5): the hooks of the chosen sets, in the order chosen (sets without one skipped). */
160
+ hooks?(sets: readonly string[]): {
161
+ readonly routes: readonly ModuleRoutesHook[];
162
+ readonly sockets: readonly ModuleSocketsHook[];
163
+ readonly events: readonly ModuleEventsHook[];
164
+ };
125
165
  /** The module context; available once the module has been set up. */
126
166
  context(): ModuleContext;
167
+ /** D-0216 (0.4.5): the switch (`enabled` of the definition; true without one). */
168
+ enabled?(): boolean;
127
169
  }
128
170
  export declare const MODULE_MOUNT: unique symbol;
129
171
  export declare function defineModule<T = void>(definition: ModuleDefinition<T>): Plugin<T>;
@@ -134,5 +176,13 @@ export interface ModuleEntry {
134
176
  }
135
177
  export interface ModuleGroupApi {
136
178
  readonly names: readonly string[];
179
+ /**
180
+ * D-0216 (0.4.5): every module of the group with its switch now (an app's menu, a permission
181
+ * list, the center's view of an instance).
182
+ */
183
+ modules(): readonly {
184
+ readonly name: string;
185
+ readonly enabled: boolean;
186
+ }[];
137
187
  }
138
188
  export declare const createPlugin: import("@dokebi/core").PluginFactory<ModuleGroupApi>;
package/dist/index.js CHANGED
@@ -2,9 +2,10 @@ import { stat } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { types } from 'node:util';
4
4
  import { DokebiError, definePlugin, dependencyOf, providerDependency, } from '@dokebi/core';
5
+ import { diagnostics } from '@dokebi/core/libraries';
5
6
  import { options } from './options.js';
6
7
  const FIX = {
7
- INVALID_DEFINITION: 'Pass defineModule a lower-case name (a-z, 0-9, ., _, -) and only the documented fields: requires and controllers arrays, views as a file: URL, hooks as functions.',
8
+ INVALID_DEFINITION: 'Pass defineModule a lower-case name (a-z, 0-9, ., _, -) and only the documented fields: requires and controllers arrays, views as a file: URL, hooks as functions; routes, sockets and events either all functions or all named sets ({ site() {…}, admin() {…} }, 1 to 16 lower-case names).',
8
9
  INVALID_REQUIREMENT: 'List plugin instances or dependency descriptors ({ name, version }) in requires, each name once.',
9
10
  INVALID_ENTRY: 'Export modules: an array of distinct defineModule plugins (at most 1024) from src/shared/modules/index.ts (npx dokebi module add <name> writes it).',
10
11
  ALREADY_SET_UP: 'Create the module plugin once per Application (call defineModule for each application).',
@@ -26,6 +27,8 @@ const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
26
27
  /** core's point name (`<owner plugin>:<name>`) and its limit per plugin (D-0063). */
27
28
  const POINT_NAME = /^[a-z0-9][a-z0-9._/-]{0,95}:[a-z0-9][a-z0-9._-]{0,63}$/;
28
29
  const POINT_LIMIT = 64;
30
+ /** Named sets of one hook (D-0216): audiences of a module, not pages, so a few. */
31
+ const SET_LIMIT = 16;
29
32
  const DEFINITION_KEYS = new Set([
30
33
  'name',
31
34
  'version',
@@ -36,6 +39,7 @@ const DEFINITION_KEYS = new Set([
36
39
  'routes',
37
40
  'sockets',
38
41
  'events',
42
+ 'enabled',
39
43
  'setup',
40
44
  'start',
41
45
  'drain',
@@ -75,7 +79,7 @@ function contributedPoints(value, module) {
75
79
  }
76
80
  return Object.freeze([...names]);
77
81
  }
78
- function moduleContext(context, name, declared, controllers, points) {
82
+ function moduleContext(context, name, declared, controllers, points, enabled) {
79
83
  // core accepts only the descriptor object this module declared; look it up by name.
80
84
  const own = (dependency) => declared.get(dependency?.name) ?? dependency;
81
85
  return Object.freeze({
@@ -115,6 +119,7 @@ function moduleContext(context, name, declared, controllers, points) {
115
119
  const pointName = point?.name;
116
120
  throw moduleError('UNDECLARED_POINT', `Module ${name} cannot collect ${typeof pointName === 'string' ? pointName : 'a point'}`, undefined, 'Modules only contribute. Collect the point in a plugin that declares it in collects (definePlugin), and give the module what it needs through requires.');
117
121
  },
122
+ enabled,
118
123
  controller: (definition) => {
119
124
  const api = controllers();
120
125
  if (!api)
@@ -124,7 +129,9 @@ function moduleContext(context, name, declared, controllers, points) {
124
129
  });
125
130
  }
126
131
  export function defineModule(definition) {
127
- const version = definition.version ?? '0.1.0';
132
+ // Read after the check below would be too late for the check itself; `?.` so that nothing
133
+ // (null, undefined) is INVALID_DEFINITION, not a TypeError (audit R9-g13-5).
134
+ const version = definition?.version ?? '0.1.0';
128
135
  if (definition === null ||
129
136
  typeof definition !== 'object' ||
130
137
  types.isProxy(definition) ||
@@ -136,7 +143,28 @@ export function defineModule(definition) {
136
143
  (definition.controllers !== undefined && !Array.isArray(definition.controllers)) ||
137
144
  (definition.views !== undefined &&
138
145
  (!(definition.views instanceof URL) || definition.views.protocol !== 'file:')) ||
139
- ['routes', 'sockets', 'events', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function'))
146
+ ['enabled', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function') ||
147
+ ['routes', 'sockets', 'events'].some((hook) => {
148
+ const value = definition[hook];
149
+ if (value === undefined || typeof value === 'function')
150
+ return false;
151
+ // Named sets (D-0216): a plain object of 1 to 16 set names, each a function.
152
+ if (value === null ||
153
+ typeof value !== 'object' ||
154
+ Array.isArray(value) ||
155
+ types.isProxy(value) ||
156
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
157
+ return true;
158
+ const entries = Object.entries(value);
159
+ return (entries.length === 0 ||
160
+ entries.length > SET_LIMIT ||
161
+ entries.some(([set, fn]) => !NAME.test(set) || typeof fn !== 'function'));
162
+ }) ||
163
+ // One shape for the three: all plain functions, or all named sets.
164
+ new Set(['routes', 'sockets', 'events']
165
+ .map((hook) => definition[hook])
166
+ .filter((value) => value !== undefined)
167
+ .map((value) => typeof value === 'function')).size > 1)
140
168
  throw moduleError('INVALID_DEFINITION', 'Invalid module definition');
141
169
  const { name, views } = definition;
142
170
  const points = contributedPoints(definition.contributes, name);
@@ -152,10 +180,49 @@ export function defineModule(definition) {
152
180
  let started = false;
153
181
  let controllers;
154
182
  let current;
183
+ let repeats;
184
+ let last;
185
+ /**
186
+ * The switch (D-0216), asked per request: `enabled` of the definition with the module context.
187
+ * A failure closes the module rather than opening it, and is logged once per window; a change
188
+ * of state is logged once.
189
+ */
190
+ const switchOn = () => {
191
+ const ask = definition.enabled;
192
+ if (!ask)
193
+ return true;
194
+ const context = current;
195
+ // Before setup nothing of the module is served.
196
+ if (!context)
197
+ return false;
198
+ let value;
199
+ let failure;
200
+ try {
201
+ value = ask.call(definition, context);
202
+ }
203
+ catch (error) {
204
+ failure = error;
205
+ }
206
+ if (failure !== undefined || typeof value !== 'boolean') {
207
+ repeats ??= new diagnostics.Repeats({ logger: context.logger });
208
+ repeats.log('error', 'Module switch failed; the module answers as switched off.', 'MODULE_SWITCH_FAILED', failure ??
209
+ moduleError('INVALID_DEFINITION', `enabled of module ${name} returned ${value instanceof Promise ? 'a Promise' : typeof value}, not a boolean (it must be synchronous)`), { module: name });
210
+ value = false;
211
+ }
212
+ if (value !== last) {
213
+ if (last !== undefined)
214
+ context.logger.log('info', value ? 'Module switched on' : 'Module switched off', {
215
+ code: value ? 'MODULE_SWITCHED_ON' : 'MODULE_SWITCHED_OFF',
216
+ module: name,
217
+ });
218
+ last = value;
219
+ }
220
+ return value;
221
+ };
155
222
  const prefix = `module.${name}`;
156
223
  const hook = (key) => async (context) => {
157
224
  const begin = performance.now();
158
- await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet));
225
+ await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet, switchOn));
159
226
  context.logger.log('debug', `Module ${key} finished`, {
160
227
  module: name,
161
228
  ms: Math.round(performance.now() - begin),
@@ -174,7 +241,11 @@ export function defineModule(definition) {
174
241
  if (started)
175
242
  throw moduleError('ALREADY_SET_UP', 'Create one module instance per Application');
176
243
  started = true;
177
- current = moduleContext(context, name, declared, () => controllers, pointSet);
244
+ current = moduleContext(context, name, declared, () => controllers, pointSet, switchOn);
245
+ // Counted failures of the switch are written before the module goes away.
246
+ context.defer(() => {
247
+ repeats?.flush();
248
+ });
178
249
  const begin = performance.now();
179
250
  if (definition.controllers?.length) {
180
251
  const { createControllers } = await import('@dokebi/controller');
@@ -201,6 +272,8 @@ export function defineModule(definition) {
201
272
  contributes: points,
202
273
  views: views ? prefix : false,
203
274
  routes: Boolean(definition.routes),
275
+ sets: sets ?? false,
276
+ switch: Boolean(definition.enabled),
204
277
  sockets: Boolean(definition.sockets),
205
278
  events: Boolean(definition.events),
206
279
  ms: Math.round(performance.now() - begin),
@@ -210,17 +283,53 @@ export function defineModule(definition) {
210
283
  ...(definition.start ? { start: hook('start') } : {}),
211
284
  ...(definition.drain ? { drain: hook('drain') } : {}),
212
285
  };
286
+ const asSets = (value) => value !== undefined && typeof value !== 'function'
287
+ ? value
288
+ : undefined;
289
+ const routeSets = asSets(definition.routes);
290
+ const socketSets = asSets(definition.sockets);
291
+ const eventSets = asSets(definition.events);
292
+ const sets = routeSets || socketSets || eventSets
293
+ ? Object.freeze([
294
+ ...new Set([
295
+ ...Object.keys(routeSets ?? {}),
296
+ ...Object.keys(socketSets ?? {}),
297
+ ...Object.keys(eventSets ?? {}),
298
+ ]),
299
+ ])
300
+ : undefined;
301
+ // A module of sets read by an app package that does not know sets would mount nothing and
302
+ // answer 404 everywhere without a word: its whole-module hooks refuse instead.
303
+ const tooOld = () => {
304
+ throw moduleError('INVALID_DEFINITION', `Module ${name} declares the sets ${sets?.join(', ')}; the app package mounting it does not know sets`, undefined, 'Update @dokebi/app to 0.4.8 or later, and mount the module as { module, use: "<set>" }.');
305
+ };
306
+ const whole = (value) => typeof value === 'function'
307
+ ? value.bind(definition)
308
+ : sets
309
+ ? tooOld
310
+ : undefined;
311
+ const chosenOf = (table, chosen) => Object.freeze(chosen.flatMap((set) => {
312
+ const hook = table && Object.hasOwn(table, set) ? table[set] : undefined;
313
+ return hook ? [hook.bind(definition)] : [];
314
+ }));
213
315
  const mount = Object.freeze({
214
316
  name,
215
317
  views: views ? prefix : undefined,
216
- routes: definition.routes?.bind(definition),
217
- sockets: definition.sockets?.bind(definition),
218
- events: definition.events?.bind(definition),
318
+ routes: whole(definition.routes),
319
+ sockets: whole(definition.sockets),
320
+ events: whole(definition.events),
321
+ sets,
322
+ hooks: (chosen) => Object.freeze({
323
+ routes: chosenOf(routeSets, chosen),
324
+ sockets: chosenOf(socketSets, chosen),
325
+ events: chosenOf(eventSets, chosen),
326
+ }),
219
327
  context: () => {
220
328
  if (!current)
221
329
  throw moduleError('NOT_SET_UP', `Module ${name} is not set up yet`);
222
330
  return current;
223
331
  },
332
+ enabled: switchOn,
224
333
  });
225
334
  Object.defineProperty(plugin, MODULE_MOUNT, { value: mount });
226
335
  return Object.freeze(plugin);
@@ -265,20 +374,29 @@ function parseEntry(input) {
265
374
  }
266
375
  class ModuleGroupRuntime {
267
376
  names;
268
- constructor(names) {
377
+ mounts;
378
+ constructor(names, mounts) {
269
379
  this.names = names;
380
+ this.mounts = mounts;
270
381
  }
271
382
  setup(context) {
272
383
  context.logger.log('debug', 'Modules registered', { modules: this.names });
273
- return Object.freeze({ names: this.names });
384
+ const mounts = this.mounts;
385
+ return Object.freeze({
386
+ names: this.names,
387
+ modules: () => Object.freeze(mounts.map((mount) => Object.freeze({ name: mount.name, enabled: mount.enabled?.() ?? true }))),
388
+ });
274
389
  }
275
390
  }
276
391
  export const createPlugin = definePlugin({
277
392
  name: 'dokebi-module',
278
- version: '0.4.3',
393
+ version: '0.4.5',
279
394
  core: '^0.4.0',
280
395
  options,
281
396
  entry: parseEntry,
282
397
  dependencies: ({ entry }) => (entry ?? []).map((module) => dependencyOf(module)),
283
- instance: ({ dependencies }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name))),
398
+ instance: ({ dependencies, entry }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name)), Object.freeze((entry ?? []).flatMap((module) => {
399
+ const mount = moduleMount(module);
400
+ return mount ? [mount] : [];
401
+ }))),
284
402
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/module",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
4
4
  "description": "Feature modules for Dokebi apps: controllers, models, views and routes in one folder mounted under a prefix.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -95,8 +95,8 @@
95
95
  "devDependencies": {
96
96
  "@dokebi/controller": "0.4.2",
97
97
  "@dokebi/template-ejs": "0.4.3",
98
- "@dokebi/template-inertia": "0.4.6",
99
- "@dokebi/web": "0.4.6"
98
+ "@dokebi/template-inertia": "0.4.7",
99
+ "@dokebi/web": "0.4.7"
100
100
  },
101
101
  "publishConfig": {
102
102
  "access": "public",