@genesislcap/mock-server 15.7.3-alpha-277c463.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.
- package/README.md +237 -52
- package/dist/db/criteria.d.ts +5 -0
- package/dist/db/criteria.js +304 -0
- package/dist/db/metadata.d.ts +3 -0
- package/dist/db/metadata.js +35 -0
- package/dist/db/store.d.ts +27 -0
- package/dist/db/store.js +226 -0
- package/dist/handlers/auth.d.ts +9 -0
- package/dist/handlers/auth.js +99 -0
- package/dist/handlers/commitEvent.d.ts +8 -0
- package/dist/handlers/commitEvent.js +40 -0
- package/dist/handlers/dataLogon.d.ts +5 -0
- package/dist/handlers/dataLogon.js +46 -0
- package/dist/handlers/heartbeat.d.ts +3 -0
- package/dist/handlers/heartbeat.js +16 -0
- package/dist/handlers/http.d.ts +4 -0
- package/dist/handlers/http.js +165 -0
- package/dist/handlers/jsonSchema.d.ts +5 -0
- package/dist/handlers/jsonSchema.js +77 -0
- package/dist/handlers/meta.d.ts +4 -0
- package/dist/handlers/meta.js +42 -0
- package/dist/handlers/requestReply.d.ts +4 -0
- package/dist/handlers/requestReply.js +68 -0
- package/dist/handlers/resourceAuth.d.ts +5 -0
- package/dist/handlers/resourceAuth.js +27 -0
- package/dist/handlers/resources.d.ts +3 -0
- package/dist/handlers/resources.js +34 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/launch.d.ts +19 -0
- package/dist/launch.js +59 -0
- package/dist/protocol/connection.d.ts +24 -0
- package/dist/protocol/connection.js +35 -0
- package/dist/protocol/errors.d.ts +17 -0
- package/dist/protocol/errors.js +16 -0
- package/dist/protocol/messageTypes.d.ts +28 -0
- package/dist/protocol/messageTypes.js +42 -0
- package/dist/protocol/router.d.ts +6 -0
- package/dist/protocol/router.js +101 -0
- package/dist/protocol/rowUpdate.d.ts +4 -0
- package/dist/protocol/rowUpdate.js +17 -0
- package/dist/server.d.ts +23 -0
- package/dist/server.js +274 -0
- package/dist/types.d.ts +142 -0
- package/dist/types.js +4 -0
- package/package.json +16 -6
- package/src/db/criteria.ts +53 -21
- package/src/db/store.ts +100 -27
- package/src/handlers/commitEvent.ts +13 -5
- package/src/handlers/dataLogon.ts +11 -4
- package/src/handlers/heartbeat.ts +16 -3
- package/src/handlers/http.ts +27 -0
- package/src/handlers/jsonSchema.ts +3 -3
- package/src/handlers/meta.ts +11 -3
- package/src/handlers/requestReply.ts +22 -8
- package/src/handlers/resourceAuth.ts +37 -0
- package/src/handlers/resources.ts +8 -1
- package/src/index.ts +9 -0
- package/src/launch.ts +95 -0
- package/src/protocol/connection.ts +3 -1
- package/src/protocol/messageTypes.ts +9 -0
- package/src/protocol/router.ts +19 -12
- package/src/protocol/rowUpdate.ts +5 -4
- package/src/server.ts +73 -8
- package/src/types.ts +132 -8
- package/test/criteria.test.ts +0 -174
- package/test/jsonSchema.test.ts +0 -38
- package/test/metadata.test.ts +0 -49
- package/test/server.test.ts +0 -289
- package/test/store.test.ts +0 -181
- package/tsconfig.json +0 -18
package/package.json
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@genesislcap/mock-server",
|
|
3
|
-
"version": "15.7.3-alpha-
|
|
3
|
+
"version": "15.7.3-alpha-e7d4aa5.0",
|
|
4
4
|
"description": "Reusable in-memory Genesis WebSocket protocol mock server for client automation/CI, without a JVM or database.",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"main": "
|
|
7
|
-
"types": "
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
|
-
".":
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"bun": "./src/index.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
10
14
|
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"src",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
11
20
|
"scripts": {
|
|
12
|
-
"build": "
|
|
21
|
+
"build": "tsc -p tsconfig.build.json",
|
|
22
|
+
"build:watch": "tsc -p tsconfig.build.json --watch",
|
|
13
23
|
"lint": "echo \"@genesislcap/mock-server: no lint step\"",
|
|
14
24
|
"typecheck": "tsc --noEmit",
|
|
15
25
|
"test": "node --experimental-strip-types --test"
|
|
@@ -33,5 +43,5 @@
|
|
|
33
43
|
"publishConfig": {
|
|
34
44
|
"access": "public"
|
|
35
45
|
},
|
|
36
|
-
"gitHead": "
|
|
46
|
+
"gitHead": "47329b0160faf49d52b2964ea22ed9362f275130"
|
|
37
47
|
}
|
package/src/db/criteria.ts
CHANGED
|
@@ -3,10 +3,15 @@
|
|
|
3
3
|
// NOT (SIDE == 'SELL') OR PRICE >= 100.5
|
|
4
4
|
// Expr.dateTimeIsGreaterEqual(TRADE_DATE, '20240101-00:00:00') && COUNTERPARTY_ID == 'CPTY001'
|
|
5
5
|
//
|
|
6
|
-
// Supports: == = != <> > >= < <=, AND OR NOT (also && ||), parentheses,
|
|
7
|
-
// string/number/boolean literals, bare field identifiers, and
|
|
8
|
-
//
|
|
9
|
-
//
|
|
6
|
+
// Supports: == = != <> > >= < <=, AND OR NOT (also && || !), parentheses,
|
|
7
|
+
// string/number/boolean literals, bare field identifiers, and two
|
|
8
|
+
// function-call dialects real clients emit:
|
|
9
|
+
// - `Expr.<fn>(field, value)` — foundation-criteria's serialisers.ts
|
|
10
|
+
// (grid date/text filters);
|
|
11
|
+
// - `<FIELD>.<fn>(value)` method-call form — e.g.
|
|
12
|
+
// `DEAL_CURRENCIES.containsIgnoreCase('USD')`, as emitted by
|
|
13
|
+
// project-level filter builders. Same EXPR_FUNCTIONS, with the receiver
|
|
14
|
+
// field as the implicit first argument.
|
|
10
15
|
// Deliberately NOT eval()/new Function() — this parses a small typed grammar
|
|
11
16
|
// so a malformed or hostile criteria string can only fail to parse, never
|
|
12
17
|
// execute arbitrary JS.
|
|
@@ -16,7 +21,7 @@ import type { Row } from '../types.ts';
|
|
|
16
21
|
export type Predicate = (record: Row) => boolean;
|
|
17
22
|
|
|
18
23
|
const TOKEN_RE =
|
|
19
|
-
/\s*(
|
|
24
|
+
/\s*(&&|\|\||<=|>=|!=|<>|==|=|<|>|!|\(|\)|,|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_.]*)/g;
|
|
20
25
|
|
|
21
26
|
function tokenize(input: string): string[] {
|
|
22
27
|
const tokens: string[] = [];
|
|
@@ -47,16 +52,28 @@ function parseLiteral(token: string): unknown {
|
|
|
47
52
|
|
|
48
53
|
const COMPARATORS = new Set(['==', '=', '!=', '<>', '<', '<=', '>', '>=']);
|
|
49
54
|
|
|
50
|
-
// Genesis date/datetime values serialize as 'YYYYMMDD-HH:MM[:SS]'
|
|
51
|
-
// foundation-criteria's serialisers.ts formatDate
|
|
52
|
-
//
|
|
55
|
+
// Genesis date/datetime values serialize as 'YYYYMMDD-HH:MM[:SS[.mmm]]' —
|
|
56
|
+
// foundation-criteria's serialisers.ts formatDate stops at seconds, but
|
|
57
|
+
// getGroovyDateFormat() emits milliseconds too, and a parser that rejects
|
|
58
|
+
// them makes every Expr.dateTimeIs* comparison silently false (date-filtered
|
|
59
|
+
// grids render zero rows with no warning). Row values may already be epoch
|
|
60
|
+
// millis (number) or an ISO string. Returns null if unparseable.
|
|
53
61
|
function parseGenesisDateTime(value: unknown): number | null {
|
|
54
62
|
if (typeof value === 'number') return value;
|
|
55
63
|
if (typeof value !== 'string') return null;
|
|
56
|
-
const match = value.match(/^(\d{4})(\d{2})(\d{2})-(\d{2}):(\d{2})(?::(\d{2}))?$/);
|
|
64
|
+
const match = value.match(/^(\d{4})(\d{2})(\d{2})-(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/);
|
|
57
65
|
if (match) {
|
|
58
|
-
const
|
|
59
|
-
|
|
66
|
+
const MS_DIGITS = 3; // '.5' means 500ms, not 5ms — right-pad to full precision
|
|
67
|
+
const [, y, mo, d, h, mi, s, ms] = match;
|
|
68
|
+
return Date.UTC(
|
|
69
|
+
Number(y),
|
|
70
|
+
Number(mo) - 1,
|
|
71
|
+
Number(d),
|
|
72
|
+
Number(h),
|
|
73
|
+
Number(mi),
|
|
74
|
+
Number(s ?? '0'),
|
|
75
|
+
Number((ms ?? '0').padEnd(MS_DIGITS, '0')),
|
|
76
|
+
);
|
|
60
77
|
}
|
|
61
78
|
const parsed = Date.parse(value);
|
|
62
79
|
return Number.isNaN(parsed) ? null : parsed;
|
|
@@ -85,19 +102,24 @@ const EXPR_FUNCTIONS: Record<
|
|
|
85
102
|
string,
|
|
86
103
|
(record: Row, args: string[], resolve: ExprResolver) => boolean
|
|
87
104
|
> = {
|
|
105
|
+
// Multi-value fields (e.g. DEAL_CURRENCIES) may hold an array — treat
|
|
106
|
+
// "contains" as membership there, substring match on strings.
|
|
88
107
|
contains: (record, args, resolve) => {
|
|
89
108
|
const value = resolve(args[0], record);
|
|
90
109
|
const needle = resolve(args[1], record);
|
|
91
|
-
|
|
110
|
+
if (typeof needle !== 'string') return false;
|
|
111
|
+
if (Array.isArray(value)) return value.some((v) => typeof v === 'string' && v === needle);
|
|
112
|
+
return typeof value === 'string' && value.includes(needle);
|
|
92
113
|
},
|
|
93
114
|
containsIgnoreCase: (record, args, resolve) => {
|
|
94
115
|
const value = resolve(args[0], record);
|
|
95
116
|
const needle = resolve(args[1], record);
|
|
96
|
-
return
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
value.
|
|
100
|
-
|
|
117
|
+
if (typeof needle !== 'string') return false;
|
|
118
|
+
const lowered = needle.toLowerCase();
|
|
119
|
+
if (Array.isArray(value)) {
|
|
120
|
+
return value.some((v) => typeof v === 'string' && v.toLowerCase() === lowered);
|
|
121
|
+
}
|
|
122
|
+
return typeof value === 'string' && value.toLowerCase().includes(lowered);
|
|
101
123
|
},
|
|
102
124
|
dateIsToday: (record, args, resolve) => {
|
|
103
125
|
const day = toEpochDay(resolve(args[0], record));
|
|
@@ -190,7 +212,8 @@ class Parser {
|
|
|
190
212
|
}
|
|
191
213
|
|
|
192
214
|
parseNot(): Predicate {
|
|
193
|
-
|
|
215
|
+
const next = this.peek();
|
|
216
|
+
if (next === '!' || next?.toUpperCase() === 'NOT') {
|
|
194
217
|
this.next();
|
|
195
218
|
const operand = this.parseNot();
|
|
196
219
|
return (record) => !operand(record);
|
|
@@ -211,7 +234,10 @@ class Parser {
|
|
|
211
234
|
throw new Error('Expected operand on the left side of comparison');
|
|
212
235
|
}
|
|
213
236
|
|
|
214
|
-
|
|
237
|
+
// Both function-call dialects arrive as one dotted token followed by '(':
|
|
238
|
+
// 'Expr.containsIgnoreCase' (foundation-criteria) or
|
|
239
|
+
// 'DEAL_CURRENCIES.containsIgnoreCase' (field method-call form).
|
|
240
|
+
if (leftToken.includes('.') && this.peek() === '(') {
|
|
215
241
|
return this.parseFunctionCall(leftToken);
|
|
216
242
|
}
|
|
217
243
|
|
|
@@ -274,12 +300,18 @@ class Parser {
|
|
|
274
300
|
}
|
|
275
301
|
if (this.next() !== ')') throw new Error(`Missing closing parenthesis in ${name}(...)`);
|
|
276
302
|
|
|
277
|
-
|
|
303
|
+
// 'Expr.<fn>(field, value)' passes args through as-is; the method-call
|
|
304
|
+
// form '<FIELD>.<fn>(value)' makes the receiver field the implicit first
|
|
305
|
+
// argument, so both dialects share EXPR_FUNCTIONS.
|
|
306
|
+
const dotIndex = name.lastIndexOf('.');
|
|
307
|
+
const receiver = name.slice(0, dotIndex);
|
|
308
|
+
const fnName = name.slice(dotIndex + 1);
|
|
278
309
|
const handler = EXPR_FUNCTIONS[fnName];
|
|
279
310
|
if (!handler) throw new Error(`Unsupported criteria function: ${name}`);
|
|
311
|
+
const allArgs = receiver === 'Expr' ? args : [receiver, ...args];
|
|
280
312
|
|
|
281
313
|
const resolve: ExprResolver = (token, record) => this.resolveValue(token, record);
|
|
282
|
-
return (record: Row) => handler(record,
|
|
314
|
+
return (record: Row) => handler(record, allArgs, resolve);
|
|
283
315
|
}
|
|
284
316
|
}
|
|
285
317
|
|
package/src/db/store.ts
CHANGED
|
@@ -6,11 +6,25 @@ import type { Row, TableDef, ViewDef } from '../types.ts';
|
|
|
6
6
|
type Pk = string;
|
|
7
7
|
|
|
8
8
|
interface TableConfig {
|
|
9
|
-
|
|
9
|
+
pkFields: string[];
|
|
10
10
|
sequencePrefix?: string;
|
|
11
11
|
sequenceWidth: number;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
// Composite keys join the pk fields' values with '|' (so values must not
|
|
15
|
+
// contain '|'). Single-field keys stay the raw value, preserving
|
|
16
|
+
// getRow('TABLE', 'TR001')-style lookups.
|
|
17
|
+
const COMPOSITE_KEY_SEPARATOR = '|';
|
|
18
|
+
|
|
19
|
+
function normalizePkFields(pkField: string | string[]): string[] {
|
|
20
|
+
return Array.isArray(pkField) ? pkField : [pkField];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function keyFor(pkFields: string[], row: Row): Pk {
|
|
24
|
+
if (pkFields.length === 1) return row[pkFields[0]];
|
|
25
|
+
return pkFields.map((field) => String(row[field])).join(COMPOSITE_KEY_SEPARATOR);
|
|
26
|
+
}
|
|
27
|
+
|
|
14
28
|
export class Store {
|
|
15
29
|
private tables = new Map<string, Map<Pk, Row>>();
|
|
16
30
|
private tableConfig = new Map<string, TableConfig>();
|
|
@@ -25,21 +39,23 @@ export class Store {
|
|
|
25
39
|
tableName: string,
|
|
26
40
|
{ pkField, sequencePrefix, sequenceWidth = 3, rows = [] }: TableDef,
|
|
27
41
|
): this {
|
|
42
|
+
const pkFields = normalizePkFields(pkField);
|
|
28
43
|
const table = new Map<Pk, Row>();
|
|
29
44
|
for (const row of rows) {
|
|
30
|
-
table.set(row
|
|
45
|
+
table.set(keyFor(pkFields, row), { ...row });
|
|
31
46
|
}
|
|
32
47
|
this.tables.set(tableName, table);
|
|
33
|
-
this.tableConfig.set(tableName, {
|
|
48
|
+
this.tableConfig.set(tableName, { pkFields, sequencePrefix, sequenceWidth });
|
|
34
49
|
this.seedRows.set(
|
|
35
50
|
tableName,
|
|
36
51
|
rows.map((row) => ({ ...row })),
|
|
37
52
|
);
|
|
38
53
|
|
|
39
|
-
|
|
54
|
+
// Sequence generation only makes sense for a single-field pk.
|
|
55
|
+
if (sequencePrefix && pkFields.length === 1) {
|
|
40
56
|
let maxN = 0;
|
|
41
57
|
for (const row of rows) {
|
|
42
|
-
const pk = String(row[
|
|
58
|
+
const pk = String(row[pkFields[0]] ?? '');
|
|
43
59
|
if (pk.startsWith(sequencePrefix)) {
|
|
44
60
|
const n = parseInt(pk.slice(sequencePrefix.length), 10);
|
|
45
61
|
if (Number.isFinite(n)) maxN = Math.max(maxN, n);
|
|
@@ -71,16 +87,26 @@ export class Store {
|
|
|
71
87
|
return this.tables.get(tableName)?.get(pk);
|
|
72
88
|
}
|
|
73
89
|
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
//
|
|
90
|
+
// The storage/broadcast key for a row: the pk field's value, or for
|
|
91
|
+
// composite-keyed tables the pk fields' values joined with '|'. Event
|
|
92
|
+
// handlers on composite tables pass this to broadcastTableChange.
|
|
93
|
+
rowKey(tableName: string, row: Row): Pk {
|
|
94
|
+
const config = this.tableConfig.get(tableName);
|
|
95
|
+
if (!config) throw new Error(`Unknown table: ${tableName}`);
|
|
96
|
+
return keyFor(config.pkFields, row);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Fallback matching for tables where the caller doesn't have the full key:
|
|
100
|
+
// try the pk field(s) first, then any single field that uniquely identifies
|
|
101
|
+
// one row, then the full combination of provided fields.
|
|
77
102
|
findRow(tableName: string, criteria: Row): Row | undefined {
|
|
78
103
|
const table = this.tables.get(tableName);
|
|
79
104
|
if (!table) return undefined;
|
|
80
|
-
const {
|
|
105
|
+
const { pkFields } = this.tableConfig.get(tableName) ?? { pkFields: [] };
|
|
81
106
|
|
|
82
|
-
if (
|
|
83
|
-
|
|
107
|
+
if (pkFields.length > 0 && pkFields.every((field) => criteria[field] !== undefined)) {
|
|
108
|
+
const byKey = table.get(keyFor(pkFields, criteria));
|
|
109
|
+
if (byKey) return byKey;
|
|
84
110
|
}
|
|
85
111
|
|
|
86
112
|
const rows = Array.from(table.values());
|
|
@@ -100,15 +126,20 @@ export class Store {
|
|
|
100
126
|
if (!table || !config) throw new Error(`Unknown table: ${tableName}`);
|
|
101
127
|
|
|
102
128
|
const row = { ...record };
|
|
103
|
-
if (
|
|
104
|
-
|
|
129
|
+
if (
|
|
130
|
+
config.pkFields.length === 1 &&
|
|
131
|
+
row[config.pkFields[0]] === undefined &&
|
|
132
|
+
config.sequencePrefix
|
|
133
|
+
) {
|
|
134
|
+
row[config.pkFields[0]] = this.nextSequenceValue(config.sequencePrefix, config.sequenceWidth);
|
|
105
135
|
}
|
|
106
|
-
|
|
136
|
+
const missing = config.pkFields.filter((field) => row[field] === undefined);
|
|
137
|
+
if (missing.length > 0) {
|
|
107
138
|
throw new Error(
|
|
108
|
-
`Primary key '${
|
|
139
|
+
`Primary key field(s) '${missing.join("', '")}' are required for inserting into table '${tableName}'`,
|
|
109
140
|
);
|
|
110
141
|
}
|
|
111
|
-
table.set(
|
|
142
|
+
table.set(keyFor(config.pkFields, row), row);
|
|
112
143
|
return row;
|
|
113
144
|
}
|
|
114
145
|
|
|
@@ -126,7 +157,9 @@ export class Store {
|
|
|
126
157
|
return table.delete(pk);
|
|
127
158
|
}
|
|
128
159
|
|
|
129
|
-
// Materializes a view: base table left-joined to related tables
|
|
160
|
+
// Materializes a view: base table left-joined to related tables (optionally
|
|
161
|
+
// narrowed by per-join `where` predicates), minus anti-joined rows, plus
|
|
162
|
+
// derived fields.
|
|
130
163
|
getViewRows(viewName: string): Row[] {
|
|
131
164
|
const view = this.views.get(viewName);
|
|
132
165
|
if (!view) throw new Error(`Unknown view: ${viewName}`);
|
|
@@ -136,13 +169,34 @@ export class Store {
|
|
|
136
169
|
private materializeView(view: ViewDef, getRows: (tableName: string) => Row[]): Row[] {
|
|
137
170
|
let rows = getRows(view.base).map((row) => ({ ...row }));
|
|
138
171
|
|
|
172
|
+
for (const antiJoin of view.antiJoins ?? []) {
|
|
173
|
+
const joinRows = getRows(antiJoin.table);
|
|
174
|
+
rows = rows.filter(
|
|
175
|
+
(row) =>
|
|
176
|
+
!joinRows.some(
|
|
177
|
+
(joinRow) =>
|
|
178
|
+
joinRow[antiJoin.on[1]] === row[antiJoin.on[0]] &&
|
|
179
|
+
(antiJoin.where?.(joinRow, row) ?? true),
|
|
180
|
+
),
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
139
184
|
for (const join of view.joins ?? []) {
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
185
|
+
const joinRows = getRows(join.table);
|
|
186
|
+
// A `where` predicate sees the base row, so an index keyed on the `on`
|
|
187
|
+
// field alone can't answer it — scan per base row instead.
|
|
188
|
+
const joinIndex = join.where ? undefined : new Map<unknown, Row>();
|
|
189
|
+
if (joinIndex) {
|
|
190
|
+
for (const row of joinRows) {
|
|
191
|
+
joinIndex.set(row[join.on[1]], row);
|
|
192
|
+
}
|
|
143
193
|
}
|
|
144
194
|
rows = rows.map((row) => {
|
|
145
|
-
const match = joinIndex
|
|
195
|
+
const match = joinIndex
|
|
196
|
+
? joinIndex.get(row[join.on[0]])
|
|
197
|
+
: joinRows.find(
|
|
198
|
+
(joinRow) => joinRow[join.on[1]] === row[join.on[0]] && join.where!(joinRow, row),
|
|
199
|
+
);
|
|
146
200
|
const merged = { ...row };
|
|
147
201
|
for (const [alias, sourceField] of Object.entries(join.select ?? {})) {
|
|
148
202
|
merged[alias] = match?.[sourceField];
|
|
@@ -184,12 +238,31 @@ export class Store {
|
|
|
184
238
|
return this.seedRows.get(resourceName) ?? [];
|
|
185
239
|
}
|
|
186
240
|
|
|
187
|
-
// Row-identity
|
|
188
|
-
|
|
189
|
-
// client-side, which keys inserts/amends/deletes off this field).
|
|
190
|
-
getPkField(resourceName: string): string | undefined {
|
|
241
|
+
// Row-identity fields for a table or view; empty when unknown.
|
|
242
|
+
getPkFields(resourceName: string): string[] {
|
|
191
243
|
const view = this.views.get(resourceName);
|
|
192
|
-
if (view)
|
|
193
|
-
|
|
244
|
+
if (view) {
|
|
245
|
+
if (view.pkField) return normalizePkFields(view.pkField);
|
|
246
|
+
return this.tableConfig.get(view.base)?.pkFields ?? [];
|
|
247
|
+
}
|
|
248
|
+
return this.tableConfig.get(resourceName)?.pkFields ?? [];
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// The DETAILS.ROW_REF value stamped on QUERY_UPDATE rows (see
|
|
252
|
+
// protocol/rowUpdate.ts): the pk field's value, or the composite key. The
|
|
253
|
+
// client's dataServerResultFilter keys inserts/amends/deletes off this.
|
|
254
|
+
getRowRef(resourceName: string, row: Row): unknown {
|
|
255
|
+
const pkFields = this.getPkFields(resourceName);
|
|
256
|
+
if (pkFields.length === 0) return undefined;
|
|
257
|
+
return keyFor(pkFields, row);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Rebuilds a DELETE stub row carrying the pk field(s) from a stored key, so
|
|
261
|
+
// subscribers can be told which row to drop after it's already gone.
|
|
262
|
+
rowStubFromKey(resourceName: string, key: Pk): Row {
|
|
263
|
+
const pkFields = this.getPkFields(resourceName);
|
|
264
|
+
if (pkFields.length <= 1) return pkFields.length ? { [pkFields[0]]: key } : {};
|
|
265
|
+
const parts = String(key).split(COMPOSITE_KEY_SEPARATOR);
|
|
266
|
+
return Object.fromEntries(pkFields.map((field, i) => [field, parts[i]]));
|
|
194
267
|
}
|
|
195
268
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Store } from '../db/store.ts';
|
|
2
2
|
import type { Connection } from '../protocol/connection.ts';
|
|
3
3
|
import { NackError } from '../protocol/errors.ts';
|
|
4
|
-
import { ERROR_CODE } from '../protocol/messageTypes.ts';
|
|
4
|
+
import { ERROR_CODE, MESSAGE_TYPE } from '../protocol/messageTypes.ts';
|
|
5
5
|
import type {
|
|
6
6
|
BroadcastFn,
|
|
7
7
|
BroadcastTableChangeFn,
|
|
@@ -26,11 +26,19 @@ export function handleCommitEvent(
|
|
|
26
26
|
ctx: CommitEventCtx,
|
|
27
27
|
): void {
|
|
28
28
|
const eventName = message.MESSAGE_TYPE;
|
|
29
|
-
|
|
29
|
+
// defaultEventHandler catches anything unregistered — lets projects with
|
|
30
|
+
// dozens of commit events adopt incrementally (e.g. `() => ({})` to ack
|
|
31
|
+
// everything unhandled) instead of enumerating ack-only handlers.
|
|
32
|
+
const handler = config.eventHandlers?.[eventName] ?? config.defaultEventHandler;
|
|
30
33
|
|
|
34
|
+
// Replies use the GENERIC EVENT_ACK/EVENT_NACK — correlation is purely via
|
|
35
|
+
// SOURCE_REF. See the note on MESSAGE_TYPE in protocol/messageTypes.ts:
|
|
36
|
+
// real consumers (foundation-comms' kv.service, entity-management) match
|
|
37
|
+
// these names exactly, so a name-suffixed <EVENT>_ACK reads as failure and
|
|
38
|
+
// a <EVENT>_NACK passes as silent success.
|
|
31
39
|
if (!handler) {
|
|
32
40
|
connection.reply(message, {
|
|
33
|
-
MESSAGE_TYPE:
|
|
41
|
+
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK,
|
|
34
42
|
ERROR: [
|
|
35
43
|
{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `No event handler registered for ${eventName}` },
|
|
36
44
|
],
|
|
@@ -41,7 +49,7 @@ export function handleCommitEvent(
|
|
|
41
49
|
try {
|
|
42
50
|
const result = handler(message.DETAILS ?? {}, { connection, store, message, ...ctx }) ?? {};
|
|
43
51
|
connection.reply(message, {
|
|
44
|
-
MESSAGE_TYPE:
|
|
52
|
+
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_ACK,
|
|
45
53
|
GENERATED: result.generated ?? [],
|
|
46
54
|
});
|
|
47
55
|
} catch (error) {
|
|
@@ -49,6 +57,6 @@ export function handleCommitEvent(
|
|
|
49
57
|
error instanceof NackError
|
|
50
58
|
? error.errors
|
|
51
59
|
: [{ CODE: ERROR_CODE.VALIDATION_ERROR, TEXT: (error as Error).message }];
|
|
52
|
-
connection.reply(message, { MESSAGE_TYPE:
|
|
60
|
+
connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK, ERROR: errors });
|
|
53
61
|
}
|
|
54
62
|
}
|
|
@@ -4,6 +4,7 @@ import type { Connection } from '../protocol/connection.ts';
|
|
|
4
4
|
import { MESSAGE_TYPE, ERROR_CODE } from '../protocol/messageTypes.ts';
|
|
5
5
|
import { stampRows } from '../protocol/rowUpdate.ts';
|
|
6
6
|
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
7
|
+
import { applyResourceAuth, requestingUser } from './resourceAuth.ts';
|
|
7
8
|
|
|
8
9
|
// DATA_LOGON opens a persistent subscription keyed by SOURCE_REF: reply with an
|
|
9
10
|
// initial snapshot, then keep the SOURCE_REF registered so later inserts/amends/
|
|
@@ -28,19 +29,25 @@ export function handleDataLogon(
|
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
const criteria = details.CRITERIA_MATCH;
|
|
31
|
-
const
|
|
32
|
-
|
|
32
|
+
const user = requestingUser(connection);
|
|
33
|
+
// Order matters: the query's own filter (the where-clause equivalent) and
|
|
34
|
+
// the user's row permissioning narrow the set BEFORE the client's
|
|
35
|
+
// CRITERIA_MATCH; hidden fields are stripped last, off the final rows.
|
|
36
|
+
let rows = store.getResourceRows(query.source);
|
|
37
|
+
if (query.filter) rows = rows.filter(query.filter);
|
|
38
|
+
rows = filterByCriteria(rows, criteria);
|
|
39
|
+
rows = applyResourceAuth(rows, query.auth, user);
|
|
33
40
|
|
|
34
41
|
connection.subscribe(message.SOURCE_REF!, {
|
|
35
42
|
resourceName,
|
|
36
|
-
|
|
43
|
+
getRowRef: (row) => store.getRowRef(query.source, row),
|
|
37
44
|
predicate: compileCriteria(criteria),
|
|
38
45
|
sequenceId: 1,
|
|
39
46
|
});
|
|
40
47
|
|
|
41
48
|
connection.reply(message, {
|
|
42
49
|
MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
|
|
43
|
-
ROW: stampRows(rows,
|
|
50
|
+
ROW: stampRows(rows, (row) => store.getRowRef(query.source, row), 'INSERT'),
|
|
44
51
|
ROWS_COUNT: rows.length,
|
|
45
52
|
SEQUENCE_ID: 1,
|
|
46
53
|
MORE_ROWS: false,
|
|
@@ -1,10 +1,23 @@
|
|
|
1
1
|
import type { Connection } from '../protocol/connection.ts';
|
|
2
2
|
import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
|
|
3
|
-
import type { GenesisMessage } from '../types.ts';
|
|
3
|
+
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
4
4
|
|
|
5
|
-
export function handleHeartbeat(
|
|
5
|
+
export function handleHeartbeat(
|
|
6
|
+
message: GenesisMessage,
|
|
7
|
+
connection: Connection,
|
|
8
|
+
config: MockServerConfig,
|
|
9
|
+
): void {
|
|
10
|
+
// With the auth gate off (the default), this server accepts every data
|
|
11
|
+
// message — so the pong must report IS_AUTHENTICATED: true even though the
|
|
12
|
+
// WS connection itself never "logged in". HTTP-login clients (httpAutoLogin
|
|
13
|
+
// included) send no SESSION_AUTH_TOKEN on WS messages, so
|
|
14
|
+
// connection.authenticated stays false forever on their connections; report
|
|
15
|
+
// that raw flag and the client treats the session as dead and tears it
|
|
16
|
+
// down, defeating httpAutoLogin entirely. Only when a project opts into
|
|
17
|
+
// auth.requireAuth does the flag reflect real connection auth state.
|
|
18
|
+
const requireAuth = config.auth?.requireAuth ?? false;
|
|
6
19
|
connection.reply(message, {
|
|
7
20
|
MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
|
|
8
|
-
IS_AUTHENTICATED: connection.authenticated,
|
|
21
|
+
IS_AUTHENTICATED: connection.authenticated || !requireAuth,
|
|
9
22
|
});
|
|
10
23
|
}
|
package/src/handlers/http.ts
CHANGED
|
@@ -88,6 +88,33 @@ export function createHttpRequestListener(
|
|
|
88
88
|
const pathname = (req.url ?? '').split('?')[0];
|
|
89
89
|
|
|
90
90
|
try {
|
|
91
|
+
// Project-defined routes run first (see HttpRouteDef) — endpoints the
|
|
92
|
+
// protocol doesn't cover (e.g. GET pbi/configs), or overrides of the
|
|
93
|
+
// built-ins below.
|
|
94
|
+
const route = (config.httpRoutes ?? []).find(
|
|
95
|
+
(candidate) =>
|
|
96
|
+
(!candidate.method || candidate.method.toUpperCase() === req.method) &&
|
|
97
|
+
(typeof candidate.path === 'string'
|
|
98
|
+
? pathname.endsWith(candidate.path)
|
|
99
|
+
: candidate.path.test(pathname)),
|
|
100
|
+
);
|
|
101
|
+
if (route) {
|
|
102
|
+
await route.handler(req, res);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// foundation-auth's login screen fetches this whenever SSO is toggled
|
|
107
|
+
// on, and treats both a failed fetch and an empty IDPS list as fatal
|
|
108
|
+
// (red error, credentials form hidden). Serve the configured providers,
|
|
109
|
+
// or one non-functional placeholder so the screen still renders.
|
|
110
|
+
if (req.method === 'GET' && pathname.endsWith('sso/list')) {
|
|
111
|
+
const idps = config.auth?.ssoIdentityProviders ?? [
|
|
112
|
+
{ ID: 'mock-sso', DESCRIPTION: 'Mock SSO (placeholder, not functional)', TYPE: 'saml' },
|
|
113
|
+
];
|
|
114
|
+
sendJson(res, HTTP_STATUS.OK, { IDPS: idps });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
|
|
91
118
|
// Cookie-based silent login on app load — auto-authenticates as the
|
|
92
119
|
// configured user when config.auth.httpAutoLogin is set, so the login
|
|
93
120
|
// screen never appears (matches how a real session cookie would behave
|
|
@@ -82,11 +82,11 @@ export function handleJsonSchemaRequest(
|
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
const pkOnly = override?.pkOnly ?? DELETE_EVENT_RE.test(eventName!);
|
|
85
|
-
const
|
|
85
|
+
const pkFields = store.getPkFields(table);
|
|
86
86
|
let fields = deriveFields(store.getMetadataRows(table), override?.fieldTypes);
|
|
87
|
-
if (pkOnly) fields = fields.filter((field) => field.NAME
|
|
87
|
+
if (pkOnly) fields = fields.filter((field) => pkFields.includes(field.NAME));
|
|
88
88
|
|
|
89
|
-
const schema = buildSchema(fields, pkOnly
|
|
89
|
+
const schema = buildSchema(fields, pkOnly ? pkFields : []);
|
|
90
90
|
|
|
91
91
|
connection.reply(message, {
|
|
92
92
|
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
package/src/handlers/meta.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { deriveFields } from '../db/metadata.ts';
|
|
|
2
2
|
import type { Store } from '../db/store.ts';
|
|
3
3
|
import type { Connection } from '../protocol/connection.ts';
|
|
4
4
|
import { ERROR_CODE } from '../protocol/messageTypes.ts';
|
|
5
|
-
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
5
|
+
import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
|
|
6
|
+
import { hiddenFields, requestingUser } from './resourceAuth.ts';
|
|
6
7
|
|
|
7
8
|
// createMetaRequestMessage (foundation-comms/src/connect/message.ts) puts the
|
|
8
9
|
// resource name in DETAILS.FEATURE — not DATASOURCE_NAME/RESOURCE_NAME despite
|
|
@@ -37,8 +38,15 @@ export function handleMetaRequest(
|
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
const resolved = (query ?? requestReply)!;
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
// Resolver-only request-replies have no backing table/view — their field
|
|
42
|
+
// metadata comes from the def's own metadataRows sample (plus fieldTypes).
|
|
43
|
+
const rows: Row[] = resolved.source
|
|
44
|
+
? store.getMetadataRows(resolved.source)
|
|
45
|
+
: (requestReply?.metadataRows ?? []);
|
|
46
|
+
// Hidden fields disappear from the metadata too — a column the user can't
|
|
47
|
+
// see must not be offered to the grid at all.
|
|
48
|
+
const hidden = hiddenFields(resolved.auth, requestingUser(connection));
|
|
49
|
+
const fields = deriveFields(rows, resolved.fieldTypes).filter((field) => !hidden.has(field.NAME));
|
|
42
50
|
|
|
43
51
|
connection.reply(message, {
|
|
44
52
|
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
|
@@ -4,6 +4,7 @@ import type { Connection } from '../protocol/connection.ts';
|
|
|
4
4
|
import { NackError } from '../protocol/errors.ts';
|
|
5
5
|
import { ERROR_CODE } from '../protocol/messageTypes.ts';
|
|
6
6
|
import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
|
|
7
|
+
import { applyResourceAuth, requestingUser } from './resourceAuth.ts';
|
|
7
8
|
|
|
8
9
|
// Keyed lookups: foundation-comms' createRequestMessage spreads RequestParams
|
|
9
10
|
// onto the message, so REQUEST is a *top-level* field ({FIELD: value} pairs
|
|
@@ -27,7 +28,7 @@ export function handleRequestReply(
|
|
|
27
28
|
const resourceName = message.MESSAGE_TYPE.replace(/^REQ_/, '');
|
|
28
29
|
const requestReply = config.requestReplies?.[resourceName];
|
|
29
30
|
|
|
30
|
-
if (!requestReply) {
|
|
31
|
+
if (!requestReply || (!requestReply.resolver && !requestReply.source)) {
|
|
31
32
|
connection.reply(message, {
|
|
32
33
|
MESSAGE_TYPE: `REP_${resourceName}`,
|
|
33
34
|
ERROR: [
|
|
@@ -40,15 +41,28 @@ export function handleRequestReply(
|
|
|
40
41
|
return;
|
|
41
42
|
}
|
|
42
43
|
|
|
44
|
+
const user = requestingUser(connection);
|
|
45
|
+
const request: Row =
|
|
46
|
+
(typeof message.REQUEST === 'object' && message.REQUEST) || message.DETAILS?.REQUEST || {};
|
|
47
|
+
|
|
43
48
|
try {
|
|
44
|
-
let rows
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
49
|
+
let rows: Row[];
|
|
50
|
+
if (requestReply.resolver) {
|
|
51
|
+
// Computed reply (date calcs, holiday roll, composite lookups...): the
|
|
52
|
+
// resolver owns REQUEST interpretation entirely — no generic REQUEST/
|
|
53
|
+
// CRITERIA filtering is applied on top, since a computed reply's rows
|
|
54
|
+
// needn't echo the request's fields at all.
|
|
55
|
+
rows = requestReply.resolver({ request, message, user, store });
|
|
56
|
+
} else {
|
|
57
|
+
rows = store.getResourceRows(requestReply.source!);
|
|
58
|
+
if (Object.keys(request).length > 0) {
|
|
59
|
+
rows = rows.filter((row) => matchesRequestFields(row, request));
|
|
60
|
+
}
|
|
61
|
+
const criteria = message.DETAILS?.CRITERIA_MATCH ?? message.CRITERIA_MATCH;
|
|
62
|
+
if (criteria) rows = filterByCriteria(rows, criteria);
|
|
63
|
+
if (requestReply.filter) rows = rows.filter(requestReply.filter);
|
|
48
64
|
}
|
|
49
|
-
|
|
50
|
-
if (criteria) rows = filterByCriteria(rows, criteria);
|
|
51
|
-
if (requestReply.filter) rows = rows.filter(requestReply.filter);
|
|
65
|
+
rows = applyResourceAuth(rows, requestReply.auth, user);
|
|
52
66
|
|
|
53
67
|
connection.reply(message, {
|
|
54
68
|
MESSAGE_TYPE: `REP_${resourceName}`,
|