@genesislcap/mock-server 15.7.3-alpha-94532c4.0 → 15.31.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 (72) hide show
  1. package/README.md +246 -40
  2. package/dist/db/criteria.d.ts +5 -0
  3. package/dist/db/criteria.js +327 -0
  4. package/dist/db/metadata.d.ts +3 -0
  5. package/dist/db/metadata.js +35 -0
  6. package/dist/db/store.d.ts +28 -0
  7. package/dist/db/store.js +254 -0
  8. package/dist/handlers/auth.d.ts +10 -0
  9. package/dist/handlers/auth.js +121 -0
  10. package/dist/handlers/commitEvent.d.ts +8 -0
  11. package/dist/handlers/commitEvent.js +40 -0
  12. package/dist/handlers/dataLogon.d.ts +5 -0
  13. package/dist/handlers/dataLogon.js +56 -0
  14. package/dist/handlers/heartbeat.d.ts +3 -0
  15. package/dist/handlers/heartbeat.js +16 -0
  16. package/dist/handlers/http.d.ts +4 -0
  17. package/dist/handlers/http.js +179 -0
  18. package/dist/handlers/jsonSchema.d.ts +5 -0
  19. package/dist/handlers/jsonSchema.js +94 -0
  20. package/dist/handlers/meta.d.ts +4 -0
  21. package/dist/handlers/meta.js +42 -0
  22. package/dist/handlers/requestReply.d.ts +4 -0
  23. package/dist/handlers/requestReply.js +68 -0
  24. package/dist/handlers/resourceAuth.d.ts +5 -0
  25. package/dist/handlers/resourceAuth.js +27 -0
  26. package/dist/handlers/resources.d.ts +3 -0
  27. package/dist/handlers/resources.js +34 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +5 -0
  30. package/dist/launch.d.ts +20 -0
  31. package/dist/launch.js +164 -0
  32. package/dist/protocol/connection.d.ts +25 -0
  33. package/dist/protocol/connection.js +36 -0
  34. package/dist/protocol/errors.d.ts +17 -0
  35. package/dist/protocol/errors.js +16 -0
  36. package/dist/protocol/messageTypes.d.ts +28 -0
  37. package/dist/protocol/messageTypes.js +42 -0
  38. package/dist/protocol/router.d.ts +6 -0
  39. package/dist/protocol/router.js +101 -0
  40. package/dist/protocol/rowUpdate.d.ts +4 -0
  41. package/dist/protocol/rowUpdate.js +17 -0
  42. package/dist/server.d.ts +23 -0
  43. package/dist/server.js +328 -0
  44. package/dist/types.d.ts +142 -0
  45. package/dist/types.js +4 -0
  46. package/package.json +16 -7
  47. package/src/db/criteria.ts +75 -21
  48. package/src/db/store.ts +126 -29
  49. package/src/handlers/auth.ts +32 -6
  50. package/src/handlers/commitEvent.ts +4 -1
  51. package/src/handlers/dataLogon.ts +23 -7
  52. package/src/handlers/heartbeat.ts +16 -3
  53. package/src/handlers/http.ts +43 -2
  54. package/src/handlers/jsonSchema.ts +21 -5
  55. package/src/handlers/meta.ts +11 -3
  56. package/src/handlers/requestReply.ts +22 -8
  57. package/src/handlers/resourceAuth.ts +37 -0
  58. package/src/handlers/resources.ts +8 -1
  59. package/src/index.ts +9 -0
  60. package/src/launch.ts +220 -0
  61. package/src/protocol/connection.ts +4 -1
  62. package/src/protocol/router.ts +2 -2
  63. package/src/protocol/rowUpdate.ts +5 -4
  64. package/src/server.ts +150 -22
  65. package/src/types.ts +124 -3
  66. package/license.txt +0 -46
  67. package/test/criteria.test.ts +0 -174
  68. package/test/jsonSchema.test.ts +0 -38
  69. package/test/metadata.test.ts +0 -49
  70. package/test/server.test.ts +0 -308
  71. package/test/store.test.ts +0 -181
  72. package/tsconfig.json +0 -18
