@genesislcap/mock-server 15.74.0 → 15.76.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.
Files changed (100) hide show
  1. package/README.md +296 -58
  2. package/dist/db/schema.d.ts +9 -1
  3. package/dist/db/schema.js +40 -11
  4. package/dist/db/store.d.ts +1 -0
  5. package/dist/db/store.js +4 -0
  6. package/dist/handlers/auth.d.ts +15 -6
  7. package/dist/handlers/auth.js +152 -33
  8. package/dist/handlers/commitEvent.js +43 -20
  9. package/dist/handlers/crudEvents.d.ts +3 -1
  10. package/dist/handlers/crudEvents.js +3 -2
  11. package/dist/handlers/eventValidation.js +6 -3
  12. package/dist/handlers/http.d.ts +2 -2
  13. package/dist/handlers/http.js +66 -43
  14. package/dist/handlers/jsonSchema.d.ts +1 -0
  15. package/dist/handlers/jsonSchema.js +72 -21
  16. package/dist/handlers/meta.d.ts +1 -1
  17. package/dist/handlers/meta.js +59 -10
  18. package/dist/handlers/requestReply.js +36 -9
  19. package/dist/index.d.ts +1 -1
  20. package/dist/presets/auth.d.ts +25 -0
  21. package/dist/presets/auth.js +855 -0
  22. package/dist/presets/cronExpression.d.ts +1 -0
  23. package/dist/presets/cronExpression.js +429 -0
  24. package/dist/presets/fileServer.d.ts +13 -0
  25. package/dist/presets/fileServer.js +399 -0
  26. package/dist/presets/gsf.d.ts +24 -0
  27. package/dist/presets/gsf.js +450 -0
  28. package/dist/presets/index.d.ts +1 -0
  29. package/dist/presets/index.js +1 -0
  30. package/dist/presets/javaTime.d.ts +7 -0
  31. package/dist/presets/javaTime.js +322 -0
  32. package/dist/presets/multipart.d.ts +14 -0
  33. package/dist/presets/multipart.js +91 -0
  34. package/dist/presets/notify.d.ts +27 -0
  35. package/dist/presets/notify.js +250 -0
  36. package/dist/presets/notifyDispatch.d.ts +28 -0
  37. package/dist/presets/notifyDispatch.js +570 -0
  38. package/dist/presets/notifyRules.d.ts +9 -0
  39. package/dist/presets/notifyRules.js +754 -0
  40. package/dist/presets/platform/backing.json +8058 -217
  41. package/dist/presets/platform/criteria-model.json +362 -0
  42. package/dist/presets/platform/time-zones.json +608 -0
  43. package/dist/presets/platform.d.ts +7 -0
  44. package/dist/presets/platform.js +145 -103
  45. package/dist/presets/products.d.ts +9 -7
  46. package/dist/presets/products.js +89 -21
  47. package/dist/presets/reconciliation.d.ts +18 -0
  48. package/dist/presets/reconciliation.js +721 -0
  49. package/dist/presets/reporting.d.ts +14 -0
  50. package/dist/presets/reporting.js +862 -0
  51. package/dist/protocol/connection.d.ts +2 -0
  52. package/dist/protocol/connection.js +4 -0
  53. package/dist/protocol/dtoTypes.d.ts +30 -0
  54. package/dist/protocol/dtoTypes.js +250 -0
  55. package/dist/protocol/errors.d.ts +3 -1
  56. package/dist/protocol/errors.js +2 -0
  57. package/dist/protocol/fieldTypes.js +5 -0
  58. package/dist/protocol/router.d.ts +1 -0
  59. package/dist/protocol/router.js +3 -3
  60. package/dist/protocol/schemaValidation.d.ts +1 -1
  61. package/dist/protocol/schemaValidation.js +53 -8
  62. package/dist/server.js +34 -2
  63. package/dist/types.d.ts +50 -2
  64. package/package.json +1 -1
  65. package/src/db/schema.ts +56 -13
  66. package/src/db/store.ts +5 -0
  67. package/src/handlers/auth.ts +211 -37
  68. package/src/handlers/commitEvent.ts +44 -19
  69. package/src/handlers/crudEvents.ts +9 -2
  70. package/src/handlers/eventValidation.ts +6 -3
  71. package/src/handlers/http.ts +83 -42
  72. package/src/handlers/jsonSchema.ts +86 -23
  73. package/src/handlers/meta.ts +77 -9
  74. package/src/handlers/requestReply.ts +42 -6
  75. package/src/index.ts +7 -0
  76. package/src/presets/auth.ts +961 -0
  77. package/src/presets/cronExpression.ts +445 -0
  78. package/src/presets/fileServer.ts +475 -0
  79. package/src/presets/gsf.ts +475 -0
  80. package/src/presets/index.ts +5 -0
  81. package/src/presets/javaTime.ts +354 -0
  82. package/src/presets/multipart.ts +110 -0
  83. package/src/presets/notify.ts +312 -0
  84. package/src/presets/notifyDispatch.ts +685 -0
  85. package/src/presets/notifyRules.ts +866 -0
  86. package/src/presets/platform/backing.json +8058 -217
  87. package/src/presets/platform/criteria-model.json +362 -0
  88. package/src/presets/platform/time-zones.json +608 -0
  89. package/src/presets/platform.ts +204 -115
  90. package/src/presets/products.ts +125 -19
  91. package/src/presets/reconciliation.ts +824 -0
  92. package/src/presets/reporting.ts +953 -0
  93. package/src/protocol/connection.ts +4 -0
  94. package/src/protocol/dtoTypes.ts +310 -0
  95. package/src/protocol/errors.ts +13 -1
  96. package/src/protocol/fieldTypes.ts +5 -0
  97. package/src/protocol/router.ts +3 -3
  98. package/src/protocol/schemaValidation.ts +61 -8
  99. package/src/server.ts +38 -2
  100. package/src/types.ts +147 -3
