@dokebi/app 0.2.0 → 0.4.1
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 +170 -100
- package/README.md +75 -73
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +21 -0
- package/dist/index.d.ts +128 -26
- package/dist/index.js +427 -232
- package/dist/options.d.ts +16 -0
- package/dist/options.js +55 -0
- package/options.schema.json +26 -16
- package/package.json +54 -42
- package/templates/app/views/default/errors/404.ejs +7 -0
- package/templates/app/views/default/errors/error.ejs +17 -0
- package/templates/app-inertia/app.ts +3 -0
- package/templates/app-inertia/views/app.js +1 -1
- package/templates/app-inertia/views/default/Pages/Error.vue +12 -0
- package/templates/app-inertia-ssr/app.ts +3 -0
- package/templates/app-inertia-ssr/views/ssr.js +1 -1
package/dist/index.js
CHANGED
|
@@ -3,9 +3,16 @@ import { fileURLToPath } from 'node:url';
|
|
|
3
3
|
import { types } from 'node:util';
|
|
4
4
|
import { createControllers, } from '@dokebi/controller';
|
|
5
5
|
import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
|
|
6
|
+
import { formBackTarget, formFieldErrors, formOldInput, isFormSubmission, } from '@dokebi/web';
|
|
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
|
|
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
|
|
56
|
+
throw invalidDefinition('Unknown app definition field: ' + key);
|
|
47
57
|
if (definition.requires !== undefined && !Array.isArray(definition.requires))
|
|
48
|
-
throw
|
|
58
|
+
throw invalidDefinition('App requires must be an array');
|
|
49
59
|
if (definition.controllers !== undefined && !Array.isArray(definition.controllers))
|
|
50
|
-
throw
|
|
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
|
|
63
|
+
throw invalidDefinition('App views must be a file: URL');
|
|
54
64
|
if (definition.modules !== undefined) {
|
|
55
65
|
if (!plain(definition.modules))
|
|
56
|
-
throw
|
|
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
|
|
69
|
+
throw invalidDefinition('Invalid module prefix: ' + prefix);
|
|
60
70
|
if (!mountOf(plugin))
|
|
61
|
-
throw
|
|
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
|
|
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,68 @@ function plain(value) {
|
|
|
108
85
|
!types.isProxy(value) &&
|
|
109
86
|
[Object.prototype, null].includes(Object.getPrototypeOf(value)));
|
|
110
87
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
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:
|
|
139
|
-
unknownDomain: unknownDomain === 'reject' ? undefined : unknownDomain,
|
|
140
|
-
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
|
|
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
|
|
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
|
}
|
|
112
|
+
/**
|
|
113
|
+
* dokebi-web 0.4.1 or later: the HTML form validation redirect uses its form helpers (D-0074
|
|
114
|
+
* addendum 1). A local descriptor instead of '@dokebi/web/dependency' (whose range stays ^0.4.0
|
|
115
|
+
* for the plugins that need nothing newer).
|
|
116
|
+
*/
|
|
156
117
|
const web = providerDependency({
|
|
157
118
|
name: 'dokebi-web',
|
|
158
|
-
version: '^0.
|
|
119
|
+
version: '^0.4.1',
|
|
159
120
|
packageName: '@dokebi/web',
|
|
160
121
|
load: () => import('@dokebi/web'),
|
|
161
122
|
});
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
}
|
|
123
|
+
const session = optionalDependency({ name: 'dokebi-session', version: '^0.4.0' });
|
|
124
|
+
const plainRecord = (value) => value !== null &&
|
|
125
|
+
typeof value === 'object' &&
|
|
126
|
+
!Array.isArray(value) &&
|
|
127
|
+
[Object.prototype, null].includes(Object.getPrototypeOf(value));
|
|
128
|
+
/** Splits a taken flash into the view data; fresh objects for every request. */
|
|
129
|
+
function viewFlash(taken) {
|
|
130
|
+
const { errors, old, ...rest } = taken ?? {};
|
|
131
|
+
return {
|
|
132
|
+
errors: plainRecord(errors) ? { ...errors } : {},
|
|
133
|
+
old: plainRecord(old) ? { ...old } : {},
|
|
134
|
+
flash: rest,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
176
137
|
/**
|
|
177
138
|
* 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
|
|
179
|
-
* seal slot of @dokebi/web).
|
|
139
|
+
* (it serves `/dokebi/seal/*`, seals the sockets through the websocket transport and fills the
|
|
140
|
+
* HTTP seal slot of @dokebi/web).
|
|
180
141
|
*/
|
|
181
|
-
const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.
|
|
182
|
-
/**
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
142
|
+
const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.4.0' });
|
|
143
|
+
/** Packages that offer an engine or transport, for the fix of a missing one. */
|
|
144
|
+
const PROVIDERS = {
|
|
145
|
+
ejs: '@dokebi/template-ejs',
|
|
146
|
+
inertia: '@dokebi/template-inertia',
|
|
147
|
+
websocket: '@dokebi/websocket',
|
|
148
|
+
sse: '@dokebi/sse',
|
|
149
|
+
};
|
|
187
150
|
/** A realtime target string: 1 to 256 characters. */
|
|
188
151
|
function targetText(value) {
|
|
189
152
|
return typeof value === 'string' && value.length > 0 && value.length <= 256;
|
|
@@ -195,50 +158,40 @@ function checkTarget(target) {
|
|
|
195
158
|
(value.tenant !== undefined && !targetText(value.tenant)) ||
|
|
196
159
|
(value.member !== undefined && !targetText(value.member)) ||
|
|
197
160
|
(value.room !== undefined && !targetText(value.room)))
|
|
198
|
-
throw
|
|
161
|
+
throw new AppError('INVALID_TARGET', 'A realtime target is { tenant?, member?, room? } with strings of 1 to 256 characters');
|
|
199
162
|
return value;
|
|
200
163
|
}
|
|
201
|
-
|
|
164
|
+
function unavailable(app, what, kind) {
|
|
165
|
+
return new AppError('REALTIME_UNAVAILABLE', `App ${app}: ${what} needs ${PROVIDERS[kind]}`, {
|
|
166
|
+
fix: `npx dokebi add ${PROVIDERS[kind]} (it contributes the ${kind} transport to dokebi-web:realtime).`,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/** The handle of one namespace (D-0061) over the transports' namespace handles. */
|
|
202
170
|
function realtimeHandle(app, namespace, sockets, streams) {
|
|
203
|
-
|
|
171
|
+
let socketHandle;
|
|
172
|
+
let streamHandle;
|
|
204
173
|
const websocket = () => {
|
|
205
|
-
if (!sockets
|
|
206
|
-
throw
|
|
207
|
-
|
|
174
|
+
if (!sockets)
|
|
175
|
+
throw unavailable(app, 'realtime sockets', 'websocket');
|
|
176
|
+
socketHandle ??= sockets.handle(namespace);
|
|
177
|
+
return socketHandle;
|
|
208
178
|
};
|
|
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
179
|
return Object.freeze({
|
|
217
180
|
namespace,
|
|
218
|
-
list: async (target = {}) =>
|
|
219
|
-
|
|
220
|
-
|
|
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),
|
|
181
|
+
list: async (target = {}) => websocket().list(checkTarget(target)),
|
|
182
|
+
send: async (target, type, data) => websocket().send(checkTarget(target), type, data),
|
|
183
|
+
kick: async (target, code, reason) => websocket().kick(checkTarget(target), code, reason),
|
|
224
184
|
onPresence: (listener) => {
|
|
225
185
|
if (typeof listener !== 'function')
|
|
226
|
-
throw new
|
|
227
|
-
return websocket().onPresence(
|
|
228
|
-
? listener(Object.freeze({ ...change, tenant: change.tenant.slice(prefix.length) }))
|
|
229
|
-
: undefined);
|
|
186
|
+
throw new AppError('INVALID_TARGET', 'Invalid presence listener');
|
|
187
|
+
return websocket().onPresence(listener);
|
|
230
188
|
},
|
|
231
189
|
publish: async (target, event, data) => {
|
|
232
190
|
if (!streams)
|
|
233
|
-
throw
|
|
191
|
+
throw unavailable(app, 'realtime publish', 'sse');
|
|
234
192
|
const checked = checkTarget(target);
|
|
235
|
-
|
|
236
|
-
|
|
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);
|
|
193
|
+
streamHandle ??= streams.handle(namespace);
|
|
194
|
+
return streamHandle.publish(checked, event, data);
|
|
242
195
|
},
|
|
243
196
|
});
|
|
244
197
|
}
|
|
@@ -258,7 +211,7 @@ function requirement(value) {
|
|
|
258
211
|
if (value === null ||
|
|
259
212
|
typeof value !== 'object' ||
|
|
260
213
|
typeof value.name !== 'string')
|
|
261
|
-
throw new
|
|
214
|
+
throw new AppError('INVALID_DEFINITION', 'Invalid app requirement');
|
|
262
215
|
return value;
|
|
263
216
|
}
|
|
264
217
|
/** A host without its port, lower case; IPv6 literals keep their brackets. */
|
|
@@ -273,6 +226,58 @@ export function withoutPort(host) {
|
|
|
273
226
|
export function hostOf(request) {
|
|
274
227
|
return withoutPort(String(request.headers.host ?? ''));
|
|
275
228
|
}
|
|
229
|
+
/** The host entry of a request, kept on the raw request: the host is worked out once. */
|
|
230
|
+
const HOST_ENTRY = Symbol('dokebi.app.host');
|
|
231
|
+
/** Hosts that are not configured (answered by `unknownDomain` or refused) kept at most. */
|
|
232
|
+
const UNKNOWN_HOSTS = 256;
|
|
233
|
+
/**
|
|
234
|
+
* The page an app handler receives. Everything but `view` is the host's, shared by every
|
|
235
|
+
* request; `view` is bound to the request (shared data) and built only when a handler reads it.
|
|
236
|
+
*/
|
|
237
|
+
class RequestPage {
|
|
238
|
+
app;
|
|
239
|
+
module;
|
|
240
|
+
base;
|
|
241
|
+
inertia;
|
|
242
|
+
sealed;
|
|
243
|
+
#request;
|
|
244
|
+
#view;
|
|
245
|
+
#built;
|
|
246
|
+
constructor(info, sealed, module, base, inertia, request, view) {
|
|
247
|
+
this.app = info;
|
|
248
|
+
this.module = module;
|
|
249
|
+
this.base = base;
|
|
250
|
+
this.inertia = inertia;
|
|
251
|
+
this.sealed = sealed;
|
|
252
|
+
this.#request = request;
|
|
253
|
+
this.#view = view;
|
|
254
|
+
Object.freeze(this);
|
|
255
|
+
}
|
|
256
|
+
get view() {
|
|
257
|
+
this.#built ??= this.#view(this.#request, this.app, this.sealed);
|
|
258
|
+
return this.#built;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/** The contributions of one point by name (`ejs`, `inertia`) or kind (`websocket`, `sse`). */
|
|
262
|
+
function byKey(context, point, key) {
|
|
263
|
+
const result = new Map();
|
|
264
|
+
for (const { value } of context.collect(point)) {
|
|
265
|
+
const name = value[key];
|
|
266
|
+
// The first contribution of a name wins (setup order); a later one is reported.
|
|
267
|
+
if (typeof name !== 'string')
|
|
268
|
+
continue;
|
|
269
|
+
if (result.has(name)) {
|
|
270
|
+
context.logger.log('warn', 'Second contribution of the same name ignored', {
|
|
271
|
+
code: 'DUPLICATE_CONTRIBUTION',
|
|
272
|
+
point: point.name,
|
|
273
|
+
name,
|
|
274
|
+
});
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
result.set(name, value);
|
|
278
|
+
}
|
|
279
|
+
return result;
|
|
280
|
+
}
|
|
276
281
|
class AppRuntime {
|
|
277
282
|
options;
|
|
278
283
|
apps;
|
|
@@ -287,12 +292,38 @@ class AppRuntime {
|
|
|
287
292
|
#declaredFor(name) {
|
|
288
293
|
const dependency = this.#declared.get(name);
|
|
289
294
|
if (!dependency)
|
|
290
|
-
throw new
|
|
295
|
+
throw new AppError('NOT_REQUIRED', `Plugin ${name} is not declared by dokebi-app`);
|
|
291
296
|
return dependency;
|
|
292
297
|
}
|
|
293
|
-
|
|
298
|
+
#hosts = new Map();
|
|
299
|
+
#unknownHosts = 0;
|
|
300
|
+
/** AppInfo and seal flag of a host (without port), cached per host. */
|
|
301
|
+
entry(host) {
|
|
302
|
+
const known = this.#hosts.get(host);
|
|
303
|
+
if (known !== undefined)
|
|
304
|
+
return known;
|
|
294
305
|
const target = this.#target(host);
|
|
295
|
-
|
|
306
|
+
const entry = target
|
|
307
|
+
? Object.freeze({
|
|
308
|
+
info: Object.freeze({ name: target.app, template: target.template, domain: host }),
|
|
309
|
+
sealed: target.seal === true,
|
|
310
|
+
})
|
|
311
|
+
: null;
|
|
312
|
+
// Configured hosts are few; any other Host header is client input, so that part is bounded.
|
|
313
|
+
if (!this.options.domains.has(host)) {
|
|
314
|
+
if (this.#unknownHosts >= UNKNOWN_HOSTS) {
|
|
315
|
+
for (const name of this.#hosts.keys())
|
|
316
|
+
if (!this.options.domains.has(name))
|
|
317
|
+
this.#hosts.delete(name);
|
|
318
|
+
this.#unknownHosts = 0;
|
|
319
|
+
}
|
|
320
|
+
this.#unknownHosts++;
|
|
321
|
+
}
|
|
322
|
+
this.#hosts.set(host, entry);
|
|
323
|
+
return entry;
|
|
324
|
+
}
|
|
325
|
+
resolve(host) {
|
|
326
|
+
return this.entry(host)?.info;
|
|
296
327
|
}
|
|
297
328
|
#target(host) {
|
|
298
329
|
const domain = this.options.domains.has(host) ? host : this.options.unknownDomain;
|
|
@@ -300,17 +331,79 @@ class AppRuntime {
|
|
|
300
331
|
}
|
|
301
332
|
/** The host's `seal` flag (an unknown host answered by `unknownDomain` takes that entry's). */
|
|
302
333
|
sealed(host) {
|
|
303
|
-
return this
|
|
334
|
+
return this.entry(host)?.sealed === true;
|
|
304
335
|
}
|
|
305
336
|
async setup(context) {
|
|
306
337
|
for (const [host, target] of this.options.domains)
|
|
307
338
|
if (!this.apps.has(target.app))
|
|
308
|
-
throw new
|
|
339
|
+
throw new AppError('UNKNOWN_APP', `Domain ${host} points to app ${target.app}, which is not registered`);
|
|
309
340
|
for (const app of this.options.apps.keys())
|
|
310
341
|
if (!this.apps.has(app))
|
|
311
|
-
throw
|
|
342
|
+
throw new AppError('UNKNOWN_APP', `dokebi-app apps.${app} names an app that is not defined (defined: ${[...this.apps.keys()].join(', ') || 'none'})`);
|
|
312
343
|
const http = context.getDependency(web);
|
|
313
344
|
const logger = context.logger;
|
|
345
|
+
const sessions = context.getOptionalDependency(this.#declaredFor(session.name));
|
|
346
|
+
// D-0074 addendum 1: the flash of a request, taken once (every render of the request shares
|
|
347
|
+
// it). Paths the session plugin excludes have no session (`request.session` is null).
|
|
348
|
+
const flashes = new WeakMap();
|
|
349
|
+
const sessionOf = (request) => sessions && request.session ? sessions.of(request) : undefined;
|
|
350
|
+
const flashOf = (request) => {
|
|
351
|
+
const current = sessionOf(request);
|
|
352
|
+
if (!current)
|
|
353
|
+
return undefined;
|
|
354
|
+
let taken = flashes.get(request);
|
|
355
|
+
if (!taken) {
|
|
356
|
+
taken = current.takeFlash().then(viewFlash);
|
|
357
|
+
flashes.set(request, taken);
|
|
358
|
+
}
|
|
359
|
+
return taken;
|
|
360
|
+
};
|
|
361
|
+
/**
|
|
362
|
+
* D-0074 addendum 1: an HTML form (urlencoded or multipart body) refused with 422
|
|
363
|
+
* VALIDATION_FAILED goes back to the page it came from — `errors` and `old` flashed in the
|
|
364
|
+
* session, 303 to the Referer of this host — when the request has a session and a way back.
|
|
365
|
+
* False otherwise: the error view (errors/422.ejs, errors/error.ejs) or dokebi-web's page.
|
|
366
|
+
*/
|
|
367
|
+
const formBack = async (response, app) => {
|
|
368
|
+
const { request, reply, status, body } = response;
|
|
369
|
+
if (status !== 422 || !isFormSubmission(request.headers))
|
|
370
|
+
return false;
|
|
371
|
+
const errors = formFieldErrors(body);
|
|
372
|
+
if (!errors)
|
|
373
|
+
return false;
|
|
374
|
+
const current = sessionOf(request);
|
|
375
|
+
const target = current ? formBackTarget(request, http.requestHost(request)) : undefined;
|
|
376
|
+
if (!current || target === undefined) {
|
|
377
|
+
if (logger.isEnabled('debug'))
|
|
378
|
+
logger.log('debug', 'App form validation answered with the error view', {
|
|
379
|
+
app,
|
|
380
|
+
reason: current ? 'no-way-back' : 'no-session',
|
|
381
|
+
method: request.method,
|
|
382
|
+
route: request.routeOptions.url ?? 'unmatched',
|
|
383
|
+
});
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
await current.flash('errors', errors);
|
|
387
|
+
const old = formOldInput(request.body);
|
|
388
|
+
if (old)
|
|
389
|
+
await current.flash('old', old);
|
|
390
|
+
if (logger.isEnabled('debug'))
|
|
391
|
+
logger.log('debug', 'App form validation redirect', {
|
|
392
|
+
app,
|
|
393
|
+
method: request.method,
|
|
394
|
+
route: request.routeOptions.url ?? 'unmatched',
|
|
395
|
+
fields: Object.keys(errors).slice(0, 32),
|
|
396
|
+
old: old ? Object.keys(old).length : 0,
|
|
397
|
+
target: target.split('?', 1)[0]?.slice(0, 200),
|
|
398
|
+
});
|
|
399
|
+
reply.redirect(target, 303);
|
|
400
|
+
return true;
|
|
401
|
+
};
|
|
402
|
+
// D-0063 §5: view engines and realtime transports by name, whoever contributes them.
|
|
403
|
+
const engines = byKey(context, viewEngines, 'name');
|
|
404
|
+
const transports = byKey(context, realtime, 'kind');
|
|
405
|
+
const sockets = transports.get('websocket');
|
|
406
|
+
const streams = transports.get('sse');
|
|
314
407
|
const sealedDomains = [...this.options.domains]
|
|
315
408
|
.filter(([, target]) => target.seal)
|
|
316
409
|
.map(([domain]) => domain);
|
|
@@ -322,16 +415,49 @@ class AppRuntime {
|
|
|
322
415
|
count: this.options.domains.size,
|
|
323
416
|
unknownDomain: this.options.unknownDomain ?? 'reject',
|
|
324
417
|
sealed: sealedDomains.length,
|
|
418
|
+
viewEngines: [...engines.keys()],
|
|
419
|
+
transports: [...transports.keys()],
|
|
325
420
|
});
|
|
326
421
|
// Fail closed (D-0059 §4): a sealed host without the seal plugin would talk plain text.
|
|
327
|
-
if (sealedDomains.length &&
|
|
328
|
-
|
|
422
|
+
if (sealedDomains.length &&
|
|
423
|
+
context.getOptionalDependency(this.#declaredFor(seal.name)) === undefined)
|
|
424
|
+
throw new AppError('SEAL_PROVIDER_MISSING', `Domains ${sealedDomains.slice(0, 8).join(', ')} set seal: true; register the dokebi-seal plugin`);
|
|
425
|
+
/** The engine an app needs, or VIEW_ENGINE_MISSING naming the package that offers it. */
|
|
426
|
+
const engine = (name, app) => {
|
|
427
|
+
const found = engines.get(name);
|
|
428
|
+
if (!found)
|
|
429
|
+
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).` });
|
|
430
|
+
return found;
|
|
431
|
+
};
|
|
329
432
|
// Behind a trusted proxy (dokebi-web trustProxy) the forwarded host picks the app.
|
|
330
433
|
const host = (request) => withoutPort(http.requestHost(request));
|
|
434
|
+
/** The host entry of a raw or Fastify request, worked out once per request. */
|
|
435
|
+
// Raw Host header → entry, so the usual request skips trimming, lower-casing and the port
|
|
436
|
+
// cut. Only when no X-Forwarded-Host is present (with one, trustProxy decides). Client input:
|
|
437
|
+
// bounded like the unknown hosts.
|
|
438
|
+
const byHeader = new Map();
|
|
439
|
+
const hostEntry = (request) => {
|
|
440
|
+
const raw = (request.raw ?? request);
|
|
441
|
+
const known = raw[HOST_ENTRY];
|
|
442
|
+
if (known !== undefined)
|
|
443
|
+
return known;
|
|
444
|
+
const header = raw.headers['x-forwarded-host'] === undefined ? raw.headers.host : undefined;
|
|
445
|
+
let entry = typeof header === 'string' ? byHeader.get(header) : undefined;
|
|
446
|
+
if (entry === undefined) {
|
|
447
|
+
entry = this.entry(host(request));
|
|
448
|
+
if (typeof header === 'string') {
|
|
449
|
+
if (byHeader.size >= UNKNOWN_HOSTS)
|
|
450
|
+
byHeader.clear();
|
|
451
|
+
byHeader.set(header, entry);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
raw[HOST_ENTRY] = entry;
|
|
455
|
+
return entry;
|
|
456
|
+
};
|
|
331
457
|
// D-0062: every HTTP request of a sealed host is sealed by dokebi-web (JSON bodies both ways,
|
|
332
458
|
// the Inertia page, SSE data), except routes with seal: false and dokebi-web sealExclude.
|
|
333
459
|
if (sealedDomains.length)
|
|
334
|
-
http.sealRequests((request) =>
|
|
460
|
+
http.sealRequests((request) => hostEntry(request)?.sealed === true);
|
|
335
461
|
http.constraint({
|
|
336
462
|
name: APP_CONSTRAINT,
|
|
337
463
|
storage() {
|
|
@@ -344,21 +470,19 @@ class AppRuntime {
|
|
|
344
470
|
};
|
|
345
471
|
},
|
|
346
472
|
deriveConstraint: (request) => {
|
|
347
|
-
const
|
|
348
|
-
const name = this.resolve(requested)?.name;
|
|
473
|
+
const name = hostEntry(request)?.info.name;
|
|
349
474
|
// Per request: only built when debug is on (D-0047).
|
|
350
475
|
if (name === undefined && logger.isEnabled('debug'))
|
|
351
|
-
logger.log('debug', 'App domain not configured', { host:
|
|
476
|
+
logger.log('debug', 'App domain not configured', { host: host(request).slice(0, 253) });
|
|
352
477
|
return name;
|
|
353
478
|
},
|
|
354
479
|
// Requests of a known app may still reach shared (unconstrained) routes.
|
|
355
480
|
mustMatchWhenDerived: false,
|
|
356
481
|
});
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
const sealFor = (own) => (request) => this.sealed(host(request)) || own === true || (typeof own === 'function' && own(request));
|
|
482
|
+
/** The shared EJS renderer (the engine's own), loaded once on first need. */
|
|
483
|
+
let ejsRoot;
|
|
484
|
+
/** Each app's error answer (D-0074), by app name. */
|
|
485
|
+
const answers = new Map();
|
|
362
486
|
for (const [name, definition] of this.apps) {
|
|
363
487
|
context.signal.throwIfAborted();
|
|
364
488
|
const begin = performance.now();
|
|
@@ -387,7 +511,7 @@ class AppRuntime {
|
|
|
387
511
|
return undefined;
|
|
388
512
|
};
|
|
389
513
|
/** `identity` in the chosen namespace: tenant prefixed, `namespace` removed. */
|
|
390
|
-
const scoped = (
|
|
514
|
+
const scoped = (kind, path) => (identity) => {
|
|
391
515
|
const chosen = namespaceOf(identity.namespace, kind, path);
|
|
392
516
|
if (chosen === undefined)
|
|
393
517
|
return undefined;
|
|
@@ -409,22 +533,22 @@ class AppRuntime {
|
|
|
409
533
|
signal: context.signal,
|
|
410
534
|
get: (plugin) => {
|
|
411
535
|
if (!allowed.has(plugin.metadata.name))
|
|
412
|
-
throw new
|
|
536
|
+
throw new AppError('NOT_REQUIRED', `App ${name} does not list ${plugin.metadata.name} in requires`);
|
|
413
537
|
return context.get(plugin);
|
|
414
538
|
},
|
|
415
539
|
getDependency: (dependency) => {
|
|
416
540
|
if (!allowed.has(dependency.name))
|
|
417
|
-
throw new
|
|
541
|
+
throw new AppError('NOT_REQUIRED', `App ${name} does not list ${dependency.name} in requires`);
|
|
418
542
|
return context.getDependency(this.#declaredFor(dependency.name));
|
|
419
543
|
},
|
|
420
544
|
getOptionalDependency: (dependency) => {
|
|
421
545
|
if (!allowed.has(dependency.name))
|
|
422
|
-
throw new
|
|
546
|
+
throw new AppError('NOT_REQUIRED', `App ${name} does not list ${dependency.name} in requires`);
|
|
423
547
|
return context.getOptionalDependency(this.#declaredFor(dependency.name));
|
|
424
548
|
},
|
|
425
549
|
controller: (token) => {
|
|
426
550
|
if (!controllers)
|
|
427
|
-
throw new
|
|
551
|
+
throw new AppError('NOT_READY', `App ${name} has no controllers yet`);
|
|
428
552
|
return controllers.get(token);
|
|
429
553
|
},
|
|
430
554
|
defer: (cleanup) => context.defer(cleanup),
|
|
@@ -433,13 +557,13 @@ class AppRuntime {
|
|
|
433
557
|
if (handle)
|
|
434
558
|
return handle;
|
|
435
559
|
if (!namespaces.includes(namespace))
|
|
436
|
-
throw
|
|
560
|
+
throw new AppError('NAMESPACE_FORBIDDEN', `App ${name} may use realtime namespaces ${namespaces.join(', ')}, not ${String(namespace).slice(0, 64)}`);
|
|
437
561
|
handle = realtimeHandle(name, namespace, sockets, streams);
|
|
438
562
|
handles.set(namespace, handle);
|
|
439
563
|
logger.log('debug', 'App realtime handle created', {
|
|
440
564
|
app: name,
|
|
441
565
|
namespace,
|
|
442
|
-
websocket:
|
|
566
|
+
websocket: sockets !== undefined,
|
|
443
567
|
sse: streams !== undefined,
|
|
444
568
|
});
|
|
445
569
|
return handle;
|
|
@@ -459,24 +583,26 @@ class AppRuntime {
|
|
|
459
583
|
});
|
|
460
584
|
controllers = await createControllers(factoryContext, definition.controllers ?? []);
|
|
461
585
|
const templates = new Set();
|
|
462
|
-
|
|
586
|
+
const hasModuleViews = Object.values(definition.modules ?? {}).some((module) => mountOf(module)?.views);
|
|
463
587
|
if (definition.views) {
|
|
464
|
-
|
|
465
|
-
await
|
|
588
|
+
// The app's folder is loaded as `<app>/…`; the engine's root renderer serves every scope.
|
|
589
|
+
ejsRoot = await engine('ejs', name).scope({
|
|
590
|
+
directory: definition.views,
|
|
591
|
+
prefix: name,
|
|
592
|
+
});
|
|
466
593
|
await this.#checkTemplates(name, definition.views, templates);
|
|
467
594
|
}
|
|
595
|
+
else if (hasModuleViews && !ejsRoot)
|
|
596
|
+
ejsRoot = await engine('ejs', name).scope({});
|
|
468
597
|
let inertiaApi;
|
|
469
598
|
if (definition.inertia) {
|
|
470
|
-
|
|
471
|
-
throw new Error(`App ${name} uses Inertia; add @dokebi/template-inertia`);
|
|
472
|
-
inertiaApi = await pages.scope({
|
|
599
|
+
inertiaApi = await engine('inertia', name).scope({
|
|
473
600
|
...definition.inertia,
|
|
474
601
|
// SSR would write the props of a sealed host as plain HTML: refused (D-0062).
|
|
475
602
|
...(appSealed ? { sealed: true } : {}),
|
|
476
603
|
shared: (request) => {
|
|
477
|
-
const
|
|
478
|
-
|
|
479
|
-
return { app: info ? { ...info } : null, sealed: this.sealed(requested) };
|
|
604
|
+
const entry = hostEntry(request);
|
|
605
|
+
return { app: entry ? { ...entry.info } : null, sealed: entry?.sealed === true };
|
|
480
606
|
},
|
|
481
607
|
});
|
|
482
608
|
}
|
|
@@ -499,61 +625,75 @@ class AppRuntime {
|
|
|
499
625
|
...appChain(template),
|
|
500
626
|
];
|
|
501
627
|
};
|
|
502
|
-
// `sealed
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
628
|
+
// `sealed`, the session flash (`errors`, `old`, `flash`; D-0074 addendum 1) and the app's
|
|
629
|
+
// shared data under the page data, computed once per render call. An error view passes
|
|
630
|
+
// its own `errors` and `old` and leaves the flash to the next page.
|
|
631
|
+
const withShared = (view, request, info, sealed, pageFlash = true) => {
|
|
632
|
+
const data = async (own) => {
|
|
633
|
+
const taken = (pageFlash ? await flashOf(request) : undefined) ?? viewFlash(undefined);
|
|
634
|
+
const result = {
|
|
635
|
+
sealed,
|
|
636
|
+
...taken,
|
|
637
|
+
...(await definition.shared?.(request, { app: info })),
|
|
638
|
+
...own,
|
|
639
|
+
};
|
|
640
|
+
// The handler's own `errors` and `old` win field by field.
|
|
641
|
+
if (plainRecord(own.errors))
|
|
642
|
+
result.errors = { ...taken.errors, ...own.errors };
|
|
643
|
+
if (plainRecord(own.old))
|
|
644
|
+
result.old = { ...taken.old, ...own.old };
|
|
645
|
+
return result;
|
|
646
|
+
};
|
|
509
647
|
return Object.freeze({
|
|
510
648
|
render: async (name, own, options) => view.render(name, await data(own), options),
|
|
511
649
|
reply: async (reply, name, own, options) => view.reply(reply, name, await data(own), options),
|
|
512
650
|
scope: (prefixes) => view.scope(prefixes),
|
|
651
|
+
has: (template) => view.has(template),
|
|
513
652
|
});
|
|
514
653
|
};
|
|
515
654
|
const pageFor = (module) => {
|
|
516
655
|
const scopes = new Map();
|
|
517
656
|
const hasViews = Boolean(definition.views || module?.views);
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
const info = this.resolve(requested) ?? {
|
|
521
|
-
name,
|
|
522
|
-
template: DEFAULT_TEMPLATE,
|
|
523
|
-
domain: requested,
|
|
524
|
-
};
|
|
525
|
-
const sealed = this.sealed(requested);
|
|
657
|
+
// Built on the first `page.view` read of a request (D-0068): most JSON routes never do.
|
|
658
|
+
const viewOf = (request, info, sealed) => {
|
|
526
659
|
let view = scopes.get(info.template);
|
|
527
660
|
if (!view) {
|
|
528
|
-
templateApi ??= hasViews ? context.getDependency(ejs) : undefined;
|
|
529
661
|
view =
|
|
530
|
-
|
|
531
|
-
?
|
|
662
|
+
ejsRoot && hasViews
|
|
663
|
+
? ejsRoot.scope(chain(info.template, module))
|
|
532
664
|
: missingViews(name);
|
|
533
665
|
scopes.set(info.template, view);
|
|
534
666
|
}
|
|
535
|
-
return
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
667
|
+
return withShared(view, request, info, sealed);
|
|
668
|
+
};
|
|
669
|
+
const moduleName = module?.name;
|
|
670
|
+
const base = module?.base ?? '';
|
|
671
|
+
return (request) => {
|
|
672
|
+
const entry = hostEntry(request);
|
|
673
|
+
// An app route is only reached through its own host (route constraint); the fallback
|
|
674
|
+
// covers a host whose entry went away in between.
|
|
675
|
+
const info = entry?.info ?? { name, template: DEFAULT_TEMPLATE, domain: host(request) };
|
|
676
|
+
return new RequestPage(info, entry?.sealed === true, moduleName, base, inertiaApi, request, viewOf);
|
|
543
677
|
};
|
|
544
678
|
};
|
|
545
679
|
const routerFor = (page, base) => {
|
|
546
680
|
const add = (options) => {
|
|
547
681
|
const { handler, ...rest } = options;
|
|
548
682
|
routeCount++;
|
|
549
|
-
|
|
683
|
+
const url = joinPath(base, rest.url);
|
|
684
|
+
const register = (path) => http.route({
|
|
550
685
|
...rest,
|
|
551
|
-
url:
|
|
686
|
+
url: path,
|
|
552
687
|
constraints: { [APP_CONSTRAINT]: name },
|
|
553
688
|
handler(request, reply) {
|
|
554
689
|
return handler(request, reply, page(request));
|
|
555
690
|
},
|
|
556
691
|
});
|
|
692
|
+
register(url);
|
|
693
|
+
// The root of a prefixed mount answers `/board/` as well as `/board`: links and form
|
|
694
|
+
// actions written with a trailing slash would otherwise be 404 (AI-M03).
|
|
695
|
+
if (base && url === base)
|
|
696
|
+
register(base + '/');
|
|
557
697
|
};
|
|
558
698
|
const method = (verb) => (url, handler, options = {}) => add({ ...options, method: verb, url, handler });
|
|
559
699
|
return Object.freeze({
|
|
@@ -565,47 +705,87 @@ class AppRuntime {
|
|
|
565
705
|
delete: method('DELETE'),
|
|
566
706
|
});
|
|
567
707
|
};
|
|
708
|
+
/** The scope of one realtime route: the full path, the app constraint and tenant rule. */
|
|
709
|
+
const scopeOf = (path, kind) => Object.freeze({
|
|
710
|
+
path,
|
|
711
|
+
constraints: Object.freeze({ [APP_CONSTRAINT]: name }),
|
|
712
|
+
identity: scoped(kind, path),
|
|
713
|
+
// The request's host decides (D-0059 §4); only when a host of this app seals.
|
|
714
|
+
...(appSealed
|
|
715
|
+
? { seal: (request) => hostEntry(request)?.sealed === true }
|
|
716
|
+
: {}),
|
|
717
|
+
});
|
|
568
718
|
const mountSockets = (routes, base, owner) => {
|
|
569
719
|
for (const route of routes) {
|
|
570
720
|
if (!sockets)
|
|
571
|
-
throw new
|
|
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' });
|
|
721
|
+
throw new AppError('REALTIME_UNAVAILABLE', `${owner} has sockets; add @dokebi/websocket`);
|
|
575
722
|
socketCount++;
|
|
576
|
-
|
|
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
|
-
});
|
|
723
|
+
sockets.mount(route, scopeOf(joinPath(base, route.path), 'socket'));
|
|
590
724
|
}
|
|
591
725
|
};
|
|
592
726
|
const mountEvents = (routes, base, owner) => {
|
|
593
727
|
for (const route of routes) {
|
|
594
728
|
if (!streams)
|
|
595
|
-
throw new
|
|
729
|
+
throw new AppError('REALTIME_UNAVAILABLE', `${owner} has event streams; add @dokebi/sse`);
|
|
596
730
|
eventCount++;
|
|
597
|
-
|
|
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
|
-
});
|
|
731
|
+
streams.mount(route, scopeOf(joinPath(base, route.path), 'stream'));
|
|
607
732
|
}
|
|
608
733
|
};
|
|
734
|
+
// D-0074 §3-4: the error answers of this app's hosts. Inertia first (the validation
|
|
735
|
+
// redirect, the app's error page component), then for an HTML answer the form redirect
|
|
736
|
+
// (addendum 1) and the app's error view: `errors/<status>` → `errors/error` in
|
|
737
|
+
// <app>/<template> → <app>/default → shared views.
|
|
738
|
+
const errorViews = new Map();
|
|
739
|
+
answers.set(name, async (response, entry) => {
|
|
740
|
+
if (inertiaApi && typeof inertiaApi.answerError === 'function') {
|
|
741
|
+
if (await inertiaApi.answerError(response))
|
|
742
|
+
return true;
|
|
743
|
+
}
|
|
744
|
+
if (response.format !== 'html')
|
|
745
|
+
return false;
|
|
746
|
+
if (await formBack(response, name))
|
|
747
|
+
return true;
|
|
748
|
+
if (!ejsRoot)
|
|
749
|
+
return false;
|
|
750
|
+
const { info, sealed } = entry;
|
|
751
|
+
let view = errorViews.get(info.template);
|
|
752
|
+
if (!view) {
|
|
753
|
+
view = ejsRoot.scope(appChain(info.template));
|
|
754
|
+
errorViews.set(info.template, view);
|
|
755
|
+
}
|
|
756
|
+
const { status, body, request, reply, production, error } = response;
|
|
757
|
+
const page = view.has(`errors/${status}`)
|
|
758
|
+
? `errors/${status}`
|
|
759
|
+
: view.has('errors/error')
|
|
760
|
+
? 'errors/error'
|
|
761
|
+
: undefined;
|
|
762
|
+
if (!page)
|
|
763
|
+
return false;
|
|
764
|
+
const fields = Array.isArray(body.fields) ? body.fields : [];
|
|
765
|
+
await withShared(view, request, info, sealed, false).reply(reply, page, {
|
|
766
|
+
status,
|
|
767
|
+
title: `${status} ${STATUS_CODES[status] ?? 'Error'}`,
|
|
768
|
+
error: body.error,
|
|
769
|
+
message: typeof body.message === 'string' ? body.message : null,
|
|
770
|
+
hint: typeof body.hint === 'string' ? body.hint : null,
|
|
771
|
+
fields,
|
|
772
|
+
// A refused form without a way back (no session, no Referer of this host): an
|
|
773
|
+
// errors/422.ejs can show the form again with these (D-0074 addendum 1).
|
|
774
|
+
errors: formFieldErrors(body) ?? {},
|
|
775
|
+
old: (status === 422 && formOldInput(request.body)) || {},
|
|
776
|
+
// Development only (dokebi-web already cut `fix` from a production body).
|
|
777
|
+
fix: typeof body.fix === 'string' ? body.fix : null,
|
|
778
|
+
stack: !production && status >= 500 && error instanceof Error ? (error.stack ?? null) : null,
|
|
779
|
+
});
|
|
780
|
+
if (logger.isEnabled('debug'))
|
|
781
|
+
logger.log('debug', 'App error view rendered', {
|
|
782
|
+
app: name,
|
|
783
|
+
template: info.template,
|
|
784
|
+
view: page,
|
|
785
|
+
status,
|
|
786
|
+
});
|
|
787
|
+
return true;
|
|
788
|
+
});
|
|
609
789
|
await definition.setup?.(appContext);
|
|
610
790
|
await definition.routes?.(routerFor(pageFor(), ''), appContext);
|
|
611
791
|
mountSockets((await definition.sockets?.(appContext)) ?? [], '', `App ${name}`);
|
|
@@ -639,9 +819,16 @@ class AppRuntime {
|
|
|
639
819
|
ms: Math.round(performance.now() - begin),
|
|
640
820
|
});
|
|
641
821
|
}
|
|
822
|
+
// D-0074: errors on an app's hosts (unknown routes included) are answered by that app.
|
|
823
|
+
// Added after the template plugins' responders, so dokebi-web asks this one first.
|
|
824
|
+
http.errorResponder((response) => {
|
|
825
|
+
const entry = hostEntry(response.request);
|
|
826
|
+
const answer = entry ? answers.get(entry.info.name) : undefined;
|
|
827
|
+
return entry && answer ? answer(response, entry) : false;
|
|
828
|
+
});
|
|
642
829
|
return Object.freeze({
|
|
643
830
|
names: Object.freeze([...this.apps.keys()]),
|
|
644
|
-
resolve: (request) =>
|
|
831
|
+
resolve: (request) => hostEntry(request)?.info,
|
|
645
832
|
});
|
|
646
833
|
}
|
|
647
834
|
/** Every template a domain selects must exist as a folder, and `default` always must. */
|
|
@@ -659,7 +846,7 @@ class AppRuntime {
|
|
|
659
846
|
return undefined;
|
|
660
847
|
});
|
|
661
848
|
if (!info?.isDirectory())
|
|
662
|
-
throw new
|
|
849
|
+
throw new AppError('VIEWS_MISSING', `App ${name} has no views/${template}/ folder`, failure === undefined ? {} : { cause: failure });
|
|
663
850
|
found.add(template);
|
|
664
851
|
}
|
|
665
852
|
}
|
|
@@ -690,30 +877,38 @@ class AppRuntime {
|
|
|
690
877
|
}
|
|
691
878
|
function missingViews(name) {
|
|
692
879
|
const fail = async () => {
|
|
693
|
-
throw new
|
|
880
|
+
throw new AppError('VIEWS_MISSING', `App ${name} has no views folder`);
|
|
694
881
|
};
|
|
695
|
-
const api = Object.freeze({
|
|
882
|
+
const api = Object.freeze({
|
|
883
|
+
render: fail,
|
|
884
|
+
reply: fail,
|
|
885
|
+
scope: () => api,
|
|
886
|
+
has: () => false,
|
|
887
|
+
});
|
|
696
888
|
return api;
|
|
697
889
|
}
|
|
698
890
|
export const createPlugin = definePlugin({
|
|
699
891
|
name: 'dokebi-app',
|
|
700
|
-
version: '0.
|
|
701
|
-
core: '^0.
|
|
702
|
-
options:
|
|
892
|
+
version: '0.4.1',
|
|
893
|
+
core: '^0.4.0',
|
|
894
|
+
options: declaration,
|
|
703
895
|
entry: parseEntry,
|
|
896
|
+
// Template and realtime plugins are found through these points, not by name (D-0063 §5).
|
|
897
|
+
collects: [viewEngines, realtime],
|
|
704
898
|
dependencies: ({ entry }) => {
|
|
705
899
|
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);
|
|
900
|
+
const list = [web, seal, session];
|
|
710
901
|
for (const app of apps)
|
|
711
902
|
for (const item of [...(app.requires ?? []), ...Object.values(app.modules ?? {})]) {
|
|
712
903
|
const dependency = requirement(item);
|
|
713
|
-
|
|
904
|
+
const index = list.findIndex((existing) => existing.name === dependency.name);
|
|
905
|
+
if (index === -1)
|
|
714
906
|
list.push(dependency);
|
|
907
|
+
// An app that requires an optional provider (session, seal) makes it required.
|
|
908
|
+
else if (list[index]?.optional && !dependency.optional)
|
|
909
|
+
list[index] = dependency;
|
|
715
910
|
}
|
|
716
911
|
return list;
|
|
717
912
|
},
|
|
718
|
-
instance: ({ options, entry, dependencies }) => new AppRuntime(options, entry ?? new Map(), dependencies),
|
|
913
|
+
instance: ({ options, entry, dependencies }) => new AppRuntime(settings(options), entry ?? new Map(), dependencies),
|
|
719
914
|
});
|