@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,47 @@
1
+ import { filterByCriteria } from '../db/criteria.ts';
2
+ import type { Store } from '../db/store.ts';
3
+ import type { Connection } from '../protocol/connection.ts';
4
+ import { NackError } from '../protocol/errors.ts';
5
+ import { ERROR_CODE } from '../protocol/messageTypes.ts';
6
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
7
+
8
+ export function handleRequestReply(
9
+ message: GenesisMessage,
10
+ connection: Connection,
11
+ config: MockServerConfig,
12
+ store: Store,
13
+ ): void {
14
+ const resourceName = message.MESSAGE_TYPE.replace(/^REQ_/, '');
15
+ const requestReply = config.requestReplies?.[resourceName];
16
+
17
+ if (!requestReply) {
18
+ connection.reply(message, {
19
+ MESSAGE_TYPE: `REP_${resourceName}`,
20
+ ERROR: [
21
+ {
22
+ CODE: ERROR_CODE.UNKNOWN_RESOURCE,
23
+ TEXT: `Unknown request-reply resource: ${resourceName}`,
24
+ },
25
+ ],
26
+ });
27
+ return;
28
+ }
29
+
30
+ try {
31
+ let rows = store.getResourceRows(requestReply.source);
32
+ const criteria = message.DETAILS?.CRITERIA_MATCH ?? message.CRITERIA_MATCH;
33
+ if (criteria) rows = filterByCriteria(rows, criteria);
34
+ if (requestReply.filter) rows = rows.filter(requestReply.filter);
35
+
36
+ connection.reply(message, {
37
+ MESSAGE_TYPE: `REP_${resourceName}`,
38
+ REPLY: rows,
39
+ });
40
+ } catch (error) {
41
+ const errors =
42
+ error instanceof NackError
43
+ ? error.errors
44
+ : [{ CODE: ERROR_CODE.VALIDATION_ERROR, TEXT: (error as Error).message }];
45
+ connection.reply(message, { MESSAGE_TYPE: `REP_${resourceName}`, ERROR: errors });
46
+ }
47
+ }
@@ -0,0 +1,35 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
3
+ import type { GenesisMessage, MockServerConfig, ResourceItem } from '../types.ts';
4
+
5
+ // GenesisResources (foundation-comms/src/resources/genesis/genesis.ts) gates
6
+ // every datasource/request-reply/commit call on this list first — an empty
7
+ // or missing RESOURCES_REQUEST_ACK.RESOURCES makes every resource silently
8
+ // "not exist" client-side, before META_REQUEST or DATA_LOGON is ever tried.
9
+ // Auto-derive it from config.queries/requestReplies/eventHandlers (same
10
+ // philosophy as db/metadata.ts's field inference) so projects don't have to
11
+ // hand-maintain a redundant list; set config.resources explicitly to override.
12
+ function deriveResources(config: MockServerConfig): ResourceItem[] {
13
+ const resources: ResourceItem[] = [];
14
+ for (const name of Object.keys(config.queries ?? {})) {
15
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'DATASERVER' });
16
+ }
17
+ for (const name of Object.keys(config.requestReplies ?? {})) {
18
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'REQUEST_SERVER' });
19
+ }
20
+ for (const name of Object.keys(config.eventHandlers ?? {})) {
21
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'EVENT_HANDLER' });
22
+ }
23
+ return resources;
24
+ }
25
+
26
+ export function handleResourcesRequest(
27
+ message: GenesisMessage,
28
+ connection: Connection,
29
+ config: MockServerConfig,
30
+ ): void {
31
+ connection.reply(message, {
32
+ MESSAGE_TYPE: MESSAGE_TYPE.RESOURCES_REQUEST_ACK,
33
+ RESOURCES: config.resources ?? deriveResources(config),
34
+ });
35
+ }
package/src/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ export { createMockServer, type MockServer } from './server.ts';
2
+ export { Store } from './db/store.ts';
3
+ export { NackError, type NackErrorInput, type NackErrorEntry } from './protocol/errors.ts';
4
+ export { compileCriteria, filterByCriteria, type Predicate } from './db/criteria.ts';
5
+ export type {
6
+ AuthConfig,
7
+ AuthUser,
8
+ BroadcastFn,
9
+ BroadcastTableChangeFn,
10
+ EventHandler,
11
+ EventHandlerCtx,
12
+ EventHandlerResult,
13
+ EventSchemaOverride,
14
+ FieldMetadata,
15
+ GenesisMessage,
16
+ JoinDef,
17
+ MockServerConfig,
18
+ QueryDef,
19
+ RequestReplyDef,
20
+ ResourceItem,
21
+ Row,
22
+ SocketLike,
23
+ TableDef,
24
+ ViewDef,
25
+ } from './types.ts';
@@ -0,0 +1,50 @@
1
+ import crypto from 'node:crypto';
2
+ import type { Predicate } from '../db/criteria.ts';
3
+ import type { GenesisMessage, Row, SocketLike } from '../types.ts';
4
+
5
+ const WS_OPEN = 1;
6
+
7
+ export interface Subscription {
8
+ resourceName: string;
9
+ pkField?: string;
10
+ predicate: Predicate;
11
+ sequenceId: number;
12
+ }
13
+
14
+ // Wraps one WebSocket client connection: auth state and its live DATA_LOGON
15
+ // subscriptions (keyed by SOURCE_REF, since that's the client's sole correlation
16
+ // key — see README pitfall #1).
17
+ export class Connection {
18
+ readonly ws: SocketLike;
19
+ readonly id = crypto.randomUUID();
20
+ authenticated = false;
21
+ sessionAuthToken: string | undefined;
22
+ sessionId: string | undefined;
23
+ userName: string | undefined;
24
+ profile: string[] = [];
25
+ permission: string[] = [];
26
+ readonly subscriptions = new Map<string, Subscription>();
27
+
28
+ constructor(ws: SocketLike) {
29
+ this.ws = ws;
30
+ }
31
+
32
+ // Every response must echo the request's SOURCE_REF verbatim, or the client's
33
+ // pending promise for that call never resolves (silent hang, no error).
34
+ send(payload: Row): void {
35
+ if (this.ws.readyState !== WS_OPEN) return;
36
+ this.ws.send(JSON.stringify(payload));
37
+ }
38
+
39
+ reply(requestMessage: GenesisMessage, payload: Row): void {
40
+ this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF });
41
+ }
42
+
43
+ subscribe(sourceRef: string, subscription: Subscription): void {
44
+ this.subscriptions.set(sourceRef, subscription);
45
+ }
46
+
47
+ unsubscribe(sourceRef: string): void {
48
+ this.subscriptions.delete(sourceRef);
49
+ }
50
+ }
@@ -0,0 +1,32 @@
1
+ export interface NackErrorInput {
2
+ CODE?: string;
3
+ code?: string;
4
+ TEXT?: string;
5
+ text?: string;
6
+ FIELD?: string;
7
+ field?: string;
8
+ }
9
+
10
+ export interface NackErrorEntry {
11
+ CODE: string;
12
+ TEXT: string;
13
+ FIELD?: string;
14
+ }
15
+
16
+ // Throw this from an event handler / request-reply resolver to produce a
17
+ // protocol-correct *_NACK with ERROR as an array of {CODE, TEXT, FIELD?} —
18
+ // never {error, details} (lowercase, non-array), which crashes real clients
19
+ // calling .forEach on the wrong shape.
20
+ export class NackError extends Error {
21
+ readonly errors: NackErrorEntry[];
22
+
23
+ constructor(errors: NackErrorInput | NackErrorInput[]) {
24
+ const list = Array.isArray(errors) ? errors : [errors];
25
+ super(list.map((e) => e.TEXT ?? e.text ?? 'Unknown error').join(', '));
26
+ this.errors = list.map((e) => ({
27
+ CODE: e.CODE ?? e.code ?? 'VALIDATION_ERROR',
28
+ TEXT: e.TEXT ?? e.text ?? 'Unknown error',
29
+ ...(e.FIELD || e.field ? { FIELD: e.FIELD ?? e.field } : {}),
30
+ }));
31
+ }
32
+ }
@@ -0,0 +1,38 @@
1
+ export const MESSAGE_TYPE = {
2
+ EVENT_LOGIN_AUTH: 'EVENT_LOGIN_AUTH',
3
+ EVENT_LOGIN_AUTH_ACK: 'EVENT_LOGIN_AUTH_ACK',
4
+ EVENT_LOGIN_AUTH_NACK: 'EVENT_LOGIN_AUTH_NACK',
5
+ EVENT_LOGOUT: 'EVENT_LOGOUT',
6
+ LOGOUT_ACK: 'LOGOUT_ACK',
7
+ EVENT_LOGOUT_NACK: 'EVENT_LOGOUT_NACK',
8
+ HEARTBEAT_PING: 'HEARTBEAT_PING',
9
+ HEARTBEAT_PONG: 'HEARTBEAT_PONG',
10
+ DATA_LOGON: 'DATA_LOGON',
11
+ DATA_LOGOFF: 'DATA_LOGOFF',
12
+ QUERY_UPDATE: 'QUERY_UPDATE',
13
+ META_REQUEST: 'META_REQUEST',
14
+ JSON_SCHEMA_REQUEST: 'JSON_SCHEMA_REQUEST',
15
+ RESOURCES_REQUEST: 'RESOURCES_REQUEST',
16
+ RESOURCES_REQUEST_ACK: 'RESOURCES_REQUEST_ACK',
17
+ RESOURCES_REQUEST_NACK: 'RESOURCES_REQUEST_NACK',
18
+ } as const;
19
+
20
+ export const ERROR_CODE = {
21
+ INCORRECT_CREDENTIALS: 'INCORRECT_CREDENTIALS',
22
+ VALIDATION_ERROR: 'VALIDATION_ERROR',
23
+ UNKNOWN_RESOURCE: 'UNKNOWN_RESOURCE',
24
+ NOT_LOGGED_ON: 'NOT_LOGGED_ON',
25
+ } as const;
26
+
27
+ export function isCommitEvent(messageType: unknown): messageType is string {
28
+ return (
29
+ typeof messageType === 'string' &&
30
+ messageType.startsWith('EVENT_') &&
31
+ messageType !== MESSAGE_TYPE.EVENT_LOGIN_AUTH &&
32
+ messageType !== MESSAGE_TYPE.EVENT_LOGOUT
33
+ );
34
+ }
35
+
36
+ export function isRequestReply(messageType: unknown): messageType is string {
37
+ return typeof messageType === 'string' && messageType.startsWith('REQ_');
38
+ }
@@ -0,0 +1,45 @@
1
+ import type { Store } from '../db/store.ts';
2
+ import { handleLogin, handleLogout } from '../handlers/auth.ts';
3
+ import { handleCommitEvent, type CommitEventCtx } from '../handlers/commitEvent.ts';
4
+ import { handleDataLogon, handleDataLogoff } from '../handlers/dataLogon.ts';
5
+ import { handleHeartbeat } from '../handlers/heartbeat.ts';
6
+ import { handleJsonSchemaRequest } from '../handlers/jsonSchema.ts';
7
+ import { handleMetaRequest } from '../handlers/meta.ts';
8
+ import { handleRequestReply } from '../handlers/requestReply.ts';
9
+ import { handleResourcesRequest } from '../handlers/resources.ts';
10
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
11
+ import type { Connection } from './connection.ts';
12
+ import { MESSAGE_TYPE, isCommitEvent, isRequestReply } from './messageTypes.ts';
13
+
14
+ export function routeMessage(
15
+ message: GenesisMessage,
16
+ connection: Connection,
17
+ config: MockServerConfig,
18
+ store: Store,
19
+ ctx: CommitEventCtx,
20
+ ): void {
21
+ switch (message.MESSAGE_TYPE) {
22
+ case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
23
+ return handleLogin(message, connection, config);
24
+ case MESSAGE_TYPE.EVENT_LOGOUT:
25
+ return handleLogout(message, connection);
26
+ case MESSAGE_TYPE.HEARTBEAT_PING:
27
+ return handleHeartbeat(message, connection);
28
+ case MESSAGE_TYPE.DATA_LOGON:
29
+ return handleDataLogon(message, connection, config, store);
30
+ case MESSAGE_TYPE.DATA_LOGOFF:
31
+ return handleDataLogoff(message, connection);
32
+ case MESSAGE_TYPE.META_REQUEST:
33
+ return handleMetaRequest(message, connection, config, store);
34
+ case MESSAGE_TYPE.JSON_SCHEMA_REQUEST:
35
+ return handleJsonSchemaRequest(message, connection, config, store);
36
+ case MESSAGE_TYPE.RESOURCES_REQUEST:
37
+ return handleResourcesRequest(message, connection, config);
38
+ default:
39
+ if (isRequestReply(message.MESSAGE_TYPE))
40
+ return handleRequestReply(message, connection, config, store);
41
+ if (isCommitEvent(message.MESSAGE_TYPE))
42
+ return handleCommitEvent(message, connection, config, store, ctx);
43
+ console.warn(`[mock-server] Unhandled MESSAGE_TYPE: ${message.MESSAGE_TYPE}`);
44
+ }
45
+ }
@@ -0,0 +1,25 @@
1
+ import type { Row } from '../types.ts';
2
+
3
+ export type RowOperation = 'INSERT' | 'MODIFY' | 'DELETE';
4
+
5
+ // Stamps each row with DETAILS.OPERATION/ROW_REF, the only fields the client's
6
+ // dataServerResultFilter uses to distinguish INSERT/MODIFY/DELETE on a QUERY_UPDATE
7
+ // (both for the initial snapshot and later unsolicited pushes on the same
8
+ // SOURCE_REF — the envelope is otherwise identical). OPERATION must be exactly
9
+ // 'INSERT' | 'MODIFY' | 'DELETE'; anything else is silently dropped client-side.
10
+ export function stampRow(row: Row, pkField: string | undefined, operation: RowOperation): Row {
11
+ const rowRef = pkField ? row[pkField] : undefined;
12
+ return {
13
+ ...row,
14
+ ROW_REF: rowRef,
15
+ DETAILS: { OPERATION: operation, ROW_REF: rowRef },
16
+ };
17
+ }
18
+
19
+ export function stampRows(
20
+ rows: Row[],
21
+ pkField: string | undefined,
22
+ operation: RowOperation,
23
+ ): Row[] {
24
+ return rows.map((row) => stampRow(row, pkField, operation));
25
+ }
package/src/server.ts ADDED
@@ -0,0 +1,251 @@
1
+ import http from 'node:http';
2
+ import { WebSocketServer, type WebSocket } from 'ws';
3
+ import { Store } from './db/store.ts';
4
+ import { createHttpRequestListener } from './handlers/http.ts';
5
+ import { Connection } from './protocol/connection.ts';
6
+ import { routeMessage } from './protocol/router.ts';
7
+ import { stampRow } from './protocol/rowUpdate.ts';
8
+ import type {
9
+ BroadcastFn,
10
+ BroadcastTableChangeFn,
11
+ EventHandler,
12
+ MockServerConfig,
13
+ QueryDef,
14
+ RequestReplyDef,
15
+ Row,
16
+ TableDef,
17
+ ViewDef,
18
+ } from './types.ts';
19
+
20
+ export interface MockServer {
21
+ start(port: number): WebSocketServer;
22
+ stop(): Promise<void>;
23
+ store: Store;
24
+ broadcast: BroadcastFn;
25
+ broadcastTableChange: BroadcastTableChangeFn;
26
+ setTable(tableName: string, tableDef: TableDef): void;
27
+ setView(viewName: string, viewDef: ViewDef): void;
28
+ setQuery(resourceName: string, queryDef: QueryDef): void;
29
+ setRequestReply(resourceName: string, requestReplyDef: RequestReplyDef): void;
30
+ setEventHandler(eventName: string, handler: EventHandler): void;
31
+ getQuery(resourceName: string): QueryDef | undefined;
32
+ getRequestReply(resourceName: string): RequestReplyDef | undefined;
33
+ getEventHandler(eventName: string): EventHandler | undefined;
34
+ extendQuery(resourceName: string, augment: (current: QueryDef | undefined) => QueryDef): void;
35
+ extendRequestReply(
36
+ resourceName: string,
37
+ augment: (current: RequestReplyDef | undefined) => RequestReplyDef,
38
+ ): void;
39
+ extendEventHandler(
40
+ eventName: string,
41
+ augment: (current: EventHandler | undefined) => EventHandler,
42
+ ): void;
43
+ }
44
+
45
+ export function createMockServer(config: MockServerConfig): MockServer {
46
+ const store = new Store();
47
+ for (const [tableName, tableDef] of Object.entries(config.tables ?? {})) {
48
+ store.registerTable(tableName, tableDef);
49
+ }
50
+ for (const [viewName, viewDef] of Object.entries(config.views ?? {})) {
51
+ store.registerView(viewName, viewDef);
52
+ }
53
+
54
+ const connections = new Set<Connection>();
55
+
56
+ // Pushes an unsolicited row update to every currently-subscribed connection
57
+ // whose DATA_LOGON resource matches, filtered by that subscription's own
58
+ // CRITERIA_MATCH. Event handlers call this after mutating the store so open
59
+ // grids reflect inserts/amends/deletes without the client re-querying.
60
+ const broadcast: BroadcastFn = (resourceName, operation, row) => {
61
+ for (const connection of connections) {
62
+ for (const [sourceRef, subscription] of connection.subscriptions) {
63
+ if (subscription.resourceName !== resourceName) continue;
64
+ try {
65
+ if (!subscription.predicate(row)) continue;
66
+ } catch (error) {
67
+ console.error(
68
+ `[mock-server] Error evaluating predicate for subscription ${sourceRef}:`,
69
+ error,
70
+ );
71
+ continue;
72
+ }
73
+ subscription.sequenceId += 1;
74
+ connection.send({
75
+ MESSAGE_TYPE: 'QUERY_UPDATE',
76
+ SOURCE_REF: sourceRef,
77
+ ROW: [stampRow(row, subscription.pkField, operation)],
78
+ ROWS_COUNT: 1,
79
+ SEQUENCE_ID: subscription.sequenceId,
80
+ });
81
+ }
82
+ }
83
+ };
84
+
85
+ // Event handlers mutate one table (e.g. TRADE) but grids may be subscribed to
86
+ // a view built on top of it (e.g. ALL_TRADES -> TRADE_VIEW). This finds every
87
+ // query resource backed by that table — directly or via a view — and pushes
88
+ // the (re-joined, for views) row to each one's subscribers.
89
+ const broadcastTableChange: BroadcastTableChangeFn = (tableName, operation, pk) => {
90
+ for (const [queryName, query] of Object.entries(config.queries ?? {})) {
91
+ const isDirect = query.source === tableName;
92
+ const view = store.views.get(query.source);
93
+ const isViewOnTable = view?.base === tableName;
94
+ if (!isDirect && !isViewOnTable) continue;
95
+
96
+ const pkField = store.getPkField(query.source);
97
+ let row: Row | undefined;
98
+ if (operation === 'DELETE') {
99
+ row = pkField ? { [pkField]: pk } : undefined;
100
+ } else if (isDirect) {
101
+ row = store.getRow(tableName, pk);
102
+ } else {
103
+ row = store.getViewRows(query.source).find((r) => r[pkField!] === pk);
104
+ }
105
+ if (row) broadcast(queryName, operation, row);
106
+ }
107
+ };
108
+
109
+ const httpSessions = new Map<string, string>(); // sessionId -> username, for the HTTP login transport (see handlers/http.ts)
110
+
111
+ // Runtime override/extend API. Every handler reads off this same `config`
112
+ // object at call time (both the WS path in routeMessage below and the HTTP
113
+ // login transport, whose handler was created once in start() and holds a
114
+ // reference to this exact object) — so these mutate config's own
115
+ // properties in place rather than rebinding the `config` variable, which
116
+ // would only be visible to callers still reading the original reference.
117
+ // Useful both for composing a project's config from a shared base
118
+ // (`setEventHandler`/`setQuery` after createMockServer) and for tests that
119
+ // want to inject a one-off failure/edge case (`extendEventHandler`) without
120
+ // spinning up a second server.
121
+ function setTable(tableName: string, tableDef: TableDef): void {
122
+ config.tables = { ...config.tables, [tableName]: tableDef };
123
+ store.registerTable(tableName, tableDef);
124
+ }
125
+
126
+ function setView(viewName: string, viewDef: ViewDef): void {
127
+ config.views = { ...config.views, [viewName]: viewDef };
128
+ store.registerView(viewName, viewDef);
129
+ }
130
+
131
+ function setQuery(resourceName: string, queryDef: QueryDef): void {
132
+ config.queries = { ...config.queries, [resourceName]: queryDef };
133
+ }
134
+
135
+ function setRequestReply(resourceName: string, requestReplyDef: RequestReplyDef): void {
136
+ config.requestReplies = { ...config.requestReplies, [resourceName]: requestReplyDef };
137
+ }
138
+
139
+ function setEventHandler(eventName: string, handler: EventHandler): void {
140
+ config.eventHandlers = { ...config.eventHandlers, [eventName]: handler };
141
+ }
142
+
143
+ function getQuery(resourceName: string): QueryDef | undefined {
144
+ return config.queries?.[resourceName];
145
+ }
146
+
147
+ function getRequestReply(resourceName: string): RequestReplyDef | undefined {
148
+ return config.requestReplies?.[resourceName];
149
+ }
150
+
151
+ function getEventHandler(eventName: string): EventHandler | undefined {
152
+ return config.eventHandlers?.[eventName];
153
+ }
154
+
155
+ // augment(current) => replacement. `current` is undefined if nothing was
156
+ // registered under that name yet, so augment can also be used to define a
157
+ // brand new query/handler in terms of "there was nothing before".
158
+ function extendQuery(
159
+ resourceName: string,
160
+ augment: (current: QueryDef | undefined) => QueryDef,
161
+ ): void {
162
+ setQuery(resourceName, augment(getQuery(resourceName)));
163
+ }
164
+
165
+ function extendRequestReply(
166
+ resourceName: string,
167
+ augment: (current: RequestReplyDef | undefined) => RequestReplyDef,
168
+ ): void {
169
+ setRequestReply(resourceName, augment(getRequestReply(resourceName)));
170
+ }
171
+
172
+ function extendEventHandler(
173
+ eventName: string,
174
+ augment: (current: EventHandler | undefined) => EventHandler,
175
+ ): void {
176
+ setEventHandler(eventName, augment(getEventHandler(eventName)));
177
+ }
178
+
179
+ let wss: WebSocketServer | undefined;
180
+ let httpServer: http.Server | undefined;
181
+
182
+ function start(port: number): WebSocketServer {
183
+ // WS (datasource/commit protocol) and HTTP (foundation-auth's login
184
+ // transport) share one http.Server, matching how the real Genesis gateway
185
+ // and the vite dev proxy present a single origin to the client. Built on
186
+ // node:http + the `ws` package rather than a runtime-specific API (e.g.
187
+ // Bun.serve) so this runs unmodified under both Node (>=22.6, via
188
+ // `node --experimental-strip-types`) and Bun.
189
+ httpServer = http.createServer(createHttpRequestListener(config, httpSessions));
190
+ wss = new WebSocketServer({ server: httpServer });
191
+
192
+ wss.on('connection', (ws: WebSocket) => {
193
+ const connection = new Connection(ws);
194
+ connections.add(connection);
195
+
196
+ ws.on('message', (data) => {
197
+ let message;
198
+ try {
199
+ message = JSON.parse(data.toString());
200
+ } catch {
201
+ console.warn('[mock-server] Ignoring non-JSON message');
202
+ return;
203
+ }
204
+ try {
205
+ routeMessage(message, connection, config, store, { broadcast, broadcastTableChange });
206
+ } catch (error) {
207
+ console.error(`[mock-server] Error handling ${message.MESSAGE_TYPE}:`, error);
208
+ }
209
+ });
210
+
211
+ ws.on('close', () => {
212
+ connections.delete(connection);
213
+ });
214
+ });
215
+
216
+ httpServer.listen(port);
217
+ console.log(
218
+ `[mock-server] Listening on ws://localhost:${port} (HTTP login endpoints on the same port)`,
219
+ );
220
+ return wss;
221
+ }
222
+
223
+ function stop(): Promise<void> {
224
+ return new Promise((resolve) => {
225
+ if (!wss || !httpServer) {
226
+ resolve();
227
+ return;
228
+ }
229
+ wss.close(() => httpServer!.close(() => resolve()));
230
+ });
231
+ }
232
+
233
+ return {
234
+ start,
235
+ stop,
236
+ store,
237
+ broadcast,
238
+ broadcastTableChange,
239
+ setTable,
240
+ setView,
241
+ setQuery,
242
+ setRequestReply,
243
+ setEventHandler,
244
+ getQuery,
245
+ getRequestReply,
246
+ getEventHandler,
247
+ extendQuery,
248
+ extendRequestReply,
249
+ extendEventHandler,
250
+ };
251
+ }
package/src/types.ts ADDED
@@ -0,0 +1,116 @@
1
+ // Shared types for the mock-server protocol engine. Deliberately loose where
2
+ // a real Genesis payload's shape is "whatever the project defines" (row data,
3
+ // event DETAILS) — Record<string, any> there is the honest type, not a cop-out.
4
+
5
+ import type { Store } from './db/store.ts';
6
+
7
+ export type Row = Record<string, any>;
8
+
9
+ export interface GenesisMessage {
10
+ MESSAGE_TYPE: string;
11
+ SOURCE_REF?: string;
12
+ DETAILS?: Row;
13
+ [key: string]: any;
14
+ }
15
+
16
+ export interface TableDef {
17
+ pkField: string;
18
+ sequencePrefix?: string;
19
+ sequenceWidth?: number;
20
+ rows?: Row[];
21
+ }
22
+
23
+ export interface JoinDef {
24
+ table: string;
25
+ on: [string, string];
26
+ select?: Record<string, string>;
27
+ }
28
+
29
+ export interface ViewDef {
30
+ base: string;
31
+ pkField?: string;
32
+ joins?: JoinDef[];
33
+ derived?: Record<string, (row: Row) => any>;
34
+ }
35
+
36
+ export interface QueryDef {
37
+ source: string;
38
+ fieldTypes?: Record<string, string>;
39
+ }
40
+
41
+ export interface RequestReplyDef {
42
+ source: string;
43
+ fieldTypes?: Record<string, string>;
44
+ filter?: (row: Row) => boolean;
45
+ }
46
+
47
+ export interface EventSchemaOverride {
48
+ table?: string;
49
+ pkOnly?: boolean;
50
+ fieldTypes?: Record<string, string>;
51
+ }
52
+
53
+ export interface ResourceItem {
54
+ RESOURCE_NAME: string;
55
+ RESOURCE_TYPE: 'DATASERVER' | 'REQUEST_SERVER' | 'EVENT_HANDLER';
56
+ }
57
+
58
+ export interface AuthUser {
59
+ username: string;
60
+ password?: string;
61
+ profile?: string[];
62
+ permission?: string[];
63
+ user?: Row;
64
+ }
65
+
66
+ export interface AuthConfig {
67
+ users?: AuthUser[];
68
+ heartbeatIntervalSecs?: number;
69
+ // A username to always ack gwf/event-login-details as (skips the login
70
+ // screen entirely), or `true` to use the first configured user.
71
+ httpAutoLogin?: string | true;
72
+ }
73
+
74
+ export interface BroadcastFn {
75
+ (resourceName: string, operation: 'INSERT' | 'MODIFY' | 'DELETE', row: Row): void;
76
+ }
77
+
78
+ export interface BroadcastTableChangeFn {
79
+ (tableName: string, operation: 'INSERT' | 'MODIFY' | 'DELETE', pk: string): void;
80
+ }
81
+
82
+ export interface EventHandlerCtx {
83
+ connection: import('./protocol/connection.ts').Connection;
84
+ store: Store;
85
+ message: GenesisMessage;
86
+ broadcast: BroadcastFn;
87
+ broadcastTableChange: BroadcastTableChangeFn;
88
+ }
89
+
90
+ export type EventHandlerResult = { generated?: Row[] } | void;
91
+
92
+ export type EventHandler = (details: Row, ctx: EventHandlerCtx) => EventHandlerResult;
93
+
94
+ export interface MockServerConfig {
95
+ tables?: Record<string, TableDef>;
96
+ views?: Record<string, ViewDef>;
97
+ queries?: Record<string, QueryDef>;
98
+ requestReplies?: Record<string, RequestReplyDef>;
99
+ eventHandlers?: Record<string, EventHandler>;
100
+ eventSchemas?: Record<string, EventSchemaOverride>;
101
+ auth?: AuthConfig;
102
+ resources?: ResourceItem[];
103
+ productName?: string;
104
+ }
105
+
106
+ export interface FieldMetadata {
107
+ NAME: string;
108
+ TYPE: string;
109
+ }
110
+
111
+ // Minimal shape both `ws`'s WebSocket and Bun's ServerWebSocket satisfy —
112
+ // Connection only needs to send text frames and check whether it still can.
113
+ export interface SocketLike {
114
+ readyState: number;
115
+ send(data: string): void;
116
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ESNext"],
7
+ "strict": true,
8
+ "noUncheckedIndexedAccess": false,
9
+ "skipLibCheck": true,
10
+ "esModuleInterop": true,
11
+ "resolveJsonModule": true,
12
+ "noEmit": true,
13
+ "allowJs": false,
14
+ "allowImportingTsExtensions": true,
15
+ "verbatimModuleSyntax": false
16
+ },
17
+ "include": ["src/**/*.ts"]
18
+ }