@genesislcap/mock-server 15.3.2-canary.16

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.
@@ -0,0 +1,173 @@
1
+ // In-memory tables + views + sequence generation. No persistence, no external deps.
2
+ // This is the "database" — disposable and rebuilt from seed data on every server start.
3
+
4
+ import type { Row, TableDef, ViewDef } from '../types.ts';
5
+
6
+ type Pk = string;
7
+
8
+ interface TableConfig {
9
+ pkField: string;
10
+ sequencePrefix?: string;
11
+ sequenceWidth: number;
12
+ }
13
+
14
+ export class Store {
15
+ private tables = new Map<string, Map<Pk, Row>>();
16
+ private tableConfig = new Map<string, TableConfig>();
17
+ private sequenceCounters = new Map<string, number>();
18
+ readonly views = new Map<string, ViewDef>();
19
+
20
+ registerTable(
21
+ tableName: string,
22
+ { pkField, sequencePrefix, sequenceWidth = 3, rows = [] }: TableDef,
23
+ ): this {
24
+ const table = new Map<Pk, Row>();
25
+ for (const row of rows) {
26
+ table.set(row[pkField], { ...row });
27
+ }
28
+ this.tables.set(tableName, table);
29
+ this.tableConfig.set(tableName, { pkField, sequencePrefix, sequenceWidth });
30
+
31
+ if (sequencePrefix) {
32
+ let maxN = 0;
33
+ for (const row of rows) {
34
+ const pk = String(row[pkField] ?? '');
35
+ if (pk.startsWith(sequencePrefix)) {
36
+ const n = parseInt(pk.slice(sequencePrefix.length), 10);
37
+ if (Number.isFinite(n)) maxN = Math.max(maxN, n);
38
+ }
39
+ }
40
+ this.sequenceCounters.set(sequencePrefix, maxN + 1);
41
+ }
42
+ return this;
43
+ }
44
+
45
+ registerView(viewName: string, definition: ViewDef): this {
46
+ this.views.set(viewName, definition);
47
+ return this;
48
+ }
49
+
50
+ nextSequenceValue(sequencePrefix: string, width: number): string {
51
+ const n = this.sequenceCounters.get(sequencePrefix) ?? 1;
52
+ this.sequenceCounters.set(sequencePrefix, n + 1);
53
+ return `${sequencePrefix}${String(n).padStart(width, '0')}`;
54
+ }
55
+
56
+ getAllRows(tableName: string): Row[] {
57
+ const table = this.tables.get(tableName);
58
+ if (!table) return [];
59
+ return Array.from(table.values());
60
+ }
61
+
62
+ getRow(tableName: string, pk: Pk): Row | undefined {
63
+ return this.tables.get(tableName)?.get(pk);
64
+ }
65
+
66
+ // Fallback matching for composite-key tables where no single field is a stable
67
+ // identifier: try ROW_REF/pk field first, then any single field that uniquely
68
+ // identifies one row, then the full combination of provided fields.
69
+ findRow(tableName: string, criteria: Row): Row | undefined {
70
+ const table = this.tables.get(tableName);
71
+ if (!table) return undefined;
72
+ const { pkField } = this.tableConfig.get(tableName) ?? {};
73
+
74
+ if (pkField && criteria[pkField] !== undefined) {
75
+ return table.get(criteria[pkField]);
76
+ }
77
+
78
+ const rows = Array.from(table.values());
79
+ const matchesAllCriteria = (row: Row) =>
80
+ Object.entries(criteria).every(([field, value]) => row[field] === value);
81
+ for (const [field, value] of Object.entries(criteria)) {
82
+ const matches = rows.filter((row) => row[field] === value);
83
+ if (matches.length === 1 && matchesAllCriteria(matches[0])) return matches[0];
84
+ }
85
+
86
+ return rows.find(matchesAllCriteria);
87
+ }
88
+
89
+ insertRow(tableName: string, record: Row): Row {
90
+ const table = this.tables.get(tableName);
91
+ const config = this.tableConfig.get(tableName);
92
+ if (!table || !config) throw new Error(`Unknown table: ${tableName}`);
93
+
94
+ const row = { ...record };
95
+ if (row[config.pkField] === undefined && config.sequencePrefix) {
96
+ row[config.pkField] = this.nextSequenceValue(config.sequencePrefix, config.sequenceWidth);
97
+ }
98
+ if (row[config.pkField] === undefined) {
99
+ throw new Error(
100
+ `Primary key '${config.pkField}' is required for inserting into table '${tableName}'`,
101
+ );
102
+ }
103
+ table.set(row[config.pkField], row);
104
+ return row;
105
+ }
106
+
107
+ updateRow(tableName: string, pk: Pk, patch: Row): Row | undefined {
108
+ const table = this.tables.get(tableName);
109
+ if (!table || !table.has(pk)) return undefined;
110
+ const updated = { ...table.get(pk), ...patch };
111
+ table.set(pk, updated);
112
+ return updated;
113
+ }
114
+
115
+ deleteRow(tableName: string, pk: Pk): boolean {
116
+ const table = this.tables.get(tableName);
117
+ if (!table) return false;
118
+ return table.delete(pk);
119
+ }
120
+
121
+ // Materializes a view: base table left-joined to related tables, plus derived fields.
122
+ getViewRows(viewName: string): Row[] {
123
+ const view = this.views.get(viewName);
124
+ if (!view) throw new Error(`Unknown view: ${viewName}`);
125
+
126
+ let rows = this.getAllRows(view.base).map((row) => ({ ...row }));
127
+
128
+ for (const join of view.joins ?? []) {
129
+ const joinTable = this.tables.get(join.table);
130
+ const joinIndex = new Map<unknown, Row>();
131
+ if (joinTable) {
132
+ for (const row of joinTable.values()) {
133
+ joinIndex.set(row[join.on[1]], row);
134
+ }
135
+ }
136
+ rows = rows.map((row) => {
137
+ const match = joinIndex.get(row[join.on[0]]);
138
+ const merged = { ...row };
139
+ for (const [alias, sourceField] of Object.entries(join.select ?? {})) {
140
+ merged[alias] = match?.[sourceField];
141
+ }
142
+ return merged;
143
+ });
144
+ }
145
+
146
+ if (view.derived) {
147
+ rows = rows.map((row) => {
148
+ const merged = { ...row };
149
+ for (const [field, compute] of Object.entries(view.derived!)) {
150
+ merged[field] = compute(row);
151
+ }
152
+ return merged;
153
+ });
154
+ }
155
+
156
+ return rows;
157
+ }
158
+
159
+ // Resolves a queryable resource (table or view) by name to its current rows.
160
+ getResourceRows(resourceName: string): Row[] {
161
+ if (this.views.has(resourceName)) return this.getViewRows(resourceName);
162
+ return this.getAllRows(resourceName);
163
+ }
164
+
165
+ // Row-identity field for a table or view, used to stamp DETAILS.ROW_REF on
166
+ // QUERY_UPDATE rows (see handlers/dataLogon.ts and dataServerResultFilter.ts
167
+ // client-side, which keys inserts/amends/deletes off this field).
168
+ getPkField(resourceName: string): string | undefined {
169
+ const view = this.views.get(resourceName);
170
+ if (view) return view.pkField ?? this.tableConfig.get(view.base)?.pkField;
171
+ return this.tableConfig.get(resourceName)?.pkField;
172
+ }
173
+ }
@@ -0,0 +1,91 @@
1
+ import crypto from 'node:crypto';
2
+ import type { Connection } from '../protocol/connection.ts';
3
+ import { MESSAGE_TYPE, ERROR_CODE } from '../protocol/messageTypes.ts';
4
+ import type { AuthUser, GenesisMessage, MockServerConfig, Row } from '../types.ts';
5
+
6
+ const DEFAULT_HEARTBEAT_INTERVAL_SECS = 30;
7
+
8
+ // Shared by the WS EVENT_LOGIN_AUTH handler and the HTTP login handlers
9
+ // (handlers/http.ts) — EVENT_LOGIN_DETAILS_ACK is byte-for-byte the same shape
10
+ // as EVENT_LOGIN_AUTH_ACK, just under a different MESSAGE_TYPE (see
11
+ // foundation-auth's EVENT_LOGIN_DETAILS_ACK.ts, which literally extends it).
12
+ export function buildLoginAckBody(
13
+ user: AuthUser,
14
+ config: MockServerConfig,
15
+ messageType: string = MESSAGE_TYPE.EVENT_LOGIN_AUTH_ACK,
16
+ ): Row {
17
+ return {
18
+ MESSAGE_TYPE: messageType,
19
+ SESSION_AUTH_TOKEN: crypto.randomUUID(),
20
+ REFRESH_AUTH_TOKEN: crypto.randomUUID(),
21
+ SESSION_ID: crypto.randomUUID(),
22
+ USER_NAME: user.username,
23
+ UPDATE_QUEUE: 'MOCK',
24
+ ZERO_MQ_PROXY_MODE_ENABLED: false,
25
+ ZERO_MQ_PROXY_INBOUND_PORT: 0,
26
+ ZERO_MQ_PROXY_OUTBOUND_PORT: 0,
27
+ USER: user.user ?? {},
28
+ DETAILS: {
29
+ SYSTEM: { DATE: new Date().toISOString() },
30
+ HEARTBEAT_INTERVAL_SECS:
31
+ config.auth?.heartbeatIntervalSecs ?? DEFAULT_HEARTBEAT_INTERVAL_SECS,
32
+ FAILED_LOGIN_ATTEMPTS: 0,
33
+ REJECTED_LOGIN_ATTEMPTS: 0,
34
+ LAST_LOGIN_DATETIME: 0,
35
+ DAYS_TO_PASSWORD_EXPIRY: -1,
36
+ PRODUCT: [{ NAME: config.productName ?? 'mock-server', VERSION: '0.1.0' }],
37
+ },
38
+ PERMISSION: user.permission ?? [],
39
+ PROFILE: user.profile ?? [],
40
+ };
41
+ }
42
+
43
+ export function findUser(
44
+ config: MockServerConfig,
45
+ username?: string,
46
+ password?: string,
47
+ ): AuthUser | undefined {
48
+ const users = config.auth?.users ?? [];
49
+ if (password === undefined) return users.find((u) => u.username === username);
50
+ return users.find((u) => u.username === username && u.password === password);
51
+ }
52
+
53
+ export function handleLogin(
54
+ message: GenesisMessage,
55
+ connection: Connection,
56
+ config: MockServerConfig,
57
+ ): void {
58
+ const details = message.DETAILS ?? {};
59
+ const user = findUser(config, details.USER_NAME, details.PASSWORD);
60
+
61
+ if (!user) {
62
+ connection.reply(message, {
63
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
64
+ ERROR: [
65
+ {
66
+ CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
67
+ STATUS_CODE: '401',
68
+ TEXT: 'Incorrect username or password',
69
+ },
70
+ ],
71
+ WARNING: [],
72
+ });
73
+ return;
74
+ }
75
+
76
+ const ack = buildLoginAckBody(user, config);
77
+ connection.authenticated = true;
78
+ connection.userName = user.username;
79
+ connection.profile = user.profile ?? [];
80
+ connection.permission = user.permission ?? [];
81
+ connection.sessionAuthToken = ack.SESSION_AUTH_TOKEN;
82
+ connection.sessionId = ack.SESSION_ID;
83
+
84
+ connection.reply(message, ack);
85
+ }
86
+
87
+ export function handleLogout(message: GenesisMessage, connection: Connection): void {
88
+ connection.authenticated = false;
89
+ connection.subscriptions.clear();
90
+ connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK });
91
+ }
@@ -0,0 +1,54 @@
1
+ import type { Store } from '../db/store.ts';
2
+ import type { Connection } from '../protocol/connection.ts';
3
+ import { NackError } from '../protocol/errors.ts';
4
+ import { ERROR_CODE } from '../protocol/messageTypes.ts';
5
+ import type {
6
+ BroadcastFn,
7
+ BroadcastTableChangeFn,
8
+ GenesisMessage,
9
+ MockServerConfig,
10
+ } from '../types.ts';
11
+
12
+ export interface CommitEventCtx {
13
+ broadcast: BroadcastFn;
14
+ broadcastTableChange: BroadcastTableChangeFn;
15
+ }
16
+
17
+ // Commit events (EVENT_<ENTITY>_INSERT/_AMEND/_DELETE, or whatever suffix
18
+ // convention your project uses) are looked up by exact MESSAGE_TYPE against
19
+ // config.eventHandlers. A handler receives (details, ctx) and either returns
20
+ // { generated?: [...] } on success, or throws NackError(errors) on failure.
21
+ export function handleCommitEvent(
22
+ message: GenesisMessage,
23
+ connection: Connection,
24
+ config: MockServerConfig,
25
+ store: Store,
26
+ ctx: CommitEventCtx,
27
+ ): void {
28
+ const eventName = message.MESSAGE_TYPE;
29
+ const handler = config.eventHandlers?.[eventName];
30
+
31
+ if (!handler) {
32
+ connection.reply(message, {
33
+ MESSAGE_TYPE: `${eventName}_NACK`,
34
+ ERROR: [
35
+ { CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `No event handler registered for ${eventName}` },
36
+ ],
37
+ });
38
+ return;
39
+ }
40
+
41
+ try {
42
+ const result = handler(message.DETAILS ?? {}, { connection, store, message, ...ctx }) ?? {};
43
+ connection.reply(message, {
44
+ MESSAGE_TYPE: `${eventName}_ACK`,
45
+ GENERATED: result.generated ?? [],
46
+ });
47
+ } catch (error) {
48
+ const errors =
49
+ error instanceof NackError
50
+ ? error.errors
51
+ : [{ CODE: ERROR_CODE.VALIDATION_ERROR, TEXT: (error as Error).message }];
52
+ connection.reply(message, { MESSAGE_TYPE: `${eventName}_NACK`, ERROR: errors });
53
+ }
54
+ }
@@ -0,0 +1,52 @@
1
+ import { compileCriteria, filterByCriteria } from '../db/criteria.ts';
2
+ import type { Store } from '../db/store.ts';
3
+ import type { Connection } from '../protocol/connection.ts';
4
+ import { MESSAGE_TYPE, ERROR_CODE } from '../protocol/messageTypes.ts';
5
+ import { stampRows } from '../protocol/rowUpdate.ts';
6
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
7
+
8
+ // DATA_LOGON opens a persistent subscription keyed by SOURCE_REF: reply with an
9
+ // initial snapshot, then keep the SOURCE_REF registered so later inserts/amends/
10
+ // deletes on this resource can be pushed on the same channel (see server.ts
11
+ // broadcast()) until the client sends DATA_LOGOFF.
12
+ export function handleDataLogon(
13
+ message: GenesisMessage,
14
+ connection: Connection,
15
+ config: MockServerConfig,
16
+ store: Store,
17
+ ): void {
18
+ const details = message.DETAILS ?? {};
19
+ const resourceName = details.DATASOURCE_NAME;
20
+ const query = config.queries?.[resourceName];
21
+
22
+ if (!query) {
23
+ connection.reply(message, {
24
+ MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
25
+ ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown datasource: ${resourceName}` }],
26
+ });
27
+ return;
28
+ }
29
+
30
+ const criteria = details.CRITERIA_MATCH;
31
+ const pkField = store.getPkField(query.source);
32
+ const rows = filterByCriteria(store.getResourceRows(query.source), criteria);
33
+
34
+ connection.subscribe(message.SOURCE_REF!, {
35
+ resourceName,
36
+ pkField,
37
+ predicate: compileCriteria(criteria),
38
+ sequenceId: 1,
39
+ });
40
+
41
+ connection.reply(message, {
42
+ MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
43
+ ROW: stampRows(rows, pkField, 'INSERT'),
44
+ ROWS_COUNT: rows.length,
45
+ SEQUENCE_ID: 1,
46
+ MORE_ROWS: false,
47
+ });
48
+ }
49
+
50
+ export function handleDataLogoff(message: GenesisMessage, connection: Connection): void {
51
+ connection.unsubscribe(message.SOURCE_REF!);
52
+ }
@@ -0,0 +1,10 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
3
+ import type { GenesisMessage } from '../types.ts';
4
+
5
+ export function handleHeartbeat(message: GenesisMessage, connection: Connection): void {
6
+ connection.reply(message, {
7
+ MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
8
+ IS_AUTHENTICATED: connection.authenticated,
9
+ });
10
+ }
@@ -0,0 +1,153 @@
1
+ import crypto from 'node:crypto';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
4
+ import type { MockServerConfig } from '../types.ts';
5
+ import { buildLoginAckBody, findUser } from './auth.ts';
6
+
7
+ const SESSION_COOKIE = 'MOCK_SESSION_ID';
8
+
9
+ const HTTP_STATUS = {
10
+ OK: 200,
11
+ UNAUTHORIZED: 401,
12
+ NOT_FOUND: 404,
13
+ INTERNAL_SERVER_ERROR: 500,
14
+ };
15
+
16
+ // foundation-auth's login UI (client-app-login) doesn't use the WebSocket
17
+ // EVENT_LOGIN_AUTH flow at all — it POSTs credentials over plain HTTP to
18
+ // gwf/event-login-auth, and separately GETs gwf/event-login-details on every
19
+ // app load (cookie-based silent login: foundation-comms/src/connect/
20
+ // sessionRefresh.ts's isAuthenticated()). Both expect the exact same ACK body
21
+ // shape as the WS login (EVENT_LOGIN_DETAILS_ACK literally extends
22
+ // EVENT_LOGIN_AUTH_ACK), just reached over HTTP with a session cookie instead
23
+ // of SOURCE_REF correlation. This is a *separate* transport from the WS
24
+ // protocol in server.ts — a client-app can use either, or (as here) both.
25
+ function parseCookies(header: string | undefined): Record<string, string> {
26
+ const cookies: Record<string, string> = {};
27
+ for (const part of (header ?? '').split(';')) {
28
+ const [key, ...rest] = part.trim().split('=');
29
+ if (key) cookies[key] = decodeURIComponent(rest.join('='));
30
+ }
31
+ return cookies;
32
+ }
33
+
34
+ function setSessionCookie(res: ServerResponse, sessionId: string): void {
35
+ res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`);
36
+ }
37
+
38
+ function sendJson(res: ServerResponse, status: number, body: unknown): void {
39
+ res.writeHead(status, { 'Content-Type': 'application/json' });
40
+ res.end(JSON.stringify(body));
41
+ }
42
+
43
+ const BYTES_PER_KB = 1024;
44
+ const MAX_BODY_KB = 1024;
45
+ const MAX_BODY_BYTES = MAX_BODY_KB * BYTES_PER_KB; // 1MB — logins/commits carry small payloads, this only guards against abuse
46
+
47
+ async function readJsonBody(req: IncomingMessage): Promise<Record<string, any>> {
48
+ const chunks: Buffer[] = [];
49
+ let bytesRead = 0;
50
+ for await (const chunk of req) {
51
+ bytesRead += chunk.length;
52
+ if (bytesRead > MAX_BODY_BYTES) {
53
+ throw new Error('Request body size limit exceeded');
54
+ }
55
+ chunks.push(chunk);
56
+ }
57
+ const raw = Buffer.concat(chunks).toString('utf8');
58
+ return raw ? JSON.parse(raw) : {};
59
+ }
60
+
61
+ export function createHttpRequestListener(config: MockServerConfig, sessions: Map<string, string>) {
62
+ return async function requestListener(req: IncomingMessage, res: ServerResponse): Promise<void> {
63
+ const pathname = (req.url ?? '').split('?')[0];
64
+
65
+ try {
66
+ // Cookie-based silent login on app load — auto-authenticates as the
67
+ // configured user when config.auth.httpAutoLogin is set, so the login
68
+ // screen never appears (matches how a real session cookie would behave
69
+ // once already logged in, but skips the manual login step entirely).
70
+ // Two different call sites hit this path with different methods:
71
+ // foundation-auth's fetch machine always POSTs (createFetchMachineEvent
72
+ // hardcodes method: 'POST') on initial silent-login; foundation-comms'
73
+ // sessionRefresh.ts's isAuthenticated() does a plain GET later, when
74
+ // checking whether an expired session can be silently renewed.
75
+ if (
76
+ (req.method === 'GET' || req.method === 'POST') &&
77
+ pathname.endsWith('event-login-details')
78
+ ) {
79
+ const autoLoginUsername = config.auth?.httpAutoLogin;
80
+ const cookies = parseCookies(req.headers.cookie);
81
+ const user = autoLoginUsername
82
+ ? findUser(
83
+ config,
84
+ autoLoginUsername === true ? config.auth?.users?.[0]?.username : autoLoginUsername,
85
+ )
86
+ : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
87
+
88
+ if (!user) {
89
+ sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
90
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
91
+ ERROR: [
92
+ { CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
93
+ ],
94
+ });
95
+ return;
96
+ }
97
+
98
+ const sessionId = crypto.randomUUID();
99
+ sessions.set(sessionId, user.username);
100
+ setSessionCookie(res, sessionId);
101
+ sendJson(res, HTTP_STATUS.OK, buildLoginAckBody(user, config, 'EVENT_LOGIN_DETAILS_ACK'));
102
+ return;
103
+ }
104
+
105
+ if (req.method === 'POST' && pathname.endsWith('event-login-auth')) {
106
+ const body = await readJsonBody(req);
107
+ const details = body.DETAILS ?? {};
108
+ const cookies = parseCookies(req.headers.cookie);
109
+
110
+ // Empty DETAILS means a session-refresh ping (foundation-comms'
111
+ // sessionRefresh.performRefresh), not a fresh credentials login —
112
+ // honor it only if the request already carries a known session.
113
+ const user =
114
+ details.USER_NAME !== undefined
115
+ ? findUser(config, details.USER_NAME, details.PASSWORD)
116
+ : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
117
+
118
+ if (!user) {
119
+ sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
120
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
121
+ ERROR: [
122
+ {
123
+ CODE: 'INCORRECT_CREDENTIALS',
124
+ STATUS_CODE: '401 Unauthorized',
125
+ TEXT: 'Problem logging in',
126
+ },
127
+ ],
128
+ WARNING: [],
129
+ });
130
+ return;
131
+ }
132
+
133
+ const sessionId = crypto.randomUUID();
134
+ sessions.set(sessionId, user.username);
135
+ setSessionCookie(res, sessionId);
136
+ sendJson(res, HTTP_STATUS.OK, buildLoginAckBody(user, config));
137
+ return;
138
+ }
139
+
140
+ if (req.method === 'POST' && pathname.endsWith('event-logout')) {
141
+ const cookies = parseCookies(req.headers.cookie);
142
+ sessions.delete(cookies[SESSION_COOKIE]);
143
+ sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
144
+ return;
145
+ }
146
+
147
+ res.writeHead(HTTP_STATUS.NOT_FOUND).end();
148
+ } catch (error) {
149
+ console.error('[mock-server] HTTP handler error:', error);
150
+ res.writeHead(HTTP_STATUS.INTERNAL_SERVER_ERROR).end();
151
+ }
152
+ };
153
+ }
@@ -0,0 +1,92 @@
1
+ import { deriveFields } from '../db/metadata.ts';
2
+ import type { Store } from '../db/store.ts';
3
+ import type { Connection } from '../protocol/connection.ts';
4
+ import { ERROR_CODE } from '../protocol/messageTypes.ts';
5
+ import type { FieldMetadata, GenesisMessage, MockServerConfig, Row } from '../types.ts';
6
+
7
+ // JSON_SCHEMA_REQUEST shares its request envelope with META_REQUEST (same
8
+ // DETAILS.FEATURE resource-name field) but its reply is a completely
9
+ // different shape: Connect.getJSONSchema doesn't read response.DETAILS at
10
+ // all — the response *is* the SchemaResponse ({ INBOUND, OUTBOUND }, each a
11
+ // draft-07 JSON Schema). @genesislcap/foundation-entity-management's
12
+ // <entity-management> calls this for every create/update form (fields come
13
+ // from INBOUND.properties.DETAILS.properties) and for delete confirmation
14
+ // (it reads Object.keys(...properties) to know which fields to copy from the
15
+ // selected row into the commit DETAILS). Route this to handleMetaRequest by
16
+ // mistake and forms silently render with zero fields, and delete can never
17
+ // build a payload — no error, just a dead button.
18
+
19
+ function jsonSchemaType(fieldType: string): string {
20
+ switch (fieldType) {
21
+ case 'LONG':
22
+ return 'integer';
23
+ case 'DOUBLE':
24
+ return 'number';
25
+ case 'BOOLEAN':
26
+ return 'boolean';
27
+ default:
28
+ return 'string';
29
+ }
30
+ }
31
+
32
+ function buildSchema(fields: FieldMetadata[], required: string[]): Row {
33
+ const properties: Row = {};
34
+ for (const field of fields) {
35
+ properties[field.NAME] = { type: jsonSchemaType(field.TYPE) };
36
+ }
37
+ return {
38
+ type: 'object',
39
+ properties: {
40
+ DETAILS: { type: 'object', properties, required },
41
+ },
42
+ };
43
+ }
44
+
45
+ const DELETE_EVENT_RE = /_DELETE(_|$)/;
46
+
47
+ // Zero-config default: EVENT_<TABLE>_<VERB...> maps to <TABLE> if it's a
48
+ // registered table name (longest match wins, so e.g. a hypothetical
49
+ // COUNTERPARTY_AUTH table can't shadow COUNTERPARTY). Covers every event
50
+ // naming pattern in this codebase (INSERT, MODIFY, DELETE, plus suffixed
51
+ // variants like INSERT_WITH_APPROVAL, DEMO_INSERT, MODIFY_PRICE, INSERT_FAIL)
52
+ // without hand-maintaining a table per event. Override via
53
+ // config.eventSchemas for names that don't follow this convention.
54
+ function inferEventTable(eventName: string | undefined, tableNames: string[]): string | undefined {
55
+ if (!eventName?.startsWith('EVENT_')) return undefined;
56
+ const rest = eventName.slice('EVENT_'.length);
57
+ const candidates = tableNames.filter((name) => rest === name || rest.startsWith(`${name}_`));
58
+ candidates.sort((a, b) => b.length - a.length);
59
+ return candidates[0];
60
+ }
61
+
62
+ export function handleJsonSchemaRequest(
63
+ message: GenesisMessage,
64
+ connection: Connection,
65
+ config: MockServerConfig,
66
+ store: Store,
67
+ ): void {
68
+ const eventName: string | undefined = message.DETAILS?.FEATURE;
69
+ const override = eventName ? config.eventSchemas?.[eventName] : undefined;
70
+ const table = override?.table ?? inferEventTable(eventName, Object.keys(config.tables ?? {}));
71
+
72
+ if (!table) {
73
+ connection.reply(message, {
74
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
75
+ ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown resource: ${eventName}` }],
76
+ });
77
+ return;
78
+ }
79
+
80
+ const pkOnly = override?.pkOnly ?? DELETE_EVENT_RE.test(eventName!);
81
+ const pkField = store.getPkField(table);
82
+ let fields = deriveFields(store.getResourceRows(table), override?.fieldTypes);
83
+ if (pkOnly) fields = fields.filter((field) => field.NAME === pkField);
84
+
85
+ const schema = buildSchema(fields, pkOnly && pkField ? [pkField] : []);
86
+
87
+ connection.reply(message, {
88
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
89
+ INBOUND: schema,
90
+ OUTBOUND: schema,
91
+ });
92
+ }
@@ -0,0 +1,49 @@
1
+ import { deriveFields } from '../db/metadata.ts';
2
+ import type { Store } from '../db/store.ts';
3
+ import type { Connection } from '../protocol/connection.ts';
4
+ import { ERROR_CODE } from '../protocol/messageTypes.ts';
5
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
6
+
7
+ // createMetaRequestMessage (foundation-comms/src/connect/message.ts) puts the
8
+ // resource name in DETAILS.FEATURE — not DATASOURCE_NAME/RESOURCE_NAME despite
9
+ // what every other message type in this protocol would suggest.
10
+ function resolveResourceName(message: GenesisMessage): string {
11
+ return (
12
+ message.DETAILS?.FEATURE ?? message.DETAILS?.DATASOURCE_NAME ?? message.DETAILS?.RESOURCE_NAME
13
+ );
14
+ }
15
+
16
+ // Connect.getMetadata reads metaResponse.DETAILS (not the top-level message)
17
+ // and extractFieldDefinitions (metadata.utils.ts) branches on DETAILS.TYPE:
18
+ // DATASERVER resources need DETAILS.FIELD, REQUEST_SERVER ones need
19
+ // DETAILS.REPLY_FIELD. Get either wrong and every grid silently reports
20
+ // "Metadata Fetch failed" / "Unsupported resource type: undefined".
21
+ export function handleMetaRequest(
22
+ message: GenesisMessage,
23
+ connection: Connection,
24
+ config: MockServerConfig,
25
+ store: Store,
26
+ ): void {
27
+ const resourceName = resolveResourceName(message);
28
+ const query = config.queries?.[resourceName];
29
+ const requestReply = config.requestReplies?.[resourceName];
30
+
31
+ if (!query && !requestReply) {
32
+ connection.reply(message, {
33
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
34
+ ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown resource: ${resourceName}` }],
35
+ });
36
+ return;
37
+ }
38
+
39
+ const resolved = (query ?? requestReply)!;
40
+ const rows = store.getResourceRows(resolved.source);
41
+ const fields = deriveFields(rows, resolved.fieldTypes);
42
+
43
+ connection.reply(message, {
44
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
45
+ DETAILS: query
46
+ ? { NAME: resourceName, TYPE: 'DATASERVER', FIELD: fields, KEY: [] }
47
+ : { NAME: resourceName, TYPE: 'REQUEST_SERVER', REPLY_FIELD: fields },
48
+ });
49
+ }