@@ -45,7 +45,10 @@ function resolveEventHandler(
45
45
  interface EventTransaction {
46
46
  broadcast: BroadcastFn;
47
47
  broadcastTableChange: BroadcastTableChangeFn;
48
- // Keeps the writes; the held pushes wait for flush().
48
+ // Holds a callback for commit() (EventHandlerCtx.afterCommit).
49
+ afterCommit(callback: () => void): void;
50
+ // Keeps the writes and runs the afterCommit callbacks; the held pushes,
51
+ // the callbacks' too, wait for flush().
49
52
  commit(): void;
50
53
  // Sends the held pushes. The event is committed whatever a push does: a
51
54
  // failing one is logged, and the rest still go out.
@@ -55,40 +58,59 @@ interface EventTransaction {
55
58
  rollback(): void;
56
59
  }
57
60
 
61
+ // Runs each callback; one that fails is logged, and the rest still run.
62
+ function runAll(callbacks: Array<() => void>, what: string): void {
63
+ for (const callback of callbacks.splice(0)) {
64
+ try {
65
+ callback();
66
+ } catch (error) {
67
+ console.error(`[mock-server] Error ${what}:`, error);
68
+ }
69
+ }
70
+ }
71
+
58
72
  function openTransaction(store: Store, ctx: CommitEventCtx, audit: AuditContext): EventTransaction {
59
73
  const pending: Array<() => void> = [];
60
- let open = true;
74
+ const committed: Array<() => void> = [];
75
+ // open: the handler runs; committed: its writes kept, its pushes waiting
76
+ // for flush(); over: flushed or rolled back.
77
+ let state: 'open' | 'committed' | 'over' = 'open';
78
+ let rolledBack = false;
61
79
  store.begin(audit);
62
80
  const hold = (push: () => void) => {
63
- if (open) pending.push(push);
64
- else push();
81
+ if (state === 'over') push();
82
+ else pending.push(push);
65
83
  };
66
84
  return {
67
85
  broadcast: (resourceName, operation, row) =>
68
86
  hold(() => ctx.broadcast(resourceName, operation, row)),
69
87
  broadcastTableChange: (tableName, operation, pk) =>
70
88
  hold(() => ctx.broadcastTableChange(tableName, operation, pk)),
89
+ // Asked for once the handler is done (from a callback, or kept for
90
+ // later): at once when the event committed, never when it rolled back.
91
+ afterCommit: (callback) => {
92
+ if (state === 'open') committed.push(callback);
93
+ else if (!rolledBack) runAll([callback], 'after a commit');
94
+ },
71
95
  commit() {
72
96
  // The audit rows the writes added go live with them.
73
97
  for (const { tableName, key } of store.takeAuditWrites()) {
74
98
  pending.push(() => ctx.broadcastTableChange(tableName, 'INSERT', key));
75
99
  }
76
- open = false;
77
100
  store.commit();
101
+ state = 'committed';
102
+ runAll(committed, 'after a commit');
78
103
  },
79
104
  flush() {
80
- for (const push of pending.splice(0)) {
81
- try {
82
- push();
83
- } catch (error) {
84
- console.error('[mock-server] Error pushing a committed change:', error);
85
- }
86
- }
105
+ state = 'over';
106
+ runAll(pending, 'pushing a committed change');
87
107
  },
88
108
  rollback() {
89
- if (!open) return;
90
- open = false;
109
+ if (state !== 'open') return;
110
+ state = 'over';
111
+ rolledBack = true;
91
112
  pending.length = 0;
113
+ committed.length = 0;
92
114
  store.rollback();
93
115
  },
94
116
  };
@@ -194,10 +216,12 @@ export function handleCommitEvent(
194
216
  connection,
195
217
  store,
196
218
  message,
219
+ config,
197
220
  broadcast: transaction?.broadcast ?? ctx.broadcast,
198
221
  broadcastTableChange: transaction?.broadcastTableChange ?? ctx.broadcastTableChange,
199
222
  validate,
200
223
  ignoreWarnings,
224
+ afterCommit: transaction?.afterCommit ?? ((callback) => callback()),
201
225
  }) ?? {};
202
226
  if (result.warnings?.length && (validate || !ignoreWarnings)) {
203
227
  transaction?.rollback();
@@ -208,20 +232,21 @@ export function handleCommitEvent(
208
232
  return;
209
233
  }
210
234
  const generated = validate && !legacy ? [] : (result.generated ?? []);
211
- // A GENERATED that can't go on the wire (a BigInt, a cycle) fails the
212
- // event here, before anything is committed.
213
- JSON.stringify(generated);
235
+ const reply = result.reply ?? { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_ACK, GENERATED: generated };
236
+ // A reply that can't go on the wire (a BigInt, a cycle) fails the event
237
+ // here, before anything is committed.
238
+ JSON.stringify(reply);
214
239
  if (validate) transaction?.rollback();
215
240
  else transaction?.commit();
216
241
  try {
217
- connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_ACK, GENERATED: generated });
242
+ connection.reply(message, reply);
218
243
  } finally {
219
244
  transaction?.flush();
220
245
  }
221
246
  } catch (error) {
222
247
  transaction?.rollback();
223
248
  connection.reply(message, {
224
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK,
249
+ MESSAGE_TYPE: (error instanceof NackError && error.messageType) || MESSAGE_TYPE.EVENT_NACK,
225
250
  ...nackPayload(error, legacy),
226
251
  });
227
252
  }
