@genesislcap/mock-server 15.7.3-alpha-94532c4.0 → 15.7.3-alpha-e7d4aa5.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 (70) hide show
  1. package/README.md +212 -37
  2. package/dist/db/criteria.d.ts +5 -0
  3. package/dist/db/criteria.js +304 -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 +27 -0
  7. package/dist/db/store.js +226 -0
  8. package/dist/handlers/auth.d.ts +9 -0
  9. package/dist/handlers/auth.js +99 -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 +46 -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 +165 -0
  18. package/dist/handlers/jsonSchema.d.ts +5 -0
  19. package/dist/handlers/jsonSchema.js +77 -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 +19 -0
  31. package/dist/launch.js +59 -0
  32. package/dist/protocol/connection.d.ts +24 -0
  33. package/dist/protocol/connection.js +35 -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 +274 -0
  44. package/dist/types.d.ts +142 -0
  45. package/dist/types.js +4 -0
  46. package/package.json +16 -6
  47. package/src/db/criteria.ts +53 -21
  48. package/src/db/store.ts +100 -27
  49. package/src/handlers/commitEvent.ts +4 -1
  50. package/src/handlers/dataLogon.ts +11 -4
  51. package/src/handlers/heartbeat.ts +16 -3
  52. package/src/handlers/http.ts +27 -0
  53. package/src/handlers/jsonSchema.ts +3 -3
  54. package/src/handlers/meta.ts +11 -3
  55. package/src/handlers/requestReply.ts +22 -8
  56. package/src/handlers/resourceAuth.ts +37 -0
  57. package/src/handlers/resources.ts +8 -1
  58. package/src/index.ts +9 -0
  59. package/src/launch.ts +95 -0
  60. package/src/protocol/connection.ts +3 -1
  61. package/src/protocol/router.ts +1 -1
  62. package/src/protocol/rowUpdate.ts +5 -4
  63. package/src/server.ts +73 -8
  64. package/src/types.ts +124 -3
  65. package/test/criteria.test.ts +0 -174
  66. package/test/jsonSchema.test.ts +0 -38
  67. package/test/metadata.test.ts +0 -49
  68. package/test/server.test.ts +0 -308
  69. package/test/store.test.ts +0 -181
  70. package/tsconfig.json +0 -18
package/src/server.ts CHANGED
@@ -2,6 +2,7 @@ import http from 'node:http';
2
2
  import { WebSocketServer, type WebSocket } from 'ws';
3
3
  import { Store } from './db/store.ts';
4
4
  import { createHttpRequestListener } from './handlers/http.ts';
5
+ import { applyResourceAuth, requestingUser } from './handlers/resourceAuth.ts';
5
6
  import { Connection, type Subscription } from './protocol/connection.ts';
6
7
  import { routeMessage } from './protocol/router.ts';
7
8
  import { stampRow } from './protocol/rowUpdate.ts';
