@dokebi/app 0.2.0 → 0.4.0

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
@@ -2,10 +2,17 @@ import { stat } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { types } from 'node:util';
4
4
  import { createControllers, } from '@dokebi/controller';
5
- import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
5
+ import { definePlugin, dependencyOf, optionalDependency, } from '@dokebi/core';
6
+ import { dependency as web } from '@dokebi/web/dependency';
7
+ import { realtime, viewEngines, } from '@dokebi/web/points';
8
+ import { AppError } from './errors.js';
9
+ import { options as declaration } from './options.js';
10
+ export { AppError } from './errors.js';
11
+ export { options } from './options.js';
6
12
  const NAME = /^[a-z][a-z0-9-]{0,31}$/;
7
- const HOST = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
8
13
  const DEFAULT_TEMPLATE = 'default';
14
+ // Not `import … from 'node:http'`: its ESM facade loads undici (D-0070 §5); Fastify loaded it already.
15
+ const { STATUS_CODES } = process.getBuiltinModule('node:http');
9
16
  /** A module mount prefix: `/` or `/a/b`. */
10
17
  const PREFIX = /^\/(?:[a-z0-9][a-z0-9._~-]*(?:\/[a-z0-9][a-z0-9._~-]*)*)?$/;
11
18
  /** Read without importing @dokebi/module (see its MODULE_MOUNT). */