@@ -0,0 +1,179 @@
1
+ import crypto from 'node:crypto';
2
+ import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
3
+ import { buildLoginAckBody, capRegistry, findUser, findUserByCredentials, registerAckTokens, } from "./auth.js";
4
+ const SESSION_COOKIE = 'MOCK_SESSION_ID';
5
+ const HTTP_STATUS = {
6
+ OK: 200,
7
+ UNAUTHORIZED: 401,
8
+ NOT_FOUND: 404,
9
+ INTERNAL_SERVER_ERROR: 500,
10
+ };
11
+ // foundation-auth's login UI (client-app-login) doesn't use the WebSocket
12
+ // EVENT_LOGIN_AUTH flow at all — it POSTs credentials over plain HTTP to
13
+ // gwf/event-login-auth, and separately GETs gwf/event-login-details on every
14
+ // app load (cookie-based silent login: foundation-comms/src/connect/
15
+ // sessionRefresh.ts's isAuthenticated()). Both expect the exact same ACK body
16
+ // shape as the WS login (EVENT_LOGIN_DETAILS_ACK literally extends
17
+ // EVENT_LOGIN_AUTH_ACK), just reached over HTTP with a session cookie instead
18
+ // of SOURCE_REF correlation. This is a *separate* transport from the WS
19
+ // protocol in server.ts — a client-app can use either, or (as here) both.
20
+ function parseCookies(header) {
21
+ const cookies = {};
22
+ for (const part of (header ?? '').split(';')) {
23
+ const [key, ...rest] = part.trim().split('=');
24
+ if (key)
25
+ cookies[key] = decodeURIComponent(rest.join('='));
26
+ }
27
+ return cookies;
28
+ }
29
+ function setSessionCookie(res, sessionId) {
30
+ res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`);
31
+ }
32
+ function sendJson(res, status, body) {
33
+ res.writeHead(status, { 'Content-Type': 'application/json' });
34
+ res.end(JSON.stringify(body));
35
+ }
36
+ const BYTES_PER_KB = 1024;
37
+ const MAX_BODY_KB = 1024;
38
+ const MAX_BODY_BYTES = MAX_BODY_KB * BYTES_PER_KB; // 1MB — logins/commits carry small payloads, this only guards against abuse
39
+ async function readJsonBody(req) {
40
+ const chunks = [];
41
+ let bytesRead = 0;
42
+ for await (const chunk of req) {
43
+ bytesRead += chunk.length;
44
+ if (bytesRead > MAX_BODY_BYTES) {
45
+ throw new Error('Request body size limit exceeded');
46
+ }
47
+ chunks.push(chunk);
48
+ }
49
+ const raw = Buffer.concat(chunks).toString('utf8');
50
+ return raw ? JSON.parse(raw) : {};
51
+ }
52
+ // Drops every token this server minted for `username`. Logout has to do this,
53
+ // not just forget the session: router.ts re-adopts any known SESSION_AUTH_TOKEN
54
+ // on every message, so a token left in the registry logs a WS connection
55
+ // straight back in on its next request.
56
+ function revokeTokensFor(tokens, username) {
57
+ for (const [token, owner] of tokens) {
58
+ if (owner === username)
59
+ tokens.delete(token);
60
+ }
61
+ }
62
+ // Reuse the request's own session when its cookie already maps to this user —
63
+ // otherwise every page load would mint (and leak) a fresh session entry on a
64
+ // long-lived dev/CI server.
65
+ function ensureSession(sessions, cookieSessionId, username) {
66
+ if (cookieSessionId && sessions.get(cookieSessionId) === username)
67
+ return cookieSessionId;
68
+ const sessionId = crypto.randomUUID();
69
+ sessions.set(sessionId, username);
70
+ capRegistry(sessions);
71
+ return sessionId;
72
+ }
73
+ export function createHttpRequestListener(config, sessions, tokens = new Map()) {
74
+ return async function requestListener(req, res) {
75
+ const pathname = (req.url ?? '').split('?')[0];
76
+ try {
77
+ // Project-defined routes run first (see HttpRouteDef) — endpoints the
78
+ // protocol doesn't cover (e.g. GET pbi/configs), or overrides of the
79
+ // built-ins below.
80
+ const route = (config.httpRoutes ?? []).find((candidate) => (!candidate.method || candidate.method.toUpperCase() === req.method) &&
81
+ (typeof candidate.path === 'string'
82
+ ? pathname.endsWith(candidate.path)
83
+ : candidate.path.test(pathname)));
84
+ if (route) {
85
+ await route.handler(req, res);
86
+ return;
87
+ }
88
+ // foundation-auth's login screen fetches this whenever SSO is toggled
89
+ // on, and treats both a failed fetch and an empty IDPS list as fatal
90
+ // (red error, credentials form hidden). Serve the configured providers,
91
+ // or one non-functional placeholder so the screen still renders.
92
+ if (req.method === 'GET' && pathname.endsWith('sso/list')) {
93
+ const idps = config.auth?.ssoIdentityProviders ?? [
94
+ { ID: 'mock-sso', DESCRIPTION: 'Mock SSO (placeholder, not functional)', TYPE: 'saml' },
95
+ ];
96
+ sendJson(res, HTTP_STATUS.OK, { IDPS: idps });
97
+ return;
98
+ }
99
+ // Cookie-based silent login on app load — auto-authenticates as the
100
+ // configured user when config.auth.httpAutoLogin is set, so the login
101
+ // screen never appears (matches how a real session cookie would behave
102
+ // once already logged in, but skips the manual login step entirely).
103
+ // Two different call sites hit this path with different methods:
104
+ // foundation-auth's fetch machine always POSTs (createFetchMachineEvent
105
+ // hardcodes method: 'POST') on initial silent-login; foundation-comms'
106
+ // sessionRefresh.ts's isAuthenticated() does a plain GET later, when
107
+ // checking whether an expired session can be silently renewed.
108
+ if ((req.method === 'GET' || req.method === 'POST') &&
109
+ pathname.endsWith('event-login-details')) {
110
+ const autoLoginUsername = config.auth?.httpAutoLogin;
111
+ const cookies = parseCookies(req.headers.cookie);
112
+ const user = autoLoginUsername
113
+ ? findUser(config, autoLoginUsername === true ? config.auth?.users?.[0]?.username : autoLoginUsername)
114
+ : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
115
+ if (!user) {
116
+ sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
117
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
118
+ ERROR: [
119
+ { CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
120
+ ],
121
+ });
122
+ return;
123
+ }
124
+ const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
125
+ setSessionCookie(res, sessionId);
126
+ const ack = buildLoginAckBody(user, config, 'EVENT_LOGIN_DETAILS_ACK');
127
+ registerAckTokens(ack, user.username, tokens);
128
+ sendJson(res, HTTP_STATUS.OK, ack);
129
+ return;
130
+ }
131
+ if (req.method === 'POST' && pathname.endsWith('event-login-auth')) {
132
+ const body = await readJsonBody(req);
133
+ const details = body.DETAILS ?? {};
134
+ const cookies = parseCookies(req.headers.cookie);
135
+ // Empty DETAILS means a session-refresh ping (foundation-comms'
136
+ // sessionRefresh.performRefresh), not a fresh credentials login —
137
+ // honor it only if the request already carries a known session.
138
+ const user = details.USER_NAME !== undefined
139
+ ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
140
+ : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
141
+ if (!user) {
142
+ sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
143
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
144
+ ERROR: [
145
+ {
146
+ CODE: 'INCORRECT_CREDENTIALS',
147
+ STATUS_CODE: '401 Unauthorized',
148
+ TEXT: 'Problem logging in',
149
+ },
150
+ ],
151
+ WARNING: [],
152
+ });
153
+ return;
154
+ }
155
+ const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
156
+ setSessionCookie(res, sessionId);
157
+ const ack = buildLoginAckBody(user, config);
158
+ registerAckTokens(ack, user.username, tokens);
159
+ sendJson(res, HTTP_STATUS.OK, ack);
160
+ return;
161
+ }
162
+ if (req.method === 'POST' && pathname.endsWith('event-logout')) {
163
+ const cookies = parseCookies(req.headers.cookie);
164
+ const sessionId = cookies[SESSION_COOKIE];
165
+ const username = sessions.get(sessionId);
166
+ sessions.delete(sessionId);
167
+ if (username !== undefined)
168
+ revokeTokensFor(tokens, username);
169
+ sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
170
+ return;
171
+ }
172
+ res.writeHead(HTTP_STATUS.NOT_FOUND).end();
173
+ }
174
+ catch (error) {
175
+ console.error('[mock-server] HTTP handler error:', error);
176
+ res.writeHead(HTTP_STATUS.INTERNAL_SERVER_ERROR).end();
177
+ }
178
+ };
179
+ }
@@ -0,0 +1,5 @@
1
+ import type { Store } from '../db/store.ts';
2
+ import type { Connection } from '../protocol/connection.ts';
3
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
4
+ export declare function inferEventTable(eventName: string | undefined, tableNames: string[]): string | undefined;
5
+ export declare function handleJsonSchemaRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
@@ -0,0 +1,94 @@
1
+ import { deriveFields } from "../db/metadata.js";
2
+ import { ERROR_CODE } from "../protocol/messageTypes.js";
3
+ // JSON_SCHEMA_REQUEST shares its request envelope with META_REQUEST (same
4
+ // DETAILS.FEATURE resource-name field) but its reply is a completely
5
+ // different shape: Connect.getJSONSchema doesn't read response.DETAILS at
6
+ // all — the response *is* the SchemaResponse ({ INBOUND, OUTBOUND }, each a
7
+ // draft-07 JSON Schema). @genesislcap/foundation-entity-management's
8
+ // <entity-management> calls this for every create/update form (fields come
9
+ // from INBOUND.properties.DETAILS.properties) and for delete confirmation
10
+ // (it reads Object.keys(...properties) to know which fields to copy from the
11
+ // selected row into the commit DETAILS). Route this to handleMetaRequest by
12
+ // mistake and forms silently render with zero fields, and delete can never
13
+ // build a payload — no error, just a dead button.
14
+ function jsonSchemaType(fieldType) {
15
+ switch (fieldType) {
16
+ case 'LONG':
17
+ return 'integer';
18
+ case 'DOUBLE':
19
+ return 'number';
20
+ case 'BOOLEAN':
21
+ return 'boolean';
22
+ default:
23
+ return 'string';
24
+ }
25
+ }
26
+ function buildSchema(fields, required) {
27
+ const properties = {};
28
+ for (const field of fields) {
29
+ properties[field.NAME] = { type: jsonSchemaType(field.TYPE) };
30
+ }
31
+ return {
32
+ type: 'object',
33
+ properties: {
34
+ DETAILS: { type: 'object', properties, required },
35
+ },
36
+ };
37
+ }
38
+ const DELETE_EVENT_RE = /_DELETE(_|$)/;
39
+ // Zero-config default: EVENT_<TABLE>_<VERB...> maps to <TABLE> if it's a
40
+ // registered table name (longest match wins, so e.g. a hypothetical
41
+ // COUNTERPARTY_AUTH table can't shadow COUNTERPARTY). Covers every event
42
+ // naming pattern in this codebase (INSERT, MODIFY, DELETE, plus suffixed
43
+ // variants like INSERT_WITH_APPROVAL, DEMO_INSERT, MODIFY_PRICE, INSERT_FAIL)
44
+ // without hand-maintaining a table per event. Override via
45
+ // config.eventSchemas for names that don't follow this convention.
46
+ // Exported for unit tests only.
47
+ export function inferEventTable(eventName, tableNames) {
48
+ if (!eventName)
49
+ return undefined;
50
+ // Not every caller asks by event name: entity-management resolves a grid's
51
+ // schema from the bare resource/table name (FEATURE: 'TRADE'), so accept an
52
+ // exact table match before requiring the EVENT_ prefix. Without this the
53
+ // request errors with UNKNOWN_RESOURCE and the form renders no fields.
54
+ if (tableNames.includes(eventName))
55
+ return eventName;
56
+ if (!eventName.startsWith('EVENT_'))
57
+ return undefined;
58
+ const rest = eventName.slice('EVENT_'.length);
59
+ const candidates = tableNames.filter((name) => rest === name || rest.startsWith(`${name}_`));
60
+ candidates.sort((a, b) => b.length - a.length);
61
+ return candidates[0];
62
+ }
63
+ export function handleJsonSchemaRequest(message, connection, config, store) {
64
+ const eventName = message.DETAILS?.FEATURE;
65
+ const override = eventName ? config.eventSchemas?.[eventName] : undefined;
66
+ // A DATASERVER/REQUEST_SERVER resource name (e.g. 'ALL_USERS') resolves
67
+ // through its own definition to the backing table/view. The FAST-Element
68
+ // showcase's entity-management grids ask by query name, not by table or
69
+ // event name, so without this their create/update forms render empty.
70
+ const resourceSource = eventName
71
+ ? (config.queries?.[eventName]?.source ?? config.requestReplies?.[eventName]?.source)
72
+ : undefined;
73
+ const table = override?.table ??
74
+ resourceSource ??
75
+ inferEventTable(eventName, Object.keys(config.tables ?? {}));
76
+ if (!table) {
77
+ connection.reply(message, {
78
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
79
+ ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown resource: ${eventName}` }],
80
+ });
81
+ return;
82
+ }
83
+ const pkOnly = override?.pkOnly ?? DELETE_EVENT_RE.test(eventName);
84
+ const pkFields = store.getPkFields(table);
85
+ let fields = deriveFields(store.getMetadataRows(table), override?.fieldTypes);
86
+ if (pkOnly)
87
+ fields = fields.filter((field) => pkFields.includes(field.NAME));
88
+ const schema = buildSchema(fields, pkOnly ? pkFields : []);
89
+ connection.reply(message, {
90
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
91
+ INBOUND: schema,
92
+ OUTBOUND: schema,
93
+ });
94
+ }
@@ -0,0 +1,4 @@
1
+ import type { Store } from '../db/store.ts';
2
+ import type { Connection } from '../protocol/connection.ts';
3
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
4
+ export declare function handleMetaRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
@@ -0,0 +1,42 @@
1
+ import { deriveFields } from "../db/metadata.js";
2
+ import { ERROR_CODE } from "../protocol/messageTypes.js";
3
+ import { hiddenFields, requestingUser } from "./resourceAuth.js";
4
+ // createMetaRequestMessage (foundation-comms/src/connect/message.ts) puts the
5
+ // resource name in DETAILS.FEATURE — not DATASOURCE_NAME/RESOURCE_NAME despite
6
+ // what every other message type in this protocol would suggest.
7
+ function resolveResourceName(message) {
8
+ return (message.DETAILS?.FEATURE ?? message.DETAILS?.DATASOURCE_NAME ?? message.DETAILS?.RESOURCE_NAME);
9
+ }
10
+ // Connect.getMetadata reads metaResponse.DETAILS (not the top-level message)
11
+ // and extractFieldDefinitions (metadata.utils.ts) branches on DETAILS.TYPE:
12
+ // DATASERVER resources need DETAILS.FIELD, REQUEST_SERVER ones need
13
+ // DETAILS.REPLY_FIELD. Get either wrong and every grid silently reports
14
+ // "Metadata Fetch failed" / "Unsupported resource type: undefined".
15
+ export function handleMetaRequest(message, connection, config, store) {
16
+ const resourceName = resolveResourceName(message);
17
+ const query = config.queries?.[resourceName];
18
+ const requestReply = config.requestReplies?.[resourceName];
19
+ if (!query && !requestReply) {
20
+ connection.reply(message, {
21
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
22
+ ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown resource: ${resourceName}` }],
23
+ });
24
+ return;
25
+ }
26
+ const resolved = (query ?? requestReply);
27
+ // Resolver-only request-replies have no backing table/view — their field
28
+ // metadata comes from the def's own metadataRows sample (plus fieldTypes).
29
+ const rows = resolved.source
30
+ ? store.getMetadataRows(resolved.source)
31
+ : (requestReply?.metadataRows ?? []);
32
+ // Hidden fields disappear from the metadata too — a column the user can't
33
+ // see must not be offered to the grid at all.
34
+ const hidden = hiddenFields(resolved.auth, requestingUser(connection));
35
+ const fields = deriveFields(rows, resolved.fieldTypes).filter((field) => !hidden.has(field.NAME));
36
+ connection.reply(message, {
37
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
38
+ DETAILS: query
39
+ ? { NAME: resourceName, TYPE: 'DATASERVER', FIELD: fields, KEY: [] }
40
+ : { NAME: resourceName, TYPE: 'REQUEST_SERVER', REPLY_FIELD: fields },
41
+ });
42
+ }
@@ -0,0 +1,4 @@
1
+ import type { Store } from '../db/store.ts';
2
+ import type { Connection } from '../protocol/connection.ts';
3
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
4
+ export declare function handleRequestReply(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
@@ -0,0 +1,68 @@
1
+ import { filterByCriteria } from "../db/criteria.js";
2
+ import { NackError } from "../protocol/errors.js";
3
+ import { ERROR_CODE } from "../protocol/messageTypes.js";
4
+ import { applyResourceAuth, requestingUser } from "./resourceAuth.js";
5
+ // Keyed lookups: foundation-comms' createRequestMessage spreads RequestParams
6
+ // onto the message, so REQUEST is a *top-level* field ({FIELD: value} pairs
7
+ // naming the request server's index fields). A real request server only
8
+ // returns rows matching them; '*' (Genesis's wildcard), null/undefined, and
9
+ // '' mean "any". Arrays match any listed value.
10
+ function matchesRequestFields(row, request) {
11
+ return Object.entries(request).every(([field, value]) => {
12
+ if (value === undefined || value === null || value === '*' || value === '')
13
+ return true;
14
+ if (Array.isArray(value))
15
+ return value.length === 0 || value.includes(row[field]);
16
+ return row[field] === value;
17
+ });
18
+ }
19
+ export function handleRequestReply(message, connection, config, store) {
20
+ const resourceName = message.MESSAGE_TYPE.replace(/^REQ_/, '');
21
+ const requestReply = config.requestReplies?.[resourceName];
22
+ if (!requestReply || (!requestReply.resolver && !requestReply.source)) {
23
+ connection.reply(message, {
24
+ MESSAGE_TYPE: `REP_${resourceName}`,
25
+ ERROR: [
26
+ {
27
+ CODE: ERROR_CODE.UNKNOWN_RESOURCE,
28
+ TEXT: `Unknown request-reply resource: ${resourceName}`,
29
+ },
30
+ ],
31
+ });
32
+ return;
33
+ }
34
+ const user = requestingUser(connection);
35
+ const request = (typeof message.REQUEST === 'object' && message.REQUEST) || message.DETAILS?.REQUEST || {};
36
+ try {
37
+ let rows;
38
+ if (requestReply.resolver) {
39
+ // Computed reply (date calcs, holiday roll, composite lookups...): the
40
+ // resolver owns REQUEST interpretation entirely — no generic REQUEST/
41
+ // CRITERIA filtering is applied on top, since a computed reply's rows
42
+ // needn't echo the request's fields at all.
43
+ rows = requestReply.resolver({ request, message, user, store });
44
+ }
45
+ else {
46
+ rows = store.getResourceRows(requestReply.source);
47
+ if (Object.keys(request).length > 0) {
48
+ rows = rows.filter((row) => matchesRequestFields(row, request));
49
+ }
50
+ const criteria = message.DETAILS?.CRITERIA_MATCH ?? message.CRITERIA_MATCH;
51
+ if (criteria)
52
+ rows = filterByCriteria(rows, criteria);
53
+ if (requestReply.filter)
54
+ rows = rows.filter(requestReply.filter);
55
+ }
56
+ rows = applyResourceAuth(rows, requestReply.auth, user);
57
+ connection.reply(message, {
58
+ MESSAGE_TYPE: `REP_${resourceName}`,
59
+ REPLY: rows,
60
+ });
61
+ }
62
+ catch (error) {
63
+ const errors = error instanceof NackError
64
+ ? error.errors
65
+ : [{ CODE: ERROR_CODE.VALIDATION_ERROR, TEXT: error.message }];
66
+ connection.reply(message, { MESSAGE_TYPE: `REP_${resourceName}`, ERROR: errors });
67
+ }
68
+ }
@@ -0,0 +1,5 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import type { ResourceAuthDef, RequestingUser, Row } from '../types.ts';
3
+ export declare function requestingUser(connection: Connection): RequestingUser;
4
+ export declare function hiddenFields(auth: ResourceAuthDef | undefined, user: RequestingUser): Set<string>;
5
+ export declare function applyResourceAuth(rows: Row[], auth: ResourceAuthDef | undefined, user: RequestingUser): Row[];
@@ -0,0 +1,27 @@
1
+ // The identity a resource-level auth hook (rowFilter/hideFields) sees for the
2
+ // requesting connection. userName is undefined for unauthenticated
3
+ // connections — possible when requireAuth is off, or pre-login.
4
+ export function requestingUser(connection) {
5
+ return {
6
+ userName: connection.userName,
7
+ profile: connection.profile,
8
+ permission: connection.permission,
9
+ };
10
+ }
11
+ export function hiddenFields(auth, user) {
12
+ const fields = typeof auth?.hideFields === 'function' ? auth.hideFields(user) : auth?.hideFields;
13
+ return new Set(fields ?? []);
14
+ }
15
+ // Applies a resource's permissioning to a reply/snapshot row set: drops rows
16
+ // the user's rowFilter rejects, then strips hidden fields from what's left.
17
+ // Mirrors dataserver auth maps + hideFields on the real server.
18
+ export function applyResourceAuth(rows, auth, user) {
19
+ if (!auth)
20
+ return rows;
21
+ let result = auth.rowFilter ? rows.filter((row) => auth.rowFilter(row, user)) : rows;
22
+ const hidden = hiddenFields(auth, user);
23
+ if (hidden.size > 0) {
24
+ result = result.map((row) => Object.fromEntries(Object.entries(row).filter(([field]) => !hidden.has(field))));
25
+ }
26
+ return result;
27
+ }
@@ -0,0 +1,3 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
3
+ export declare function handleResourcesRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig): void;
@@ -0,0 +1,34 @@
1
+ import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
2
+ // GenesisResources (foundation-comms/src/resources/genesis/genesis.ts) gates
3
+ // every datasource/request-reply/commit call on this list first — an empty
4
+ // or missing RESOURCES_REQUEST_ACK.RESOURCES makes every resource silently
5
+ // "not exist" client-side, before META_REQUEST or DATA_LOGON is ever tried.
6
+ // Auto-derive it from config.queries/requestReplies/eventHandlers (same
7
+ // philosophy as db/metadata.ts's field inference) so projects don't have to
8
+ // hand-maintain a redundant list; set config.resources explicitly to override.
9
+ function deriveResources(config) {
10
+ const resources = [];
11
+ for (const name of Object.keys(config.queries ?? {})) {
12
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'DATASERVER' });
13
+ }
14
+ for (const name of Object.keys(config.requestReplies ?? {})) {
15
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'REQUEST_SERVER' });
16
+ }
17
+ const eventNames = new Set([
18
+ ...Object.keys(config.eventHandlers ?? {}),
19
+ // Events served only by eventSchemas + defaultEventHandler still need to
20
+ // be discoverable, or the client-side resource gate blocks them before
21
+ // the commit is ever sent.
22
+ ...Object.keys(config.eventSchemas ?? {}),
23
+ ]);
24
+ for (const name of eventNames) {
25
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'EVENT_HANDLER' });
26
+ }
27
+ return resources;
28
+ }
29
+ export function handleResourcesRequest(message, connection, config) {
30
+ connection.reply(message, {
31
+ MESSAGE_TYPE: MESSAGE_TYPE.RESOURCES_REQUEST_ACK,
32
+ RESOURCES: config.resources ?? deriveResources(config),
33
+ });
34
+ }
@@ -0,0 +1,6 @@
1
+ export { createMockServer, type MockServer } from './server.ts';
2
+ export { launchStack, type LaunchStackOptions, type LaunchedStack } from './launch.ts';
3
+ export { Store } from './db/store.ts';
4
+ export { NackError, type NackErrorInput, type NackErrorEntry } from './protocol/errors.ts';
5
+ export { compileCriteria, filterByCriteria, type Predicate } from './db/criteria.ts';
6
+ export type { AntiJoinDef, AuthConfig, AuthUser, BroadcastFn, BroadcastTableChangeFn, EventHandler, EventHandlerCtx, EventHandlerResult, EventSchemaOverride, FieldMetadata, GenesisMessage, HttpRouteDef, JoinDef, MockServerConfig, OnMessageCtx, OnMessageHook, QueryDef, RequestingUser, RequestReplyDef, RequestReplyResolverCtx, ResourceAuthDef, ResourceItem, Row, SocketLike, SsoIdentityProvider, TableDef, ViewDef, } from './types.ts';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { createMockServer } from "./server.js";
2
+ export { launchStack } from "./launch.js";
3
+ export { Store } from "./db/store.js";
4
+ export { NackError } from "./protocol/errors.js";
5
+ export { compileCriteria, filterByCriteria } from "./db/criteria.js";
@@ -0,0 +1,20 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ import { type MockServer } from './server.ts';
3
+ import type { MockServerConfig } from './types.ts';
4
+ export interface LaunchStackOptions {
5
+ config: MockServerConfig;
6
+ clientCommand: string | string[];
7
+ port?: number;
8
+ cwd?: string;
9
+ clientEnv?: (port: number) => Record<string, string>;
10
+ tieLifetimes?: boolean;
11
+ clientExitGraceMs?: number;
12
+ }
13
+ export interface LaunchedStack {
14
+ server: MockServer;
15
+ port: number;
16
+ client: ChildProcess;
17
+ clientExited: Promise<number | null>;
18
+ stop(): Promise<void>;
19
+ }
20
+ export declare function launchStack(options: LaunchStackOptions): Promise<LaunchedStack>;