@@ -19,6 +20,11 @@ import type {
19
20
 
20
21
  export interface MockServer {
21
22
  start(port: number): WebSocketServer;
23
+ // Like start(), but resolves with the ACTUAL bound port once listening —
24
+ // pass 0 (the default) to let the OS pick a free one. This is the way to
25
+ // run several servers in parallel (per test worker/shard) without
26
+ // hand-assigning ports.
27
+ listen(port?: number): Promise<number>;
22
28
  stop(): Promise<void>;
23
29
  store: Store;
24
30
  broadcast: BroadcastFn;
@@ -80,15 +86,30 @@ export function createMockServer(config: MockServerConfig): MockServer {
80
86
  }
81
87
 
82
88
  const broadcast: BroadcastFn = (resourceName, operation, row) => {
89
+ const query = config.queries?.[resourceName];
90
+ // The query's own filter (where-clause equivalent) applies to live pushes
91
+ // too — a row the snapshot would exclude must not leak in via broadcast.
92
+ // DELETEs always go through: dropping an unknown ROW_REF is a no-op
93
+ // client-side, while a swallowed DELETE leaves a ghost row.
94
+ if (operation !== 'DELETE' && query?.filter && !query.filter(row)) return;
83
95
  for (const connection of connections) {
84
96
  for (const [sourceRef, subscription] of connection.subscriptions) {
85
97
  if (subscription.resourceName !== resourceName) continue;
86
98
  if (!subscriptionAccepts(subscription, sourceRef, operation, row)) continue;
99
+ // Per-user permissioning (auth maps / hideFields equivalent): the
100
+ // ROW_REF is computed from the unstripped row, since pk fields may
101
+ // themselves be hidden from this user.
102
+ let outRow = row;
103
+ if (operation !== 'DELETE' && query?.auth) {
104
+ const [permitted] = applyResourceAuth([row], query.auth, requestingUser(connection));
105
+ if (!permitted) continue;
106
+ outRow = permitted;
107
+ }
87
108
  subscription.sequenceId += 1;
88
109
  connection.send({
89
110
  MESSAGE_TYPE: 'QUERY_UPDATE',
90
111
  SOURCE_REF: sourceRef,
91
- ROW: [stampRow(row, subscription.pkField, operation)],
112
+ ROW: [stampRow(outRow, subscription.getRowRef(row), operation)],
92
113
  ROWS_COUNT: 1,
93
114
  SEQUENCE_ID: subscription.sequenceId,
94
115
  });
@@ -99,7 +120,9 @@ export function createMockServer(config: MockServerConfig): MockServer {
99
120
  // Event handlers mutate one table (e.g. TRADE) but grids may be subscribed to
100
121
  // a view built on top of it (e.g. ALL_TRADES -> TRADE_VIEW). This finds every
101
122
  // query resource backed by that table — directly or via a view — and pushes
102
- // the (re-joined, for views) row to each one's subscribers.
123
+ // the (re-joined, for views) row to each one's subscribers. `pk` is the
124
+ // store key: the single pk field's value, or store.rowKey(...) for
125
+ // composite-keyed tables.
103
126
  const broadcastTableChange: BroadcastTableChangeFn = (tableName, operation, pk) => {
104
127
  for (const [queryName, query] of Object.entries(config.queries ?? {})) {
105
128
  const isDirect = query.source === tableName;
@@ -107,14 +130,16 @@ export function createMockServer(config: MockServerConfig): MockServer {
107
130
  const isViewOnTable = view?.base === tableName;
108
131
  if (!isDirect && !isViewOnTable) continue;
109
132
 
110
- const pkField = store.getPkField(query.source);
111
133
  let row: Row | undefined;
112
134
  if (operation === 'DELETE') {
113
- row = pkField ? { [pkField]: pk } : undefined;
135
+ const stub = store.rowStubFromKey(query.source, pk);
136
+ row = Object.keys(stub).length > 0 ? stub : undefined;
114
137
  } else if (isDirect) {
115
138
  row = store.getRow(tableName, pk);
116
139
  } else {
117
- row = store.getViewRows(query.source).find((r) => r[pkField!] === pk);
140
+ row = store
141
+ .getViewRows(query.source)
142
+ .find((r) => String(store.getRowRef(query.source, r)) === String(pk));
118
143
  }
119
144
  if (row) broadcast(queryName, operation, row);
120
145
  }
@@ -222,6 +247,19 @@ export function createMockServer(config: MockServerConfig): MockServer {
222
247
  return;
223
248
  }
224
249
  try {
250
+ // Inbound hook: lets a project rewrite messages before routing
251
+ // (e.g. normalize a CRITERIA_MATCH dialect) or handle them fully
252
+ // itself (return false) — instead of monkey-patching ws.on.
253
+ if (config.onMessage) {
254
+ const hooked = config.onMessage(message, {
255
+ connection,
256
+ store,
257
+ broadcast,
258
+ broadcastTableChange,
259
+ });
260
+ if (hooked === false) return;
261
+ if (hooked) message = hooked;
262
+ }
225
263
  routeMessage(
226
264
  message,
227
265
  connection,
@@ -241,12 +279,38 @@ export function createMockServer(config: MockServerConfig): MockServer {
241
279
  });
242
280
 
243
281
  httpServer.listen(port);
244
- console.log(
245
- `[mock-server] Listening on ws://localhost:${port} (HTTP login endpoints on the same port)`,
246
- );
282
+ // Log the ACTUAL bound port once listening — with port 0 (ephemeral, the
283
+ // parallel-servers pattern) the requested port would read "0".
284
+ httpServer.once('listening', () => {
285
+ console.log(
286
+ `[mock-server] Listening on ws://localhost:${boundPort()} (HTTP login endpoints on the same port)`,
287
+ );
288
+ });
247
289
  return wss;
248
290
  }
249
291
 
292
+ function boundPort(): number | undefined {
293
+ const address = httpServer?.address();
294
+ return typeof address === 'object' && address ? address.port : undefined;
295
+ }
296
+
297
+ // start() + resolve with the OS-assigned port once actually listening.
298
+ // Pass no argument (port 0) to run any number of servers side by side —
299
+ // each instance's store/connections/sessions are fully isolated already,
300
+ // so parallel test workers just call listen() and hand the returned port
301
+ // to their own client (API_HOST=ws://localhost:<port>).
302
+ function listen(port = 0): Promise<number> {
303
+ return new Promise((resolve, reject) => {
304
+ if (httpServer?.listening) {
305
+ resolve(boundPort()!);
306
+ return;
307
+ }
308
+ if (!httpServer) start(port);
309
+ httpServer!.once('error', reject);
310
+ httpServer!.once('listening', () => resolve(boundPort()!));
311
+ });
312
+ }
313
+
250
314
  function stop(): Promise<void> {
251
315
  return new Promise((resolve) => {
252
316
  if (!wss || !httpServer) {
@@ -269,6 +333,7 @@ export function createMockServer(config: MockServerConfig): MockServer {
269
333
 
270
334
  return {
271
335
  start,
336
+ listen,
272
337
  stop,
273
338
  store,
274
339
  broadcast,
package/src/types.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // a real Genesis payload's shape is "whatever the project defines" (row data,
3
3
  // event DETAILS) — Record<string, any> there is the honest type, not a cop-out.
4
4
 
5
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
6
  import type { Store } from './db/store.ts';
6
7
 
7
8
  export type Row = Record<string, any>;
@@ -14,7 +15,12 @@ export interface GenesisMessage {
14
15
  }
15
16
 
16
17
  export interface TableDef {
17
- pkField: string;
18
+ // A single field, or several for composite-keyed tables (e.g. PRICE keyed
19
+ // by [RFQ_ID, SIDE]). Composite rows are identified by the fields' values
20
+ // joined with '|' (see Store.rowKey) — no synthetic key column needed, and
21
+ // nothing extra shows up in grids. Field values therefore must not contain
22
+ // '|' themselves. Sequence generation requires a single pkField.
23
+ pkField: string | string[];
18
24
  sequencePrefix?: string;
19
25
  sequenceWidth?: number;
20
26
  rows?: Row[];
@@ -24,24 +30,86 @@ export interface JoinDef {
24
30
  table: string;
25
31
  on: [string, string];
26
32
  select?: Record<string, string>;
33
+ // Extra join predicate beyond the `on` equality — receives the candidate
34
+ // join row and the base row, e.g. side-specific joins like
35
+ // (price, rfq) => price.SIDE === 'SALES'. When present, matching scans the
36
+ // join table per base row instead of using a prebuilt index (fine at mock
37
+ // scale).
38
+ where?: (joinRow: Row, baseRow: Row) => boolean;
39
+ }
40
+
41
+ // Keeps only base rows with NO match in `table` (e.g. USER_WITHOUT_DETAIL:
42
+ // users lacking a USER_DETAIL row). `where` narrows what counts as a match,
43
+ // same contract as JoinDef.where.
44
+ export interface AntiJoinDef {
45
+ table: string;
46
+ on: [string, string];
47
+ where?: (joinRow: Row, baseRow: Row) => boolean;
27
48
  }
28
49
 
29
50
  export interface ViewDef {
30
51
  base: string;
31
- pkField?: string;
52
+ pkField?: string | string[];
32
53
  joins?: JoinDef[];
54
+ antiJoins?: AntiJoinDef[];
33
55
  derived?: Record<string, (row: Row) => any>;
34
56
  }
35
57
 
58
+ // The authenticated identity a resource-level auth hook sees. userName is
59
+ // undefined for unauthenticated connections (possible when requireAuth is
60
+ // off, or pre-login).
61
+ export interface RequestingUser {
62
+ userName?: string;
63
+ profile: string[];
64
+ permission: string[];
65
+ }
66
+
67
+ // Per-resource permissioning, mirroring what dataserver auth maps and
68
+ // hideFields do on the real server: rowFilter drops rows the user must not
69
+ // see (applied to snapshots, live pushes, and REQ_ replies); hideFields
70
+ // strips columns from rows AND from META_REQUEST field metadata, so e.g.
71
+ // sales users never see the trader side of mirrored columns.
72
+ export interface ResourceAuthDef {
73
+ rowFilter?: (row: Row, user: RequestingUser) => boolean;
74
+ hideFields?: string[] | ((user: RequestingUser) => string[]);
75
+ }
76
+
36
77
  export interface QueryDef {
37
78
  source: string;
38
79
  fieldTypes?: Record<string, string>;
80
+ // Server-side where-clause equivalent, applied before any client
81
+ // CRITERIA_MATCH — to both the DATA_LOGON snapshot and live pushes. Use it
82
+ // for things the real query's filter/where clause does (e.g. keep template
83
+ // rows out of ALL_QTE_MAIN_ENTRIES, CANCELLED out of the blotter).
84
+ filter?: (row: Row) => boolean;
85
+ auth?: ResourceAuthDef;
86
+ }
87
+
88
+ // Details a request-reply resolver receives: the keyed REQUEST fields, the
89
+ // full message, the requesting user, and the live store.
90
+ export interface RequestReplyResolverCtx {
91
+ request: Row;
92
+ message: GenesisMessage;
93
+ user: RequestingUser;
94
+ store: Store;
39
95
  }
40
96
 
41
97
  export interface RequestReplyDef {
42
- source: string;
98
+ // Either serve rows from a table/view (`source`, optionally narrowed by
99
+ // `filter`/REQUEST fields/CRITERIA_MATCH), or compute the reply yourself
100
+ // (`resolver`) — for request servers that calculate rather than read (date
101
+ // calculations, holiday validate/roll, premium schedules, composite
102
+ // lookups). A resolver receives the REQUEST fields and returns the REPLY
103
+ // rows verbatim; throw NackError for a protocol-correct error reply. When
104
+ // both are set, resolver wins. With resolver only, set `metadataRows` (a
105
+ // representative sample reply) or `fieldTypes` so META_REQUEST can still
106
+ // derive REPLY_FIELD metadata.
107
+ source?: string;
108
+ resolver?: (ctx: RequestReplyResolverCtx) => Row[];
109
+ metadataRows?: Row[];
43
110
  fieldTypes?: Record<string, string>;
44
111
  filter?: (row: Row) => boolean;
112
+ auth?: ResourceAuthDef;
45
113
  }
46
114
 
47
115
  export interface EventSchemaOverride {
@@ -63,8 +131,25 @@ export interface AuthUser {
63
131
  user?: Row;
64
132
  }
65
133
 
134
+ // Entry served from GET gwf/sso/list, matching foundation-auth's
135
+ // IDENTITY_PROVIDER DTO (services/idp.ts): { ID, DESCRIPTION, TYPE }.
136
+ export interface SsoIdentityProvider {
137
+ ID: string;
138
+ DESCRIPTION?: string;
139
+ TYPE?: string;
140
+ [key: string]: any;
141
+ }
142
+
66
143
  export interface AuthConfig {
67
144
  users?: AuthUser[];
145
+ // Served from GET gwf/sso/list as { IDPS: [...] }. foundation-auth's login
146
+ // screen fetches this whenever sso.toggled is on, shows a red "Failed to
147
+ // fetch identity providers" AND hides the credentials form if the fetch
148
+ // fails, and rejects an empty list too ("Identity provider list empty") —
149
+ // so when unset, the mock serves one non-functional placeholder provider
150
+ // to keep the login screen rendering. Clicking it navigates to the real
151
+ // SSO login URL template, which the mock does not implement.
152
+ ssoIdentityProviders?: SsoIdentityProvider[];
68
153
  heartbeatIntervalSecs?: number;
69
154
  // A username to always ack gwf/event-login-details as (skips the login
70
155
  // screen entirely), or `true` to use the first configured user.
@@ -100,15 +185,51 @@ export type EventHandlerResult = { generated?: Row[] } | void;
100
185
 
101
186
  export type EventHandler = (details: Row, ctx: EventHandlerCtx) => EventHandlerResult;
102
187
 
188
+ // Extra HTTP route served by the engine's shared http.Server — for project
189
+ // endpoints the protocol doesn't cover (e.g. GET pbi/configs). Routes are
190
+ // tried FIRST, before the built-in login/SSO handlers, so they can also
191
+ // override those. A string path matches pathname.endsWith(path) (same
192
+ // convention as the built-ins, which tolerates any gateway prefix); a RegExp
193
+ // is tested against the full pathname.
194
+ export interface HttpRouteDef {
195
+ method?: string;
196
+ path: string | RegExp;
197
+ handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
198
+ }
199
+
200
+ export interface OnMessageCtx {
201
+ connection: import('./protocol/connection.ts').Connection;
202
+ store: Store;
203
+ broadcast: BroadcastFn;
204
+ broadcastTableChange: BroadcastTableChangeFn;
205
+ }
206
+
207
+ // Inbound-message hook, called for every parsed WS message BEFORE routing.
208
+ // Return a message (possibly rewritten — e.g. normalizing a CRITERIA_MATCH
209
+ // dialect) to continue routing with it, `false` if the hook fully handled
210
+ // the message itself (reply via ctx.connection.reply), or nothing to route
211
+ // the original unchanged.
212
+ export type OnMessageHook = (
213
+ message: GenesisMessage,
214
+ ctx: OnMessageCtx,
215
+ ) => GenesisMessage | false | void;
216
+
103
217
  export interface MockServerConfig {
104
218
  tables?: Record<string, TableDef>;
105
219
  views?: Record<string, ViewDef>;
106
220
  queries?: Record<string, QueryDef>;
107
221
  requestReplies?: Record<string, RequestReplyDef>;
108
222
  eventHandlers?: Record<string, EventHandler>;
223
+ // Fallback for commit events with no registered handler — lets a project
224
+ // with many events adopt incrementally (e.g. `() => ({})` acks everything
225
+ // unhandled) instead of enumerating ack-only handlers. Unregistered events
226
+ // NACK with UNKNOWN_RESOURCE when this is unset.
227
+ defaultEventHandler?: EventHandler;
109
228
  eventSchemas?: Record<string, EventSchemaOverride>;
110
229
  auth?: AuthConfig;
111
230
  resources?: ResourceItem[];
231
+ httpRoutes?: HttpRouteDef[];
232
+ onMessage?: OnMessageHook;
112
233
  productName?: string;
113
234
  }
114
235
 
@@ -1,174 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import { describe, it } from 'node:test';
3
- import { compileCriteria, filterByCriteria } from '../src/db/criteria.ts';
4
-
5
- const TRADE = {
6
- TRADE_ID: 'TR001',
7
- TRADE_STATUS: 'CONFIRMED',
8
- SIDE: 'BUY',
9
- QUANTITY: 150,
10
- PRICE: 105.5,
11
- ENABLED: true,
12
- NOTES: null,
13
- COUNTERPARTY_NAME: "O'Brien Securities",
14
- TRADE_DATE: Date.UTC(2024, 5, 15, 10, 30, 0), // 2024-06-15T10:30Z as epoch millis
15
- };
16
-
17
- describe('compileCriteria comparisons', () => {
18
- it('matches string equality with == and =', () => {
19
- assert.equal(compileCriteria("TRADE_STATUS == 'CONFIRMED'")(TRADE), true);
20
- assert.equal(compileCriteria("TRADE_STATUS = 'CONFIRMED'")(TRADE), true);
21
- assert.equal(compileCriteria("TRADE_STATUS == 'PENDING'")(TRADE), false);
22
- });
23
-
24
- it('matches inequality with != and <>', () => {
25
- assert.equal(compileCriteria("SIDE != 'SELL'")(TRADE), true);
26
- assert.equal(compileCriteria("SIDE <> 'SELL'")(TRADE), true);
27
- assert.equal(compileCriteria("SIDE != 'BUY'")(TRADE), false);
28
- });
29
-
30
- it('compares numbers with > >= < <=', () => {
31
- assert.equal(compileCriteria('QUANTITY > 100')(TRADE), true);
32
- assert.equal(compileCriteria('QUANTITY >= 150')(TRADE), true);
33
- assert.equal(compileCriteria('QUANTITY < 150')(TRADE), false);
34
- assert.equal(compileCriteria('QUANTITY <= 150')(TRADE), true);
35
- assert.equal(compileCriteria('PRICE > 105.4')(TRADE), true);
36
- assert.equal(compileCriteria('PRICE > -1')(TRADE), true);
37
- });
38
-
39
- it('matches boolean and null literals', () => {
40
- assert.equal(compileCriteria('ENABLED == true')(TRADE), true);
41
- assert.equal(compileCriteria('ENABLED == false')(TRADE), false);
42
- assert.equal(compileCriteria('NOTES == null')(TRADE), true);
43
- });
44
-
45
- it('handles double-quoted strings and escaped quotes', () => {
46
- assert.equal(compileCriteria('SIDE == "BUY"')(TRADE), true);
47
- assert.equal(compileCriteria("COUNTERPARTY_NAME == 'O\\'Brien Securities'")(TRADE), true);
48
- });
49
-
50
- it('equality is strict — numeric field never equals a string literal', () => {
51
- assert.equal(compileCriteria("QUANTITY == '150'")(TRADE), false);
52
- });
53
- });
54
-
55
- describe('compileCriteria boolean operators', () => {
56
- it('supports AND / OR / NOT keywords case-insensitively and && / ||', () => {
57
- assert.equal(compileCriteria("SIDE == 'BUY' AND QUANTITY > 100")(TRADE), true);
58
- assert.equal(compileCriteria("SIDE == 'BUY' and QUANTITY > 999")(TRADE), false);
59
- assert.equal(compileCriteria("SIDE == 'SELL' OR QUANTITY > 100")(TRADE), true);
60
- assert.equal(compileCriteria("SIDE == 'SELL' || QUANTITY > 100")(TRADE), true);
61
- assert.equal(compileCriteria("SIDE == 'BUY' && QUANTITY > 100")(TRADE), true);
62
- assert.equal(compileCriteria("NOT SIDE == 'SELL'")(TRADE), true);
63
- });
64
-
65
- it('binds AND tighter than OR', () => {
66
- // Parses as A OR (B AND C), which is true; ((A OR B) AND C) would be false.
67
- const predicate = compileCriteria(
68
- "SIDE == 'SELL' OR TRADE_STATUS == 'CONFIRMED' AND QUANTITY > 100",
69
- );
70
- assert.equal(predicate(TRADE), true);
71
- const flipped = compileCriteria(
72
- "(SIDE == 'SELL' OR TRADE_STATUS == 'CONFIRMED') AND QUANTITY > 999",
73
- );
74
- assert.equal(flipped(TRADE), false);
75
- });
76
-
77
- it('honors parentheses and NOT of a group', () => {
78
- assert.equal(compileCriteria("NOT (SIDE == 'SELL') OR PRICE >= 999")(TRADE), true);
79
- assert.equal(compileCriteria("NOT (SIDE == 'BUY' AND QUANTITY > 100)")(TRADE), false);
80
- });
81
- });
82
-
83
- describe('compileCriteria Expr.* functions', () => {
84
- it('contains / containsIgnoreCase', () => {
85
- assert.equal(compileCriteria("Expr.contains(COUNTERPARTY_NAME, 'Brien')")(TRADE), true);
86
- assert.equal(compileCriteria("Expr.contains(COUNTERPARTY_NAME, 'brien')")(TRADE), false);
87
- assert.equal(
88
- compileCriteria("Expr.containsIgnoreCase(COUNTERPARTY_NAME, 'brien')")(TRADE),
89
- true,
90
- );
91
- assert.equal(compileCriteria("Expr.contains(QUANTITY, '15')")(TRADE), false); // non-string field
92
- });
93
-
94
- it('dateIs* compares by calendar day against YYYYMMDD-HH:MM[:SS] literals', () => {
95
- assert.equal(compileCriteria("Expr.dateIsEqual(TRADE_DATE, '20240615-00:00')")(TRADE), true);
96
- assert.equal(compileCriteria("Expr.dateIsEqual(TRADE_DATE, '20240616-00:00')")(TRADE), false);
97
- assert.equal(
98
- compileCriteria("Expr.dateIsGreaterEqual(TRADE_DATE, '20240615-23:59')")(TRADE),
99
- true, // same calendar day, time-of-day ignored
100
- );
101
- assert.equal(
102
- compileCriteria("Expr.dateIsLessEqual(TRADE_DATE, '20240614-00:00')")(TRADE),
103
- false,
104
- );
105
- });
106
-
107
- it('dateTimeIs* compares full timestamps (After/Before alias >= / <=)', () => {
108
- assert.equal(
109
- compileCriteria("Expr.dateTimeIsEqual(TRADE_DATE, '20240615-10:30:00')")(TRADE),
110
- true,
111
- );
112
- assert.equal(
113
- compileCriteria("Expr.dateTimeIsGreaterEqual(TRADE_DATE, '20240615-10:30:01')")(TRADE),
114
- false,
115
- );
116
- assert.equal(
117
- compileCriteria("Expr.dateTimeIsAfter(TRADE_DATE, '20240615-10:00')")(TRADE),
118
- true,
119
- );
120
- assert.equal(
121
- compileCriteria("Expr.dateTimeIsBefore(TRADE_DATE, '20240615-11:00')")(TRADE),
122
- true,
123
- );
124
- assert.equal(compileCriteria('Expr.dateIsToday(TRADE_DATE)')(TRADE), false);
125
- });
126
-
127
- it('date functions return false (not throw) for unparseable values', () => {
128
- assert.equal(compileCriteria("Expr.dateIsEqual(SIDE, '20240615-00:00')")(TRADE), false);
129
- assert.equal(compileCriteria("Expr.dateTimeIsEqual(NOTES, '20240615-00:00')")(TRADE), false);
130
- });
131
- });
132
-
133
- describe('compileCriteria fail-open behavior', () => {
134
- it('matches everything for empty or missing criteria', () => {
135
- assert.equal(compileCriteria(undefined)(TRADE), true);
136
- assert.equal(compileCriteria(null)(TRADE), true);
137
- assert.equal(compileCriteria(' ')(TRADE), true);
138
- });
139
-
140
- it('fails open on untokenizable input', () => {
141
- assert.equal(compileCriteria('£$%^ not a criteria')(TRADE), true);
142
- });
143
-
144
- it('fails open on trailing tokens', () => {
145
- assert.equal(compileCriteria("SIDE == 'SELL' QUANTITY")(TRADE), true);
146
- });
147
-
148
- it('fails open on an unknown Expr function', () => {
149
- assert.equal(compileCriteria("Expr.noSuchFn(SIDE, 'BUY')")(TRADE), true);
150
- });
151
-
152
- it('fails open on unbalanced parentheses', () => {
153
- assert.equal(compileCriteria("(SIDE == 'SELL'")(TRADE), true);
154
- });
155
- });
156
-
157
- describe('filterByCriteria', () => {
158
- const rows = [
159
- { ID: 'A', STATUS: 'OPEN', QTY: 10 },
160
- { ID: 'B', STATUS: 'CLOSED', QTY: 20 },
161
- { ID: 'C', STATUS: 'OPEN', QTY: 30 },
162
- ];
163
-
164
- it('filters rows by the compiled predicate', () => {
165
- assert.deepEqual(
166
- filterByCriteria(rows, "STATUS == 'OPEN' AND QTY > 15").map((r) => r.ID),
167
- ['C'],
168
- );
169
- });
170
-
171
- it('returns all rows when criteria is absent', () => {
172
- assert.equal(filterByCriteria(rows, undefined).length, 3);
173
- });
174
- });
@@ -1,38 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import { describe, it } from 'node:test';
3
- import { inferEventTable } from '../src/handlers/jsonSchema.ts';
4
-
5
- const TABLES = ['TRADE', 'COUNTERPARTY', 'COUNTERPARTY_AUTH', 'POSITION'];
6
-
7
- describe('inferEventTable', () => {
8
- it('maps EVENT_<TABLE>_<VERB> to the table', () => {
9
- assert.equal(inferEventTable('EVENT_TRADE_INSERT', TABLES), 'TRADE');
10
- assert.equal(inferEventTable('EVENT_POSITION_DELETE', TABLES), 'POSITION');
11
- });
12
-
13
- it('handles suffixed verb variants', () => {
14
- assert.equal(
15
- inferEventTable('EVENT_COUNTERPARTY_INSERT_WITH_APPROVAL', TABLES),
16
- 'COUNTERPARTY',
17
- );
18
- assert.equal(inferEventTable('EVENT_TRADE_MODIFY_PRICE', TABLES), 'TRADE');
19
- assert.equal(inferEventTable('EVENT_TRADE_INSERT_FAIL', TABLES), 'TRADE');
20
- });
21
-
22
- it('prefers the longest matching table name', () => {
23
- assert.equal(inferEventTable('EVENT_COUNTERPARTY_AUTH_MODIFY', TABLES), 'COUNTERPARTY_AUTH');
24
- assert.equal(inferEventTable('EVENT_COUNTERPARTY_MODIFY', TABLES), 'COUNTERPARTY');
25
- });
26
-
27
- it('matches an exact EVENT_<TABLE> with no verb', () => {
28
- assert.equal(inferEventTable('EVENT_TRADE', TABLES), 'TRADE');
29
- });
30
-
31
- it('returns undefined for non-EVENT names, unknown tables, and missing input', () => {
32
- assert.equal(inferEventTable('REQ_TRADE', TABLES), undefined);
33
- assert.equal(inferEventTable('EVENT_ORDER_INSERT', TABLES), undefined);
34
- assert.equal(inferEventTable(undefined, TABLES), undefined);
35
- // Prefix of a table name is not a match — TRADES is not TRADE.
36
- assert.equal(inferEventTable('EVENT_TRADES_INSERT', TABLES), undefined);
37
- });
38
- });
@@ -1,49 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import { describe, it } from 'node:test';
3
- import { deriveFields } from '../src/db/metadata.ts';
4
-
5
- describe('deriveFields', () => {
6
- it('covers every key seen across rows, in first-seen order', () => {
7
- const fields = deriveFields([
8
- { A: 1, B: 'x' },
9
- { B: 'y', C: true },
10
- ]);
11
- assert.deepEqual(
12
- fields.map((f) => f.NAME),
13
- ['A', 'B', 'C'],
14
- );
15
- });
16
-
17
- it('infers LONG only when every numeric value is whole', () => {
18
- const [qty] = deriveFields([{ QTY: 100 }, { QTY: 250 }]);
19
- assert.deepEqual(qty, { NAME: 'QTY', TYPE: 'LONG' });
20
- });
21
-
22
- it('infers DOUBLE when any row holds a fractional value, even if the first is whole', () => {
23
- const [price] = deriveFields([{ PRICE: 100 }, { PRICE: 100.5 }, { PRICE: 99 }]);
24
- assert.deepEqual(price, { NAME: 'PRICE', TYPE: 'DOUBLE' });
25
- });
26
-
27
- it('infers BOOLEAN and STRING from the first non-null value', () => {
28
- const fields = deriveFields([
29
- { ENABLED: null, NAME: null },
30
- { ENABLED: true, NAME: 'x' },
31
- ]);
32
- assert.deepEqual(fields, [
33
- { NAME: 'ENABLED', TYPE: 'BOOLEAN' },
34
- { NAME: 'NAME', TYPE: 'STRING' },
35
- ]);
36
- });
37
-
38
- it('defaults to STRING for all-null fields and applies overrides', () => {
39
- const fields = deriveFields([{ EMPTY: null, NOTIONAL: 105000 }], { NOTIONAL: 'DOUBLE' });
40
- assert.deepEqual(fields, [
41
- { NAME: 'EMPTY', TYPE: 'STRING' },
42
- { NAME: 'NOTIONAL', TYPE: 'DOUBLE' },
43
- ]);
44
- });
45
-
46
- it('returns an empty list for no rows', () => {
47
- assert.deepEqual(deriveFields([]), []);
48
- });
49
- });