@@ -24,10 +31,13 @@ function joinPath(base, path) {
24
31
  /** The Fastify route constraint that selects an app by request host. */
25
32
  export const APP_CONSTRAINT = 'dokebiApp';
26
33
  const defined = new WeakSet();
34
+ function invalidDefinition(message) {
35
+ return new AppError('INVALID_DEFINITION', message);
36
+ }
27
37
  /** Declares one app. Its name is the key under which the generated code registers it. */
28
38
  export function defineApp(definition) {
29
39
  if (definition === null || typeof definition !== 'object' || types.isProxy(definition))
30
- throw new TypeError('Invalid app definition');
40
+ throw invalidDefinition('Invalid app definition');
31
41
  for (const key of Object.keys(definition))
32
42
  if (![
33
43
  'requires',
@@ -43,64 +53,31 @@ export function defineApp(definition) {
43
53
  'start',
44
54
  'drain',
45
55
  ].includes(key))
46
- throw new TypeError('Unknown app definition field: ' + key);
56
+ throw invalidDefinition('Unknown app definition field: ' + key);
47
57
  if (definition.requires !== undefined && !Array.isArray(definition.requires))
48
- throw new TypeError('App requires must be an array');
58
+ throw invalidDefinition('App requires must be an array');
49
59
  if (definition.controllers !== undefined && !Array.isArray(definition.controllers))
50
- throw new TypeError('App controllers must be an array');
60
+ throw invalidDefinition('App controllers must be an array');
51
61
  if (definition.views !== undefined &&
52
62
  (!(definition.views instanceof URL) || definition.views.protocol !== 'file:'))
53
- throw new TypeError('App views must be a file: URL');
63
+ throw invalidDefinition('App views must be a file: URL');
54
64
  if (definition.modules !== undefined) {
55
65
  if (!plain(definition.modules))
56
- throw new TypeError('App modules must be a plain object');
66
+ throw invalidDefinition('App modules must be a plain object');
57
67
  for (const [prefix, plugin] of Object.entries(definition.modules)) {
58
68
  if (!PREFIX.test(prefix))
59
- throw new TypeError('Invalid module prefix: ' + prefix);
69
+ throw invalidDefinition('Invalid module prefix: ' + prefix);
60
70
  if (!mountOf(plugin))
61
- throw new TypeError('App modules must be made with defineModule');
71
+ throw invalidDefinition('App modules must be made with defineModule');
62
72
  }
63
73
  }
64
74
  for (const hook of ['shared', 'routes', 'sockets', 'events', 'setup', 'start', 'drain'])
65
75
  if (definition[hook] !== undefined && typeof definition[hook] !== 'function')
66
- throw new TypeError(`App ${hook} must be a function`);
76
+ throw invalidDefinition(`App ${hook} must be a function`);
67
77
  const frozen = Object.freeze({ ...definition });
68
78
  defined.add(frozen);
69
79
  return frozen;
70
80
  }
71
- /** Most namespaces one app may list. */
72
- const MAX_NAMESPACES = 32;
73
- function parseApps(input) {
74
- const result = new Map();
75
- if (input === undefined)
76
- return result;
77
- if (!plain(input))
78
- throw new TypeError('Invalid dokebi-app apps');
79
- for (const [app, settings] of Object.entries(input)) {
80
- if (!NAME.test(app) || !plain(settings))
81
- throw new TypeError('Invalid apps entry: ' + app);
82
- const { realtime, ...extra } = settings;
83
- if (Object.keys(extra).length)
84
- throw new TypeError('Invalid apps entry: ' + app);
85
- let namespaces;
86
- if (realtime !== undefined) {
87
- if (!plain(realtime))
88
- throw new TypeError('Invalid realtime settings of app ' + app);
89
- const { namespaces: list, ...more } = realtime;
90
- if (Object.keys(more).length ||
91
- !Array.isArray(list) ||
92
- types.isProxy(list) ||
93
- list.length < 1 ||
94
- list.length > MAX_NAMESPACES ||
95
- list.some((item) => typeof item !== 'string' || !NAME.test(item)) ||
96
- new Set(list).size !== list.length)
97
- throw new TypeError(`apps.${app}.realtime.namespaces must list 1 to ${MAX_NAMESPACES} distinct names matching ${NAME.source}`);
98
- namespaces = Object.freeze([...list]);
99
- }
100
- result.set(app, Object.freeze({ namespaces }));
101
- }
102
- return result;
103
- }
104
81
  function plain(value) {
105
82
  return (value !== null &&
106
83
  typeof value === 'object' &&
@@ -108,82 +85,43 @@ function plain(value) {
108
85
  !types.isProxy(value) &&
109
86
  [Object.prototype, null].includes(Object.getPrototypeOf(value)));
110
87
  }
111
- function parseOptions(input) {
112
- if (!plain(input))
113
- throw new TypeError('Invalid dokebi-app options');
114
- const { domains, unknownDomain, apps, ...rest } = input;
115
- if (Object.keys(rest).length || !plain(domains))
116
- throw new TypeError('Invalid dokebi-app options');
117
- const map = new Map();
118
- for (const [host, target] of Object.entries(domains)) {
119
- if (host.length > 253 || !HOST.test(host) || !plain(target))
120
- throw new TypeError('Invalid domain entry');
121
- const { app, template = DEFAULT_TEMPLATE, seal = false, ...extra } = target;
122
- if (Object.keys(extra).length ||
123
- typeof app !== 'string' ||
124
- !NAME.test(app) ||
125
- typeof template !== 'string' ||
126
- !NAME.test(template) ||
127
- typeof seal !== 'boolean')
128
- throw new TypeError('Invalid domain entry');
129
- map.set(host, Object.freeze({ app, template, seal }));
130
- }
131
- if (map.size > 1024)
132
- throw new TypeError('Too many domains');
133
- if (unknownDomain !== undefined && unknownDomain !== 'reject') {
134
- if (typeof unknownDomain !== 'string' || !map.has(unknownDomain))
135
- throw new TypeError('unknownDomain must be reject or a configured domain');
136
- }
88
+ /** The parsed options (checked by the declaration, D-0063 §3) as maps. */
89
+ function settings(parsed) {
90
+ const apps = new Map();
91
+ for (const [app, value] of Object.entries(parsed.apps ?? {}))
92
+ apps.set(app, Object.freeze({ namespaces: value.realtime?.namespaces }));
137
93
  return Object.freeze({
138
- domains: map,
139
- unknownDomain: unknownDomain === 'reject' ? undefined : unknownDomain,
140
- apps: parseApps(apps),
94
+ domains: new Map(Object.entries(parsed.domains)),
95
+ unknownDomain: parsed.unknownDomain === 'reject' ? undefined : parsed.unknownDomain,
96
+ apps,
141
97
  });
142
98
  }
143
99
  function parseEntry(input) {
144
100
  if (input === undefined)
145
101
  return new Map();
146
102
  if (!plain(input) || Object.keys(input).some((key) => key !== 'apps') || !plain(input.apps))
147
- throw new TypeError('Invalid dokebi-app entry');
103
+ throw new AppError('INVALID_ENTRY', 'Invalid dokebi-app entry');
148
104
  const apps = new Map();
149
105
  for (const [name, definition] of Object.entries(input.apps)) {
150
106
  if (!NAME.test(name) || !defined.has(definition))
151
- throw new TypeError('Apps must be made with defineApp and named ' + NAME.source);
107
+ throw new AppError('INVALID_ENTRY', 'Apps must be made with defineApp and named ' + NAME.source);
152
108
  apps.set(name, definition);
153
109
  }
154
110
  return apps;
155
111
  }
156
- const web = providerDependency({
157
- name: 'dokebi-web',
158
- version: '^0.2.0',
159
- packageName: '@dokebi/web',
160
- load: () => import('@dokebi/web'),
161
- });
162
- const ejs = providerDependency({
163
- name: 'dokebi-template-ejs',
164
- version: '^0.1.0',
165
- packageName: '@dokebi/template-ejs',
166
- load: () => import('@dokebi/template-ejs'),
167
- });
168
- const inertia = optionalDependency({
169
- name: 'dokebi-template-inertia',
170
- version: '^0.2.0',
171
- });
172
- const websocket = optionalDependency({
173
- name: 'dokebi-websocket',
174
- version: '^0.1.0 || ^0.2.0 || ^0.3.0',
175
- });
176
112
  /**
177
113
  * The seal plugin (D-0059 §4, D-0062), looked up by name only: a host with `seal: true` needs it
178
- * (it serves `/dokebi/seal/*`, seals the sockets through @dokebi/websocket and fills the HTTP
179
- * seal slot of @dokebi/web).
114
+ * (it serves `/dokebi/seal/*`, seals the sockets through the websocket transport and fills the
115
+ * HTTP seal slot of @dokebi/web).
180
116
  */
181
- const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.1.0' });
182
- /** Server-sent events (@dokebi/sse): app and module `events` routes and `realtime().publish`. */
183
- const sse = optionalDependency({ name: 'dokebi-sse', version: '^0.1.0' });
184
- function coded(message, code) {
185
- return Object.assign(new Error(message), { code });
186
- }
117
+ const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.4.0' });
118
+ /** Packages that offer an engine or transport, for the fix of a missing one. */
119
+ const PROVIDERS = {
120
+ ejs: '@dokebi/template-ejs',
121
+ inertia: '@dokebi/template-inertia',
122
+ websocket: '@dokebi/websocket',
123
+ sse: '@dokebi/sse',
124
+ };
187
125
  /** A realtime target string: 1 to 256 characters. */
188
126
  function targetText(value) {
189
127
  return typeof value === 'string' && value.length > 0 && value.length <= 256;
@@ -195,50 +133,40 @@ function checkTarget(target) {
195
133
  (value.tenant !== undefined && !targetText(value.tenant)) ||
196
134
  (value.member !== undefined && !targetText(value.member)) ||
197
135
  (value.room !== undefined && !targetText(value.room)))
198
- throw coded('A realtime target is { tenant?, member?, room? } with strings of 1 to 256 characters', 'INVALID_TARGET');
136
+ throw new AppError('INVALID_TARGET', 'A realtime target is { tenant?, member?, room? } with strings of 1 to 256 characters');
199
137
  return value;
200
138
  }
201
- /** The handle of one namespace (D-0061): the namespace prefix on the way in, off on the way out. */
139
+ function unavailable(app, what, kind) {
140
+ return new AppError('REALTIME_UNAVAILABLE', `App ${app}: ${what} needs ${PROVIDERS[kind]}`, {
141
+ fix: `npx dokebi add ${PROVIDERS[kind]} (it contributes the ${kind} transport to dokebi-web:realtime).`,
142
+ });
143
+ }
144
+ /** The handle of one namespace (D-0061) over the transports' namespace handles. */
202
145
  function realtimeHandle(app, namespace, sockets, streams) {
203
- const prefix = `${namespace}:`;
146
+ let socketHandle;
147
+ let streamHandle;
204
148
  const websocket = () => {
205
- if (!sockets || typeof sockets.list !== 'function')
206
- throw coded(`App ${app}: realtime sockets need @dokebi/websocket 0.3 or later`, 'REALTIME_UNAVAILABLE');
207
- return sockets;
149
+ if (!sockets)
150
+ throw unavailable(app, 'realtime sockets', 'websocket');
151
+ socketHandle ??= sockets.handle(namespace);
152
+ return socketHandle;
208
153
  };
209
- const filter = (target) => ({
210
- ...(target.tenant === undefined
211
- ? { tenantPrefix: prefix }
212
- : { tenant: prefix + target.tenant }),
213
- ...(target.room === undefined ? {} : { room: target.room }),
214
- ...(target.member === undefined ? {} : { member: target.member }),
215
- });
216
154
  return Object.freeze({
217
155
  namespace,
218
- list: async (target = {}) => {
219
- const connections = await websocket().list(filter(checkTarget(target)));
220
- return Object.freeze(connections.map((connection) => Object.freeze({ ...connection, tenant: connection.tenant.slice(prefix.length) })));
221
- },
222
- send: async (target, type, data) => websocket().send(filter(checkTarget(target)), type, data),
223
- kick: async (target, code, reason) => websocket().kick(filter(checkTarget(target)), code, reason),
156
+ list: async (target = {}) => websocket().list(checkTarget(target)),
157
+ send: async (target, type, data) => websocket().send(checkTarget(target), type, data),
158
+ kick: async (target, code, reason) => websocket().kick(checkTarget(target), code, reason),
224
159
  onPresence: (listener) => {
225
160
  if (typeof listener !== 'function')
226
- throw new TypeError('Invalid presence listener');
227
- return websocket().onPresence((change) => change.tenant.startsWith(prefix)
228
- ? listener(Object.freeze({ ...change, tenant: change.tenant.slice(prefix.length) }))
229
- : undefined);
161
+ throw new AppError('INVALID_TARGET', 'Invalid presence listener');
162
+ return websocket().onPresence(listener);
230
163
  },
231
164
  publish: async (target, event, data) => {
232
165
  if (!streams)
233
- throw coded(`App ${app}: realtime publish needs @dokebi/sse`, 'REALTIME_UNAVAILABLE');
166
+ throw unavailable(app, 'realtime publish', 'sse');
234
167
  const checked = checkTarget(target);
235
- return streams.publish({
236
- ...(checked.tenant === undefined
237
- ? { tenantPrefix: prefix }
238
- : { tenant: prefix + checked.tenant }),
239
- ...(checked.room === undefined ? {} : { room: checked.room }),
240
- ...(checked.member === undefined ? {} : { member: checked.member }),
241
- }, event, data);
168
+ streamHandle ??= streams.handle(namespace);
169
+ return streamHandle.publish(checked, event, data);
242
170
  },
243
171
  });
244
172
  }
@@ -258,7 +186,7 @@ function requirement(value) {
258
186
  if (value === null ||
259
187
  typeof value !== 'object' ||
260
188
  typeof value.name !== 'string')
261
- throw new TypeError('Invalid app requirement');
189
+ throw new AppError('INVALID_DEFINITION', 'Invalid app requirement');
262
190
  return value;
263
191
  }
264
192
  /** A host without its port, lower case; IPv6 literals keep their brackets. */
@@ -273,6 +201,58 @@ export function withoutPort(host) {
273
201
  export function hostOf(request) {
274
202
  return withoutPort(String(request.headers.host ?? ''));
275
203
  }
204
+ /** The host entry of a request, kept on the raw request: the host is worked out once. */
205
+ const HOST_ENTRY = Symbol('dokebi.app.host');
206
+ /** Hosts that are not configured (answered by `unknownDomain` or refused) kept at most. */
207
+ const UNKNOWN_HOSTS = 256;
208
+ /**
209
+ * The page an app handler receives. Everything but `view` is the host's, shared by every
210
+ * request; `view` is bound to the request (shared data) and built only when a handler reads it.
211
+ */
212
+ class RequestPage {
213
+ app;
214
+ module;
215
+ base;
216
+ inertia;
217
+ sealed;
218
+ #request;
219
+ #view;
220
+ #built;
221
+ constructor(info, sealed, module, base, inertia, request, view) {
222
+ this.app = info;
223
+ this.module = module;
224
+ this.base = base;
225
+ this.inertia = inertia;
226
+ this.sealed = sealed;
227
+ this.#request = request;
228
+ this.#view = view;
229
+ Object.freeze(this);
230
+ }
231
+ get view() {
232
+ this.#built ??= this.#view(this.#request, this.app, this.sealed);
233
+ return this.#built;
234
+ }
235
+ }
236
+ /** The contributions of one point by name (`ejs`, `inertia`) or kind (`websocket`, `sse`). */
237
+ function byKey(context, point, key) {
238
+ const result = new Map();
239
+ for (const { value } of context.collect(point)) {
240
+ const name = value[key];
241
+ // The first contribution of a name wins (setup order); a later one is reported.
242
+ if (typeof name !== 'string')
243
+ continue;
244
+ if (result.has(name)) {
245
+ context.logger.log('warn', 'Second contribution of the same name ignored', {
246
+ code: 'DUPLICATE_CONTRIBUTION',
247
+ point: point.name,
248
+ name,
249
+ });
250
+ continue;
251
+ }
252
+ result.set(name, value);
253
+ }
254
+ return result;
255
+ }
276
256
  class AppRuntime {
277
257
  options;
278
258
  apps;
@@ -287,12 +267,38 @@ class AppRuntime {
287
267
  #declaredFor(name) {
288
268
  const dependency = this.#declared.get(name);
289
269
  if (!dependency)
290
- throw new Error(`Plugin ${name} is not declared by dokebi-app`);
270
+ throw new AppError('NOT_REQUIRED', `Plugin ${name} is not declared by dokebi-app`);
291
271
  return dependency;
292
272
  }
293
- resolve(host) {
273
+ #hosts = new Map();
274
+ #unknownHosts = 0;
275
+ /** AppInfo and seal flag of a host (without port), cached per host. */
276
+ entry(host) {
277
+ const known = this.#hosts.get(host);
278
+ if (known !== undefined)
279
+ return known;
294
280
  const target = this.#target(host);
295
- return target ? { name: target.app, template: target.template, domain: host } : undefined;
281
+ const entry = target
282
+ ? Object.freeze({
283
+ info: Object.freeze({ name: target.app, template: target.template, domain: host }),
284
+ sealed: target.seal === true,
285
+ })
286
+ : null;
287
+ // Configured hosts are few; any other Host header is client input, so that part is bounded.
288
+ if (!this.options.domains.has(host)) {
289
+ if (this.#unknownHosts >= UNKNOWN_HOSTS) {
290
+ for (const name of this.#hosts.keys())
291
+ if (!this.options.domains.has(name))
292
+ this.#hosts.delete(name);
293
+ this.#unknownHosts = 0;
294
+ }
295
+ this.#unknownHosts++;
296
+ }
297
+ this.#hosts.set(host, entry);
298
+ return entry;
299
+ }
300
+ resolve(host) {
301
+ return this.entry(host)?.info;
296
302
  }
297
303
  #target(host) {
298
304
  const domain = this.options.domains.has(host) ? host : this.options.unknownDomain;
@@ -300,17 +306,22 @@ class AppRuntime {
300
306
  }
301
307
  /** The host's `seal` flag (an unknown host answered by `unknownDomain` takes that entry's). */
302
308
  sealed(host) {
303
- return this.#target(host)?.seal === true;
309
+ return this.entry(host)?.sealed === true;
304
310
  }
305
311
  async setup(context) {
306
312
  for (const [host, target] of this.options.domains)
307
313
  if (!this.apps.has(target.app))
308
- throw new Error(`Domain ${host} points to app ${target.app}, which is not registered`);
314
+ throw new AppError('UNKNOWN_APP', `Domain ${host} points to app ${target.app}, which is not registered`);
309
315
  for (const app of this.options.apps.keys())
310
316
  if (!this.apps.has(app))
311
- throw coded(`dokebi-app apps.${app} names an app that is not defined (defined: ${[...this.apps.keys()].join(', ') || 'none'})`, 'UNKNOWN_APP');
317
+ throw new AppError('UNKNOWN_APP', `dokebi-app apps.${app} names an app that is not defined (defined: ${[...this.apps.keys()].join(', ') || 'none'})`);
312
318
  const http = context.getDependency(web);
313
319
  const logger = context.logger;
320
+ // D-0063 §5: view engines and realtime transports by name, whoever contributes them.
321
+ const engines = byKey(context, viewEngines, 'name');
322
+ const transports = byKey(context, realtime, 'kind');
323
+ const sockets = transports.get('websocket');
324
+ const streams = transports.get('sse');
314
325
  const sealedDomains = [...this.options.domains]
315
326
  .filter(([, target]) => target.seal)
316
327
  .map(([domain]) => domain);
@@ -322,16 +333,48 @@ class AppRuntime {
322
333
  count: this.options.domains.size,
323
334
  unknownDomain: this.options.unknownDomain ?? 'reject',
324
335
  sealed: sealedDomains.length,
336
+ viewEngines: [...engines.keys()],
337
+ transports: [...transports.keys()],
325
338
  });
326
339
  // Fail closed (D-0059 §4): a sealed host without the seal plugin would talk plain text.
327
340
  if (sealedDomains.length && context.getOptionalDependency(seal) === undefined)
328
- throw Object.assign(new Error(`Domains ${sealedDomains.slice(0, 8).join(', ')} set seal: true; register the dokebi-seal plugin`), { code: 'SEAL_PROVIDER_MISSING' });
341
+ throw new AppError('SEAL_PROVIDER_MISSING', `Domains ${sealedDomains.slice(0, 8).join(', ')} set seal: true; register the dokebi-seal plugin`);
342
+ /** The engine an app needs, or VIEW_ENGINE_MISSING naming the package that offers it. */
343
+ const engine = (name, app) => {
344
+ const found = engines.get(name);
345
+ if (!found)
346
+ throw new AppError('VIEW_ENGINE_MISSING', `App ${app} uses the ${name} view engine; add ${PROVIDERS[name]}`, { fix: `npx dokebi add ${PROVIDERS[name]} (it contributes the ${name} view engine).` });
347
+ return found;
348
+ };
329
349
  // Behind a trusted proxy (dokebi-web trustProxy) the forwarded host picks the app.
330
350
  const host = (request) => withoutPort(http.requestHost(request));
351
+ /** The host entry of a raw or Fastify request, worked out once per request. */
352
+ // Raw Host header → entry, so the usual request skips trimming, lower-casing and the port
353
+ // cut. Only when no X-Forwarded-Host is present (with one, trustProxy decides). Client input:
354
+ // bounded like the unknown hosts.
355
+ const byHeader = new Map();
356
+ const hostEntry = (request) => {
357
+ const raw = (request.raw ?? request);
358
+ const known = raw[HOST_ENTRY];
359
+ if (known !== undefined)
360
+ return known;
361
+ const header = raw.headers['x-forwarded-host'] === undefined ? raw.headers.host : undefined;
362
+ let entry = typeof header === 'string' ? byHeader.get(header) : undefined;
363
+ if (entry === undefined) {
364
+ entry = this.entry(host(request));
365
+ if (typeof header === 'string') {
366
+ if (byHeader.size >= UNKNOWN_HOSTS)
367
+ byHeader.clear();
368
+ byHeader.set(header, entry);
369
+ }
370
+ }
371
+ raw[HOST_ENTRY] = entry;
372
+ return entry;
373
+ };
331
374
  // D-0062: every HTTP request of a sealed host is sealed by dokebi-web (JSON bodies both ways,
332
375
  // the Inertia page, SSE data), except routes with seal: false and dokebi-web sealExclude.
333
376
  if (sealedDomains.length)
334
- http.sealRequests((request) => this.sealed(host(request)));
377
+ http.sealRequests((request) => hostEntry(request)?.sealed === true);
335
378
  http.constraint({
336
379
  name: APP_CONSTRAINT,
337
380
  storage() {
@@ -344,21 +387,19 @@ class AppRuntime {
344
387
  };
345
388
  },
346
389
  deriveConstraint: (request) => {
347
- const requested = host(request);
348
- const name = this.resolve(requested)?.name;
390
+ const name = hostEntry(request)?.info.name;
349
391
  // Per request: only built when debug is on (D-0047).
350
392
  if (name === undefined && logger.isEnabled('debug'))
351
- logger.log('debug', 'App domain not configured', { host: requested.slice(0, 253) });
393
+ logger.log('debug', 'App domain not configured', { host: host(request).slice(0, 253) });
352
394
  return name;
353
395
  },
354
396
  // Requests of a known app may still reach shared (unconstrained) routes.
355
397
  mustMatchWhenDerived: false,
356
398
  });
357
- const pages = context.getOptionalDependency(inertia);
358
- const sockets = context.getOptionalDependency(websocket);
359
- const streams = context.getOptionalDependency(sse);
360
- /** Every route of a sealed host seals; other hosts keep what the route itself says. */
361
- const sealFor = (own) => (request) => this.sealed(host(request)) || own === true || (typeof own === 'function' && own(request));
399
+ /** The shared EJS renderer (the engine's own), loaded once on first need. */
400
+ let ejsRoot;
401
+ /** Each app's error answer (D-0074), by app name. */
402
+ const answers = new Map();
362
403
  for (const [name, definition] of this.apps) {
363
404
  context.signal.throwIfAborted();
364
405
  const begin = performance.now();
@@ -387,7 +428,7 @@ class AppRuntime {
387
428
  return undefined;
388
429
  };
389
430
  /** `identity` in the chosen namespace: tenant prefixed, `namespace` removed. */
390
- const scoped = (identity, kind, path) => {
431
+ const scoped = (kind, path) => (identity) => {
391
432
  const chosen = namespaceOf(identity.namespace, kind, path);
392
433
  if (chosen === undefined)
393
434
  return undefined;
@@ -409,22 +450,22 @@ class AppRuntime {
409
450
  signal: context.signal,
410
451
  get: (plugin) => {
411
452
  if (!allowed.has(plugin.metadata.name))
412
- throw new Error(`App ${name} does not list ${plugin.metadata.name} in requires`);
453
+ throw new AppError('NOT_REQUIRED', `App ${name} does not list ${plugin.metadata.name} in requires`);
413
454
  return context.get(plugin);
414
455
  },
415
456
  getDependency: (dependency) => {
416
457
  if (!allowed.has(dependency.name))
417
- throw new Error(`App ${name} does not list ${dependency.name} in requires`);
458
+ throw new AppError('NOT_REQUIRED', `App ${name} does not list ${dependency.name} in requires`);
418
459
  return context.getDependency(this.#declaredFor(dependency.name));
419
460
  },
420
461
  getOptionalDependency: (dependency) => {
421
462
  if (!allowed.has(dependency.name))
422
- throw new Error(`App ${name} does not list ${dependency.name} in requires`);
463
+ throw new AppError('NOT_REQUIRED', `App ${name} does not list ${dependency.name} in requires`);
423
464
  return context.getOptionalDependency(this.#declaredFor(dependency.name));
424
465
  },
425
466
  controller: (token) => {
426
467
  if (!controllers)
427
- throw new Error(`App ${name} has no controllers yet`);
468
+ throw new AppError('NOT_READY', `App ${name} has no controllers yet`);
428
469
  return controllers.get(token);
429
470
  },
430
471
  defer: (cleanup) => context.defer(cleanup),
@@ -433,13 +474,13 @@ class AppRuntime {
433
474
  if (handle)
434
475
  return handle;
435
476
  if (!namespaces.includes(namespace))
436
- throw coded(`App ${name} may use realtime namespaces ${namespaces.join(', ')}, not ${String(namespace).slice(0, 64)}`, 'NAMESPACE_FORBIDDEN');
477
+ throw new AppError('NAMESPACE_FORBIDDEN', `App ${name} may use realtime namespaces ${namespaces.join(', ')}, not ${String(namespace).slice(0, 64)}`);
437
478
  handle = realtimeHandle(name, namespace, sockets, streams);
438
479
  handles.set(namespace, handle);
439
480
  logger.log('debug', 'App realtime handle created', {
440
481
  app: name,
441
482
  namespace,
442
- websocket: typeof sockets?.list === 'function',
483
+ websocket: sockets !== undefined,
443
484
  sse: streams !== undefined,
444
485
  });
445
486
  return handle;
@@ -459,24 +500,26 @@ class AppRuntime {
459
500
  });
460
501
  controllers = await createControllers(factoryContext, definition.controllers ?? []);
461
502
  const templates = new Set();
462
- let templateApi;
503
+ const hasModuleViews = Object.values(definition.modules ?? {}).some((module) => mountOf(module)?.views);
463
504
  if (definition.views) {
464
- templateApi = context.getDependency(ejs);
465
- await templateApi.addDirectory(definition.views, name);
505
+ // The app's folder is loaded as `<app>/…`; the engine's root renderer serves every scope.
506
+ ejsRoot = await engine('ejs', name).scope({
507
+ directory: definition.views,
508
+ prefix: name,
509
+ });
466
510
  await this.#checkTemplates(name, definition.views, templates);
467
511
  }
512
+ else if (hasModuleViews && !ejsRoot)
513
+ ejsRoot = await engine('ejs', name).scope({});
468
514
  let inertiaApi;
469
515
  if (definition.inertia) {
470
- if (!pages)
471
- throw new Error(`App ${name} uses Inertia; add @dokebi/template-inertia`);
472
- inertiaApi = await pages.scope({
516
+ inertiaApi = await engine('inertia', name).scope({
473
517
  ...definition.inertia,
474
518
  // SSR would write the props of a sealed host as plain HTML: refused (D-0062).
475
519
  ...(appSealed ? { sealed: true } : {}),
476
520
  shared: (request) => {
477
- const requested = host(request);
478
- const info = this.resolve(requested);
479
- return { app: info ? { ...info } : null, sealed: this.sealed(requested) };
521
+ const entry = hostEntry(request);
522
+ return { app: entry ? { ...entry.info } : null, sealed: entry?.sealed === true };
480
523
  },
481
524
  });
482
525
  }
@@ -510,50 +553,52 @@ class AppRuntime {
510
553
  render: async (name, own, options) => view.render(name, await data(own), options),
511
554
  reply: async (reply, name, own, options) => view.reply(reply, name, await data(own), options),
512
555
  scope: (prefixes) => view.scope(prefixes),
556
+ has: (template) => view.has(template),
513
557
  });
514
558
  };
515
559
  const pageFor = (module) => {
516
560
  const scopes = new Map();
517
561
  const hasViews = Boolean(definition.views || module?.views);
518
- return (request) => {
519
- const requested = host(request);
520
- const info = this.resolve(requested) ?? {
521
- name,
522
- template: DEFAULT_TEMPLATE,
523
- domain: requested,
524
- };
525
- const sealed = this.sealed(requested);
562
+ // Built on the first `page.view` read of a request (D-0068): most JSON routes never do.
563
+ const viewOf = (request, info, sealed) => {
526
564
  let view = scopes.get(info.template);
527
565
  if (!view) {
528
- templateApi ??= hasViews ? context.getDependency(ejs) : undefined;
529
566
  view =
530
- templateApi && hasViews
531
- ? templateApi.scope(chain(info.template, module))
567
+ ejsRoot && hasViews
568
+ ? ejsRoot.scope(chain(info.template, module))
532
569
  : missingViews(name);
533
570
  scopes.set(info.template, view);
534
571
  }
535
- return Object.freeze({
536
- app: info,
537
- module: module?.name,
538
- base: module?.base ?? '',
539
- view: withShared(view, request, info, sealed),
540
- inertia: inertiaApi,
541
- sealed,
542
- });
572
+ return withShared(view, request, info, sealed);
573
+ };
574
+ const moduleName = module?.name;
575
+ const base = module?.base ?? '';
576
+ return (request) => {
577
+ const entry = hostEntry(request);
578
+ // An app route is only reached through its own host (route constraint); the fallback
579
+ // covers a host whose entry went away in between.
580
+ const info = entry?.info ?? { name, template: DEFAULT_TEMPLATE, domain: host(request) };
581
+ return new RequestPage(info, entry?.sealed === true, moduleName, base, inertiaApi, request, viewOf);
543
582
  };
544
583
  };
545
584
  const routerFor = (page, base) => {
546
585
  const add = (options) => {
547
586
  const { handler, ...rest } = options;
548
587
  routeCount++;
549
- http.route({
588
+ const url = joinPath(base, rest.url);
589
+ const register = (path) => http.route({
550
590
  ...rest,
551
- url: joinPath(base, rest.url),
591
+ url: path,
552
592
  constraints: { [APP_CONSTRAINT]: name },
553
593
  handler(request, reply) {
554
594
  return handler(request, reply, page(request));
555
595
  },
556
596
  });
597
+ register(url);
598
+ // The root of a prefixed mount answers `/board/` as well as `/board`: links and form
599
+ // actions written with a trailing slash would otherwise be 404 (AI-M03).
600
+ if (base && url === base)
601
+ register(base + '/');
557
602
  };
558
603
  const method = (verb) => (url, handler, options = {}) => add({ ...options, method: verb, url, handler });
559
604
  return Object.freeze({
@@ -565,47 +610,78 @@ class AppRuntime {
565
610
  delete: method('DELETE'),
566
611
  });
567
612
  };
613
+ /** The scope of one realtime route: the full path, the app constraint and tenant rule. */
614
+ const scopeOf = (path, kind) => Object.freeze({
615
+ path,
616
+ constraints: Object.freeze({ [APP_CONSTRAINT]: name }),
617
+ identity: scoped(kind, path),
618
+ // The request's host decides (D-0059 §4); only when a host of this app seals.
619
+ ...(appSealed
620
+ ? { seal: (request) => hostEntry(request)?.sealed === true }
621
+ : {}),
622
+ });
568
623
  const mountSockets = (routes, base, owner) => {
569
624
  for (const route of routes) {
570
625
  if (!sockets)
571
- throw new Error(`${owner} has sockets; add @dokebi/websocket`);
572
- // An older @dokebi/websocket ignores route.seal: refuse rather than run plain text.
573
- if (appSealed && sockets.sealing !== true)
574
- throw Object.assign(new Error(`${owner} has sealed domains; use @dokebi/websocket 0.3 or later`), { code: 'SEAL_PROVIDER_MISSING' });
626
+ throw new AppError('REALTIME_UNAVAILABLE', `${owner} has sockets; add @dokebi/websocket`);
575
627
  socketCount++;
576
- const path = joinPath(base, route.path);
577
- sockets.route({
578
- ...route,
579
- path,
580
- constraints: { ...(route.constraints ?? {}), [APP_CONSTRAINT]: name },
581
- // The request's host decides (D-0059 §4); set only when a host of this app seals.
582
- ...(appSealed ? { seal: sealFor(route.seal) } : {}),
583
- // Each namespace is its own tenant space in the hub (D-0061): apps that share a
584
- // namespace share presence and broadcasts; the app's own name is the default.
585
- authenticate: async (request) => {
586
- const identity = await route.authenticate(request);
587
- return identity ? scoped(identity, 'socket', path) : undefined;
588
- },
589
- });
628
+ sockets.mount(route, scopeOf(joinPath(base, route.path), 'socket'));
590
629
  }
591
630
  };
592
631
  const mountEvents = (routes, base, owner) => {
593
632
  for (const route of routes) {
594
633
  if (!streams)
595
- throw new Error(`${owner} has event streams; add @dokebi/sse`);
634
+ throw new AppError('REALTIME_UNAVAILABLE', `${owner} has event streams; add @dokebi/sse`);
596
635
  eventCount++;
597
- const path = joinPath(base, route.path);
598
- streams.route({
599
- ...route,
600
- path,
601
- constraints: { ...(route.constraints ?? {}), [APP_CONSTRAINT]: name },
602
- authenticate: async (request) => {
603
- const identity = await route.authenticate(request);
604
- return identity ? scoped(identity, 'stream', path) : undefined;
605
- },
606
- });
636
+ streams.mount(route, scopeOf(joinPath(base, route.path), 'stream'));
607
637
  }
608
638
  };
639
+ // D-0074 §3-4: the error answers of this app's hosts. Inertia first (the validation
640
+ // redirect, the app's error page component), then for an HTML answer the app's error view:
641
+ // `errors/<status>` → `errors/error` in <app>/<template> → <app>/default → shared views.
642
+ const errorViews = new Map();
643
+ answers.set(name, async (response, entry) => {
644
+ if (inertiaApi && typeof inertiaApi.answerError === 'function') {
645
+ if (await inertiaApi.answerError(response))
646
+ return true;
647
+ }
648
+ if (response.format !== 'html' || !ejsRoot)
649
+ return false;
650
+ const { info, sealed } = entry;
651
+ let view = errorViews.get(info.template);
652
+ if (!view) {
653
+ view = ejsRoot.scope(appChain(info.template));
654
+ errorViews.set(info.template, view);
655
+ }
656
+ const { status, body, request, reply, production, error } = response;
657
+ const page = view.has(`errors/${status}`)
658
+ ? `errors/${status}`
659
+ : view.has('errors/error')
660
+ ? 'errors/error'
661
+ : undefined;
662
+ if (!page)
663
+ return false;
664
+ const fields = Array.isArray(body.fields) ? body.fields : [];
665
+ await withShared(view, request, info, sealed).reply(reply, page, {
666
+ status,
667
+ title: `${status} ${STATUS_CODES[status] ?? 'Error'}`,
668
+ error: body.error,
669
+ message: typeof body.message === 'string' ? body.message : null,
670
+ hint: typeof body.hint === 'string' ? body.hint : null,
671
+ fields,
672
+ // Development only (dokebi-web already cut `fix` from a production body).
673
+ fix: typeof body.fix === 'string' ? body.fix : null,
674
+ stack: !production && status >= 500 && error instanceof Error ? (error.stack ?? null) : null,
675
+ });
676
+ if (logger.isEnabled('debug'))
677
+ logger.log('debug', 'App error view rendered', {
678
+ app: name,
679
+ template: info.template,
680
+ view: page,
681
+ status,
682
+ });
683
+ return true;
684
+ });
609
685
  await definition.setup?.(appContext);
610
686
  await definition.routes?.(routerFor(pageFor(), ''), appContext);
611
687
  mountSockets((await definition.sockets?.(appContext)) ?? [], '', `App ${name}`);
@@ -639,9 +715,16 @@ class AppRuntime {
639
715
  ms: Math.round(performance.now() - begin),
640
716
  });
641
717
  }
718
+ // D-0074: errors on an app's hosts (unknown routes included) are answered by that app.
719
+ // Added after the template plugins' responders, so dokebi-web asks this one first.
720
+ http.errorResponder((response) => {
721
+ const entry = hostEntry(response.request);
722
+ const answer = entry ? answers.get(entry.info.name) : undefined;
723
+ return entry && answer ? answer(response, entry) : false;
724
+ });
642
725
  return Object.freeze({
643
726
  names: Object.freeze([...this.apps.keys()]),
644
- resolve: (request) => this.resolve(host(request)),
727
+ resolve: (request) => hostEntry(request)?.info,
645
728
  });
646
729
  }
647
730
  /** Every template a domain selects must exist as a folder, and `default` always must. */
@@ -659,7 +742,7 @@ class AppRuntime {
659
742
  return undefined;
660
743
  });
661
744
  if (!info?.isDirectory())
662
- throw new Error(`App ${name} has no views/${template}/ folder`, failure === undefined ? undefined : { cause: failure });
745
+ throw new AppError('VIEWS_MISSING', `App ${name} has no views/${template}/ folder`, failure === undefined ? {} : { cause: failure });
663
746
  found.add(template);
664
747
  }
665
748
  }
@@ -690,23 +773,27 @@ class AppRuntime {
690
773
  }
691
774
  function missingViews(name) {
692
775
  const fail = async () => {
693
- throw new Error(`App ${name} has no views folder`);
776
+ throw new AppError('VIEWS_MISSING', `App ${name} has no views folder`);
694
777
  };
695
- const api = Object.freeze({ render: fail, reply: fail, scope: () => api });
778
+ const api = Object.freeze({
779
+ render: fail,
780
+ reply: fail,
781
+ scope: () => api,
782
+ has: () => false,
783
+ });
696
784
  return api;
697
785
  }
698
786
  export const createPlugin = definePlugin({
699
787
  name: 'dokebi-app',
700
- version: '0.2.0',
701
- core: '^0.2.0',
702
- options: parseOptions,
788
+ version: '0.4.0',
789
+ core: '^0.4.0',
790
+ options: declaration,
703
791
  entry: parseEntry,
792
+ // Template and realtime plugins are found through these points, not by name (D-0063 §5).
793
+ collects: [viewEngines, realtime],
704
794
  dependencies: ({ entry }) => {
705
795
  const apps = [...(entry ?? new Map()).values()];
706
- const list = [web];
707
- if (apps.some((app) => app.views || Object.values(app.modules ?? {}).some((module) => mountOf(module)?.views)))
708
- list.push(ejs);
709
- list.push(inertia, websocket, seal, sse);
796
+ const list = [web, seal];
710
797
  for (const app of apps)
711
798
  for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})]) {
712
799
  const dependency = requirement(item);
@@ -715,5 +802,5 @@ export const createPlugin = definePlugin({
715
802
  }
716
803
  return list;
717
804
  },
718
- instance: ({ options, entry, dependencies }) => new AppRuntime(options, entry ?? new Map(), dependencies),
805
+ instance: ({ options, entry, dependencies }) => new AppRuntime(settings(options), entry ?? new Map(), dependencies),
719
806
  });