@@ -44,8 +44,15 @@ function indexValueText(fields: string[], row: Row): string {
44
44
 
45
45
  // The database's unique constraints: the primary key (unless `self` is the
46
46
  // record being modified, whose key can't change) and every other unique
47
- // index. A null in an index's fields never clashes, as in SQL.
48
- function checkUnique(table: string, def: TableDef, row: Row, store: Store, self?: string): void {
47
+ // index. A null in an index's fields never clashes, as in SQL. A clash is
48
+ // entityDb's DUPLICATE_KEY.
49
+ export function checkUnique(
50
+ table: string,
51
+ def: TableDef,
52
+ row: Row,
53
+ store: Store,
54
+ self?: string,
55
+ ): void {
49
56
  const pkFields = pkFieldsOf(def);
50
57
  if (self === undefined && pkFields.every((field) => !isMissing(row[field]))) {
51
58
  if (store.getRow(table, store.rowKey(table, row))) {
@@ -2,6 +2,7 @@ import { eventFields, isDeclared, resolveEventTarget, type ResolvedField } from
2
2
  import type { Store } from '../db/store.ts';
3
3
  import { eventValue } from '../db/values.ts';
4
4
  import type { Connection } from '../protocol/connection.ts';
5
+ import { decodedValue } from '../protocol/dtoTypes.ts';
5
6
  import type { NackErrorInput } from '../protocol/errors.ts';
6
7
  import { schemaFieldErrors, validateSchema } from '../protocol/schemaValidation.ts';
7
8
  import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
@@ -52,8 +53,10 @@ function declaredEvent(
52
53
 
53
54
  // DETAILS as the handler gets them, after the schema check: a declared
54
55
  // BigDecimal field's string is a number, as GSF hands its handler a
55
- // deserialized BigDecimal (db/values.ts eventValue). Anything else, and any
56
- // undeclared event's DETAILS, as sent.
56
+ // deserialized BigDecimal (db/values.ts eventValue), and a nested class
57
+ // loses the keys it doesn't declare, which its schema lets through
58
+ // (protocol/dtoTypes.ts decodedValue). Anything else, and any undeclared
59
+ // event's DETAILS, as sent.
57
60
  export function eventDetails(message: GenesisMessage, config: MockServerConfig, store: Store): Row {
58
61
  const details: Row = message.DETAILS ?? {};
59
62
  const declared = declaredEvent(message.MESSAGE_TYPE, config, store);
@@ -61,7 +64,7 @@ export function eventDetails(message: GenesisMessage, config: MockServerConfig,
61
64
  let converted: Row | undefined;
62
65
  for (const field of declared.fields) {
63
66
  if (!Object.hasOwn(details, field.name)) continue;
64
- const value = eventValue(field, details[field.name]);
67
+ const value = eventValue(field, decodedValue(field, details[field.name]));
65
68
  if (value === details[field.name]) continue;
66
69
  converted ??= { ...details };
67
70
  converted[field.name] = value;
@@ -1,22 +1,35 @@
1
1
  import crypto from 'node:crypto';
2
2
  import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import type { Store } from '../db/store.ts';
3
4
  import { isLegacyFidelity } from '../protocol/fidelity.ts';
4
5
  import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
5
6
  import { notLoggedInNack } from '../protocol/msgNack.ts';
6
- import type { AuthUser, CookieAuthenticationOptions, MockServerConfig, Row } from '../types.ts';
7
+ import type {
8
+ AuthUser,
9
+ CookieAuthenticationOptions,
10
+ HttpRouteCtx,
11
+ LoginCtx,
12
+ MockServerConfig,
13
+ Row,
14
+ } from '../types.ts';
7
15
  import {
16
+ attemptLogin,
8
17
  buildLoginAckBody,
9
18
  buildLoginNackBody,
10
19
  buildLogoutAckBody,
11
20
  capRegistry,
12
21
  closeSession,
13
- createAuthState,
22
+ credentialsLogin,
14
23
  findUser,
15
- findUserByCredentials,
24
+ loginKind,
16
25
  openSession,
26
+ recordLogout,
27
+ refreshLogin,
17
28
  refreshTokenExpirationMins,
29
+ routerHostname,
18
30
  sessionByRefreshToken,
19
31
  sessionTimeoutMins,
32
+ unclaimedLogin,
20
33
  type AuthSession,
21
34
  type AuthState,
22
35
  } from './auth.ts';
@@ -177,10 +190,14 @@ function headerValue(req: IncomingMessage, name: string): string | undefined {
177
190
  return typeof value === 'string' ? value : undefined;
178
191
  }
179
192
 
180
- function autoLoginUser(config: MockServerConfig): AuthUser | undefined {
193
+ function autoLoginUser(config: MockServerConfig, store: Store): AuthUser | undefined {
181
194
  const autoLogin = config.auth?.httpAutoLogin;
182
195
  if (!autoLogin) return undefined;
183
- return findUser(config, autoLogin === true ? config.auth?.users?.[0]?.username : autoLogin);
196
+ return findUser(
197
+ config,
198
+ store,
199
+ autoLogin === true ? config.auth?.users?.[0]?.username : autoLogin,
200
+ );
184
201
  }
185
202
 
186
203
  // Drops every token this server minted for `username` (fidelity: 'legacy',
@@ -216,8 +233,17 @@ function legacySessionCookie(sessionId: string): string {
216
233
  export function createHttpRequestListener(
217
234
  config: MockServerConfig,
218
235
  legacySessions: Map<string, string>,
219
- auth: AuthState = createAuthState(),
236
+ auth: AuthState,
237
+ routeCtx: Omit<HttpRouteCtx, 'userName'>,
220
238
  ) {
239
+ const { store } = routeCtx;
240
+ // What a login or logout over HTTP runs with.
241
+ const loginCtx = (req: IncomingMessage, body: Row): LoginCtx => ({
242
+ store,
243
+ broadcastTableChange: routeCtx.broadcastTableChange,
244
+ hostname: routerHostname(req.headers.hostname, req.socket.remoteAddress),
245
+ messageUser: typeof body.USER_NAME === 'string' ? body.USER_NAME : null,
246
+ });
221
247
  // Every HTTP reply carries a SOURCE_REF: the request's, or AUTO_<uuid> as
222
248
  // the router mints one (http-login.json). Not under fidelity: 'legacy'.
223
249
  const withSourceRef = (body: Row, request: Row = {}): Row =>
@@ -225,12 +251,13 @@ export function createHttpRequestListener(
225
251
  ? body
226
252
  : { ...body, SOURCE_REF: request.SOURCE_REF ?? `AUTO_${crypto.randomUUID()}` };
227
253
 
228
- // The session a request names: the sessionAuthToken cookie under
229
- // cookieAuthentication, else (GSF) the SESSION_AUTH_TOKEN header. '' when
230
- // the cookie is there but empty, as after a logout cleared it.
254
+ // The session a request names: the SESSION_AUTH_TOKEN header, which under
255
+ // cookieAuthentication the sessionAuthToken cookie overwrites when there is
256
+ // one (CookieHandler.kt:52-59 @v8.15.29). '' when the cookie is there but
257
+ // empty, as after a logout cleared it.
231
258
  function requestToken(req: IncomingMessage, cookies: Record<string, string>): string | undefined {
232
- if (cookieAuthentication(config)) return cookies[SESSION_AUTH_TOKEN_COOKIE];
233
- return headerValue(req, 'SESSION_AUTH_TOKEN');
259
+ const cookie = cookieAuthentication(config) ? cookies[SESSION_AUTH_TOKEN_COOKIE] : undefined;
260
+ return cookie ?? headerValue(req, 'SESSION_AUTH_TOKEN');
234
261
  }
235
262
 
236
263
  // The legacy-mode session cookie, or none.
@@ -254,13 +281,13 @@ export function createHttpRequestListener(
254
281
  function handleLoginDetails(req: IncomingMessage, res: ServerResponse, request: Row): void {
255
282
  const cookies = parseCookies(req.headers.cookie);
256
283
  const legacyWithoutCookies = isLegacyFidelity(config) && !cookieAuthentication(config);
257
- const autoLogin = autoLoginUser(config);
284
+ const autoLogin = autoLoginUser(config, store);
258
285
 
259
286
  // fidelity: 'legacy' without cookieAuthentication: as up to 15.47, a new
260
287
  // session per call, found by the MOCK_SESSION_ID cookie.
261
288
  if (legacyWithoutCookies) {
262
289
  const user =
263
- autoLogin ?? findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
290
+ autoLogin ?? findUser(config, store, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
264
291
  if (!user) {
265
292
  sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
266
293
  MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
@@ -278,7 +305,7 @@ export function createHttpRequestListener(
278
305
 
279
306
  const token = requestToken(req, cookies);
280
307
  const session = token === undefined ? undefined : auth.sessions.get(token);
281
- const sessionUser = session && findUser(config, session.username);
308
+ const sessionUser = session && findUser(config, store, session.username);
282
309
  if (session && sessionUser) {
283
310
  const body = buildLoginAckBody(sessionUser, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
284
311
  sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request));
@@ -304,30 +331,40 @@ export function createHttpRequestListener(
304
331
  const cookies = parseCookies(req.headers.cookie);
305
332
  const cookieOptions = cookieAuthentication(config);
306
333
 
307
- // No USER_NAME: a token refresh (foundation-comms' sessionRefresh
308
- // performRefresh). Its refresh token is the refreshAuthToken cookie under
309
- // cookieAuthentication (CookieHandler.kt:62-67), else DETAILS'; under
310
- // fidelity: 'legacy' without cookies, the MOCK_SESSION_ID session.
311
- let user: AuthUser | undefined;
312
- if (details.USER_NAME !== undefined) {
313
- user = findUserByCredentials(config, details.USER_NAME, details.PASSWORD);
314
- } else if (isLegacyFidelity(config) && !cookieOptions) {
315
- user = findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
316
- } else {
317
- const refreshToken = cookieOptions
318
- ? cookies[REFRESH_AUTH_TOKEN_COOKIE]
319
- : (details.REFRESH_AUTH_TOKEN ?? headerValue(req, 'REFRESH_AUTH_TOKEN'));
320
- user = findUser(config, sessionByRefreshToken(auth, refreshToken)?.username);
321
- }
334
+ // A refresh (foundation-comms' sessionRefresh performRefresh) names its
335
+ // token in the refreshAuthToken cookie under cookieAuthentication
336
+ // (CookieHandler.kt:62-67), else in DETAILS; under fidelity: 'legacy'
337
+ // without cookies, the MOCK_SESSION_ID session is the one refreshed.
338
+ const refreshToken = cookieOptions
339
+ ? cookies[REFRESH_AUTH_TOKEN_COOKIE]
340
+ : (details.REFRESH_AUTH_TOKEN ?? headerValue(req, 'REFRESH_AUTH_TOKEN'));
341
+ const ctx = loginCtx(req, body);
342
+ // The session a refresh logs out (RefreshTokenAuthenticator deletes the
343
+ // USER_SESSION whose token it used); fidelity: 'legacy' keeps it.
344
+ let replaced: AuthSession | undefined;
345
+ const user = attemptLogin(() => {
346
+ const kind = loginKind(config, details, refreshToken);
347
+ if (kind === 'credentials') return credentialsLogin(config, store, details, ctx);
348
+ if (kind === 'none') return unclaimedLogin(config, details, ctx);
349
+ if (isLegacyFidelity(config) && !cookieOptions) {
350
+ const username = legacySessions.get(cookies[LEGACY_SESSION_COOKIE]);
351
+ return findUser(config, store, username) ?? 'INCORRECT_CREDENTIALS';
352
+ }
353
+ const session = sessionByRefreshToken(auth, refreshToken);
354
+ if (!isLegacyFidelity(config)) replaced = session;
355
+ return refreshLogin(config, store, session?.username, ctx);
356
+ });
322
357
 
323
- if (!user) {
358
+ if (typeof user === 'string') {
324
359
  // GSF answers a failed login with HTTP 200; fidelity: 'legacy' with 401.
325
360
  const status = isLegacyFidelity(config) ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.OK;
326
361
  const nackCookies = cookieOptions ? loginNackCookies(cookieOptions) : [];
327
- sendJson(res, status, withSourceRef(buildLoginNackBody(config, 'http'), body), nackCookies);
362
+ const nack = buildLoginNackBody(config, 'http', user);
363
+ sendJson(res, status, withSourceRef(nack, body), nackCookies);
328
364
  return;
329
365
  }
330
366
 
367
+ if (replaced) closeSession(auth, replaced);
331
368
  const session = openSession(auth, user);
332
369
  const ack = buildLoginAckBody(user, session, config, auth);
333
370
  sendJson(res, HTTP_STATUS.OK, withSourceRef(ack, body), sessionCookies(cookies, session));
@@ -348,16 +385,18 @@ export function createHttpRequestListener(
348
385
  }
349
386
 
350
387
  // auth's LOGOUT ends the session SESSION_ID names (the sessionId cookie
351
- // under cookieAuthentication, CookieHandler.kt:76-81), else the token's.
352
- const sessionId = cookieOptions
353
- ? cookies[SESSION_ID_COOKIE]
354
- : (body.SESSION_ID ?? headerValue(req, 'SESSION_ID'));
355
- const token = cookieOptions ? cookies[SESSION_AUTH_TOKEN_COOKIE] : requestToken(req, cookies);
356
- for (const session of auth.sessions.values()) {
357
- if (session.sessionId === sessionId || session.sessionAuthToken === token) {
358
- closeSession(auth, session);
359
- }
360
- }
388
+ // under cookieAuthentication, CookieHandler.kt:76-81, else the request's
389
+ // own), else the token's.
390
+ const sessionId =
391
+ (cookieOptions ? cookies[SESSION_ID_COOKIE] : undefined) ??
392
+ body.SESSION_ID ??
393
+ headerValue(req, 'SESSION_ID');
394
+ const token = requestToken(req, cookies);
395
+ const ended = [...auth.sessions.values()].filter(
396
+ (session) => session.sessionId === sessionId || session.sessionAuthToken === token,
397
+ );
398
+ for (const session of ended) closeSession(auth, session);
399
+ for (const session of ended) recordLogout(config, auth, session.username, loginCtx(req, body));
361
400
  if (isLegacyFidelity(config)) {
362
401
  sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config), logoutCookies(cookieOptions!));
363
402
  return;
@@ -385,7 +424,9 @@ export function createHttpRequestListener(
385
424
  : candidate.path.test(pathname)),
386
425
  );
387
426
  if (route) {
388
- await route.handler(req, res);
427
+ const token = requestToken(req, parseCookies(req.headers.cookie));
428
+ const userName = token === undefined ? undefined : auth.sessions.get(token)?.username;
429
+ await route.handler(req, res, { ...routeCtx, ...(userName ? { userName } : {}) });
389
430
  return;
390
431
  }
391
432
 
@@ -1,4 +1,5 @@
1
1
  import {
2
+ dtoFields,
2
3
  eventDefaultOf,
3
4
  eventFields,
4
5
  inferEventTable,
@@ -10,12 +11,14 @@ import {
10
11
  requestReplySourceSchema,
11
12
  resolveEventTarget,
12
13
  resolveSourceSchema,
14
+ typedFields,
13
15
  withTypeOverrides,
14
16
  type EventTarget,
15
17
  type ResolvedField,
16
18
  } from '../db/schema.ts';
17
19
  import type { Store } from '../db/store.ts';
18
20
  import type { Connection } from '../protocol/connection.ts';
21
+ import { isNestedType, jsonDefs, nestedClasses, nestedProperty } from '../protocol/dtoTypes.ts';
19
22
  import { isLegacyFidelity } from '../protocol/fidelity.ts';
20
23
  import {
21
24
  BIGDECIMAL_PATTERN,
@@ -70,10 +73,12 @@ export { inferEventTable };
70
73
  // One DETAILS property of an event's INBOUND schema. Nullable fields are
71
74
  // oneOf [schema, null]; BigDecimal is a string with a pattern and no
72
75
  // genesisType; dates are integers (epoch millis) described as DateTime. Only
73
- // a table event's DAO class has titles, lengths, ranges and genesisTypes
74
- // (see meta.ts eventMetaField).
75
- function eventProperty(field: ResolvedField, annotated: boolean, appName?: string): Row {
76
+ // a table event's DAO class, and a DAO a DTO unwraps, have titles, lengths,
77
+ // ranges and genesisTypes (see meta.ts eventMetaField).
78
+ function eventProperty(field: ResolvedField, table: boolean, appName?: string): Row {
76
79
  const type = field.type;
80
+ if (isNestedType(type)) return nestedProperty(field);
81
+ const annotated = table || field.dao === true;
77
82
  const property: Row = {};
78
83
  if (annotated && type === 'STRING') {
79
84
  if (field.minLength !== undefined) property.minLength = field.minLength;
@@ -85,7 +90,8 @@ function eventProperty(field: ResolvedField, annotated: boolean, appName?: strin
85
90
  property.readOnly = false;
86
91
  if (type === 'ENUM' && knownValues(field)) property.enum = knownValues(field);
87
92
  property.description =
88
- field.description ?? jvmClassOf(type, () => enumClassOf(field.table, field.name, appName));
93
+ field.description ??
94
+ jvmClassOf(type, () => field.enumClass ?? enumClassOf(field.table, field.name, appName));
89
95
  const fieldDefault = eventDefaultOf(field);
90
96
  if (fieldDefault !== undefined) property.default = fieldDefault;
91
97
  if (annotated) property.title = field.title ?? titleCase(field.name);
@@ -101,6 +107,32 @@ function isRequired(field: ResolvedField): boolean {
101
107
  return !field.optional;
102
108
  }
103
109
 
110
+ // The nested classes an INBOUND schema's $refs name, as GSF writes them for
111
+ // its validator and its JSON_SCHEMA reply alike
112
+ // (SingleObjectDefinition.toJsonSchema, JsonSchema.kt:474-486 @v8.15.29):
113
+ // each property as DETAILS' are, the required ones listed (an empty list
114
+ // too), and no additionalProperties, so a nested item may carry keys its
115
+ // class doesn't have, which the decoder drops. A reply's $defs are written
116
+ // the other way (dtoTypes.ts jsonDefs).
117
+ function inboundDefs(fields: ResolvedField[], table?: string, appName?: string): Row {
118
+ return Object.fromEntries(
119
+ [...nestedClasses(fields).values()].map((nested) => {
120
+ const properties = dtoFields(nested.fields, table);
121
+ return [
122
+ nested.className,
123
+ {
124
+ properties: Object.fromEntries(
125
+ properties.map((field) => [field.name, eventProperty(field, false, appName)]),
126
+ ),
127
+ required: properties.filter(isRequired).map((field) => field.name),
128
+ description: nested.className,
129
+ type: 'object',
130
+ },
131
+ ];
132
+ }),
133
+ );
134
+ }
135
+
104
136
  // An event's INBOUND schema: the message, with DETAILS as the event's class.
105
137
  // It is also what an inbound event is validated against
106
138
  // (handlers/eventValidation.ts), as on the real server.
@@ -125,7 +157,7 @@ export function eventInboundSchema(
125
157
  additionalProperties: true,
126
158
  description: target.className,
127
159
  ...(target.title ? { title: target.title } : {}),
128
- $defs: {},
160
+ $defs: inboundDefs(fields, target.table, appName),
129
161
  $schema: GENESIS_META_SCHEMA,
130
162
  type: 'object',
131
163
  };
@@ -153,8 +185,10 @@ function typeSchema(field: ResolvedField): Row {
153
185
  }
154
186
 
155
187
  // A row property in a reply schema: nullable as oneOf [null, schema], with
156
- // an empty description and the Genesis type (BigDecimal included).
188
+ // an empty description and the Genesis type (BigDecimal included); a typed
189
+ // server's list, map or nested class as a DTO's is.
157
190
  function rowProperty(field: ResolvedField, nullable: boolean): Row {
191
+ if (isNestedType(field.type)) return nestedProperty({ ...field, nullable });
158
192
  return nullable
159
193
  ? { oneOf: [{ type: 'null' }, typeSchema(field)], description: '', genesisType: field.type }
160
194
  : { ...typeSchema(field), description: '', genesisType: field.type };
@@ -183,27 +217,42 @@ function requestServerSchema(
183
217
  config: MockServerConfig,
184
218
  store: Store,
185
219
  ): { INBOUND: Row; OUTBOUND: Row } {
186
- const entityFields = requestReplySourceSchema(requestReply, config, store).fields;
220
+ // A typed server's request and reply classes (not recorded: in the
221
+ // envelope a GPAL request server's schema has), else the request block and
222
+ // the source's fields.
223
+ const typed = requestReply.typed;
224
+ const entityFields = typed ? [] : requestReplySourceSchema(requestReply, config, store).fields;
225
+ const requestFields = typed
226
+ ? typedFields(typed.request.fields)
227
+ : requestFieldsOf(requestReply, store).map(
228
+ (fieldName) =>
229
+ entityFields.find((candidate) => candidate.name === fieldName) ??
230
+ ({ name: fieldName, type: 'STRING' } as ResolvedField),
231
+ );
187
232
  const requestProperties = Object.fromEntries(
188
- requestFieldsOf(requestReply, store).map((fieldName) => {
189
- const field = entityFields.find((candidate) => candidate.name === fieldName);
190
- const type = field?.type ?? 'STRING';
191
- return [
192
- fieldName,
193
- {
194
- readOnly: false,
195
- ...(type === 'ENUM' && field && knownValues(field) ? { enum: knownValues(field) } : {}),
196
- description: '',
197
- genesisType: type,
198
- type: jsonTypeOf(type),
199
- },
200
- ];
201
- }),
233
+ requestFields.map((field) => [
234
+ field.name,
235
+ isNestedType(field.type)
236
+ ? nestedProperty(field)
237
+ : {
238
+ readOnly: false,
239
+ ...(field.type === 'ENUM' && knownValues(field) ? { enum: knownValues(field) } : {}),
240
+ description: '',
241
+ genesisType: field.type,
242
+ type: jsonTypeOf(field.type),
243
+ },
244
+ ]),
202
245
  );
203
246
  const request = { properties: requestProperties, additionalProperties: false, type: 'object' };
204
247
  // The reply block, else the source's fields then RECORD_ID and TIMESTAMP,
205
248
  // as REPLY_FIELD (see requestReplyReplySchema).
206
- const fields = requestReplyReplySchema(requestReply, config, store).fields;
249
+ const fields = typed
250
+ ? typedFields(typed.reply.fields)
251
+ : requestReplyReplySchema(requestReply, config, store).fields;
252
+ // The nested classes a typed server's reply $refs name.
253
+ const replyDefs = typed
254
+ ? jsonDefs(nestedClasses(fields), (nested) => dtoFields(nested.fields))
255
+ : {};
207
256
  return {
208
257
  INBOUND: {
209
258
  properties: {
@@ -216,7 +265,7 @@ function requestServerSchema(
216
265
  required: ['MESSAGE_TYPE', 'SOURCE_REF', 'USER_NAME', 'REQUEST'],
217
266
  additionalProperties: false,
218
267
  description: `GPAL Request definition for ${name}`,
219
- $defs: {},
268
+ $defs: typed ? inboundDefs(requestFields) : {},
220
269
  type: 'object',
221
270
  },
222
271
  OUTBOUND: {
@@ -240,10 +289,24 @@ function requestServerSchema(
240
289
  },
241
290
  required: ['MESSAGE_TYPE', 'SOURCE_REF'],
242
291
  additionalProperties: false,
292
+ ...(Object.keys(replyDefs).length > 0 ? { $defs: replyDefs } : {}),
243
293
  },
244
294
  };
245
295
  }
246
296
 
297
+ // A request server's reply row properties, as its OUTBOUND schema's
298
+ // REPLY.items gives them, or undefined when the config has no such server.
299
+ export function requestServerReplyProperties(
300
+ name: string,
301
+ config: MockServerConfig,
302
+ store: Store,
303
+ ): Row | undefined {
304
+ const requestReply = config.requestReplies?.[name];
305
+ if (!requestReply) return undefined;
306
+ return requestServerSchema(name, requestReply, config, store).OUTBOUND.properties.REPLY.items
307
+ .properties;
308
+ }
309
+
247
310
  // The FEATURE resolves, in order, as: an entry in config.eventSchemas, a
248
311
  // dataserver query, a request server (by resource name, without REQ_), an
249
312
  // EVENT_<TABLE>_<VERB> event, and finally a bare table name — the last is