@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.
- package/README.md +212 -37
- 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 +4 -1
- 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/router.ts +1 -1
- package/src/protocol/rowUpdate.ts +5 -4
- package/src/server.ts +73 -8
- package/src/types.ts +124 -3
- 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 -308
- package/test/store.test.ts +0 -181
- package/tsconfig.json +0 -18
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { deriveFields } from "../db/metadata.js";
|
|
2
|
+
import { ERROR_CODE } from "../protocol/messageTypes.js";
|
|
3
|
+
// JSON_SCHEMA_REQUEST shares its request envelope with META_REQUEST (same
|
|
4
|
+
// DETAILS.FEATURE resource-name field) but its reply is a completely
|
|
5
|
+
// different shape: Connect.getJSONSchema doesn't read response.DETAILS at
|
|
6
|
+
// all — the response *is* the SchemaResponse ({ INBOUND, OUTBOUND }, each a
|
|
7
|
+
// draft-07 JSON Schema). @genesislcap/foundation-entity-management's
|
|
8
|
+
// <entity-management> calls this for every create/update form (fields come
|
|
9
|
+
// from INBOUND.properties.DETAILS.properties) and for delete confirmation
|
|
10
|
+
// (it reads Object.keys(...properties) to know which fields to copy from the
|
|
11
|
+
// selected row into the commit DETAILS). Route this to handleMetaRequest by
|
|
12
|
+
// mistake and forms silently render with zero fields, and delete can never
|
|
13
|
+
// build a payload — no error, just a dead button.
|
|
14
|
+
function jsonSchemaType(fieldType) {
|
|
15
|
+
switch (fieldType) {
|
|
16
|
+
case 'LONG':
|
|
17
|
+
return 'integer';
|
|
18
|
+
case 'DOUBLE':
|
|
19
|
+
return 'number';
|
|
20
|
+
case 'BOOLEAN':
|
|
21
|
+
return 'boolean';
|
|
22
|
+
default:
|
|
23
|
+
return 'string';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function buildSchema(fields, required) {
|
|
27
|
+
const properties = {};
|
|
28
|
+
for (const field of fields) {
|
|
29
|
+
properties[field.NAME] = { type: jsonSchemaType(field.TYPE) };
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
type: 'object',
|
|
33
|
+
properties: {
|
|
34
|
+
DETAILS: { type: 'object', properties, required },
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const DELETE_EVENT_RE = /_DELETE(_|$)/;
|
|
39
|
+
// Zero-config default: EVENT_<TABLE>_<VERB...> maps to <TABLE> if it's a
|
|
40
|
+
// registered table name (longest match wins, so e.g. a hypothetical
|
|
41
|
+
// COUNTERPARTY_AUTH table can't shadow COUNTERPARTY). Covers every event
|
|
42
|
+
// naming pattern in this codebase (INSERT, MODIFY, DELETE, plus suffixed
|
|
43
|
+
// variants like INSERT_WITH_APPROVAL, DEMO_INSERT, MODIFY_PRICE, INSERT_FAIL)
|
|
44
|
+
// without hand-maintaining a table per event. Override via
|
|
45
|
+
// config.eventSchemas for names that don't follow this convention.
|
|
46
|
+
// Exported for unit tests only.
|
|
47
|
+
export function inferEventTable(eventName, tableNames) {
|
|
48
|
+
if (!eventName?.startsWith('EVENT_'))
|
|
49
|
+
return undefined;
|
|
50
|
+
const rest = eventName.slice('EVENT_'.length);
|
|
51
|
+
const candidates = tableNames.filter((name) => rest === name || rest.startsWith(`${name}_`));
|
|
52
|
+
candidates.sort((a, b) => b.length - a.length);
|
|
53
|
+
return candidates[0];
|
|
54
|
+
}
|
|
55
|
+
export function handleJsonSchemaRequest(message, connection, config, store) {
|
|
56
|
+
const eventName = message.DETAILS?.FEATURE;
|
|
57
|
+
const override = eventName ? config.eventSchemas?.[eventName] : undefined;
|
|
58
|
+
const table = override?.table ?? inferEventTable(eventName, Object.keys(config.tables ?? {}));
|
|
59
|
+
if (!table) {
|
|
60
|
+
connection.reply(message, {
|
|
61
|
+
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
|
62
|
+
ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown resource: ${eventName}` }],
|
|
63
|
+
});
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const pkOnly = override?.pkOnly ?? DELETE_EVENT_RE.test(eventName);
|
|
67
|
+
const pkFields = store.getPkFields(table);
|
|
68
|
+
let fields = deriveFields(store.getMetadataRows(table), override?.fieldTypes);
|
|
69
|
+
if (pkOnly)
|
|
70
|
+
fields = fields.filter((field) => pkFields.includes(field.NAME));
|
|
71
|
+
const schema = buildSchema(fields, pkOnly ? pkFields : []);
|
|
72
|
+
connection.reply(message, {
|
|
73
|
+
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
|
74
|
+
INBOUND: schema,
|
|
75
|
+
OUTBOUND: schema,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Store } from '../db/store.ts';
|
|
2
|
+
import type { Connection } from '../protocol/connection.ts';
|
|
3
|
+
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
4
|
+
export declare function handleMetaRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { deriveFields } from "../db/metadata.js";
|
|
2
|
+
import { ERROR_CODE } from "../protocol/messageTypes.js";
|
|
3
|
+
import { hiddenFields, requestingUser } from "./resourceAuth.js";
|
|
4
|
+
// createMetaRequestMessage (foundation-comms/src/connect/message.ts) puts the
|
|
5
|
+
// resource name in DETAILS.FEATURE — not DATASOURCE_NAME/RESOURCE_NAME despite
|
|
6
|
+
// what every other message type in this protocol would suggest.
|
|
7
|
+
function resolveResourceName(message) {
|
|
8
|
+
return (message.DETAILS?.FEATURE ?? message.DETAILS?.DATASOURCE_NAME ?? message.DETAILS?.RESOURCE_NAME);
|
|
9
|
+
}
|
|
10
|
+
// Connect.getMetadata reads metaResponse.DETAILS (not the top-level message)
|
|
11
|
+
// and extractFieldDefinitions (metadata.utils.ts) branches on DETAILS.TYPE:
|
|
12
|
+
// DATASERVER resources need DETAILS.FIELD, REQUEST_SERVER ones need
|
|
13
|
+
// DETAILS.REPLY_FIELD. Get either wrong and every grid silently reports
|
|
14
|
+
// "Metadata Fetch failed" / "Unsupported resource type: undefined".
|
|
15
|
+
export function handleMetaRequest(message, connection, config, store) {
|
|
16
|
+
const resourceName = resolveResourceName(message);
|
|
17
|
+
const query = config.queries?.[resourceName];
|
|
18
|
+
const requestReply = config.requestReplies?.[resourceName];
|
|
19
|
+
if (!query && !requestReply) {
|
|
20
|
+
connection.reply(message, {
|
|
21
|
+
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
|
22
|
+
ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown resource: ${resourceName}` }],
|
|
23
|
+
});
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const resolved = (query ?? requestReply);
|
|
27
|
+
// Resolver-only request-replies have no backing table/view — their field
|
|
28
|
+
// metadata comes from the def's own metadataRows sample (plus fieldTypes).
|
|
29
|
+
const rows = resolved.source
|
|
30
|
+
? store.getMetadataRows(resolved.source)
|
|
31
|
+
: (requestReply?.metadataRows ?? []);
|
|
32
|
+
// Hidden fields disappear from the metadata too — a column the user can't
|
|
33
|
+
// see must not be offered to the grid at all.
|
|
34
|
+
const hidden = hiddenFields(resolved.auth, requestingUser(connection));
|
|
35
|
+
const fields = deriveFields(rows, resolved.fieldTypes).filter((field) => !hidden.has(field.NAME));
|
|
36
|
+
connection.reply(message, {
|
|
37
|
+
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
|
38
|
+
DETAILS: query
|
|
39
|
+
? { NAME: resourceName, TYPE: 'DATASERVER', FIELD: fields, KEY: [] }
|
|
40
|
+
: { NAME: resourceName, TYPE: 'REQUEST_SERVER', REPLY_FIELD: fields },
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Store } from '../db/store.ts';
|
|
2
|
+
import type { Connection } from '../protocol/connection.ts';
|
|
3
|
+
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
4
|
+
export declare function handleRequestReply(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { filterByCriteria } from "../db/criteria.js";
|
|
2
|
+
import { NackError } from "../protocol/errors.js";
|
|
3
|
+
import { ERROR_CODE } from "../protocol/messageTypes.js";
|
|
4
|
+
import { applyResourceAuth, requestingUser } from "./resourceAuth.js";
|
|
5
|
+
// Keyed lookups: foundation-comms' createRequestMessage spreads RequestParams
|
|
6
|
+
// onto the message, so REQUEST is a *top-level* field ({FIELD: value} pairs
|
|
7
|
+
// naming the request server's index fields). A real request server only
|
|
8
|
+
// returns rows matching them; '*' (Genesis's wildcard), null/undefined, and
|
|
9
|
+
// '' mean "any". Arrays match any listed value.
|
|
10
|
+
function matchesRequestFields(row, request) {
|
|
11
|
+
return Object.entries(request).every(([field, value]) => {
|
|
12
|
+
if (value === undefined || value === null || value === '*' || value === '')
|
|
13
|
+
return true;
|
|
14
|
+
if (Array.isArray(value))
|
|
15
|
+
return value.length === 0 || value.includes(row[field]);
|
|
16
|
+
return row[field] === value;
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export function handleRequestReply(message, connection, config, store) {
|
|
20
|
+
const resourceName = message.MESSAGE_TYPE.replace(/^REQ_/, '');
|
|
21
|
+
const requestReply = config.requestReplies?.[resourceName];
|
|
22
|
+
if (!requestReply || (!requestReply.resolver && !requestReply.source)) {
|
|
23
|
+
connection.reply(message, {
|
|
24
|
+
MESSAGE_TYPE: `REP_${resourceName}`,
|
|
25
|
+
ERROR: [
|
|
26
|
+
{
|
|
27
|
+
CODE: ERROR_CODE.UNKNOWN_RESOURCE,
|
|
28
|
+
TEXT: `Unknown request-reply resource: ${resourceName}`,
|
|
29
|
+
},
|
|
30
|
+
],
|
|
31
|
+
});
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const user = requestingUser(connection);
|
|
35
|
+
const request = (typeof message.REQUEST === 'object' && message.REQUEST) || message.DETAILS?.REQUEST || {};
|
|
36
|
+
try {
|
|
37
|
+
let rows;
|
|
38
|
+
if (requestReply.resolver) {
|
|
39
|
+
// Computed reply (date calcs, holiday roll, composite lookups...): the
|
|
40
|
+
// resolver owns REQUEST interpretation entirely — no generic REQUEST/
|
|
41
|
+
// CRITERIA filtering is applied on top, since a computed reply's rows
|
|
42
|
+
// needn't echo the request's fields at all.
|
|
43
|
+
rows = requestReply.resolver({ request, message, user, store });
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
rows = store.getResourceRows(requestReply.source);
|
|
47
|
+
if (Object.keys(request).length > 0) {
|
|
48
|
+
rows = rows.filter((row) => matchesRequestFields(row, request));
|
|
49
|
+
}
|
|
50
|
+
const criteria = message.DETAILS?.CRITERIA_MATCH ?? message.CRITERIA_MATCH;
|
|
51
|
+
if (criteria)
|
|
52
|
+
rows = filterByCriteria(rows, criteria);
|
|
53
|
+
if (requestReply.filter)
|
|
54
|
+
rows = rows.filter(requestReply.filter);
|
|
55
|
+
}
|
|
56
|
+
rows = applyResourceAuth(rows, requestReply.auth, user);
|
|
57
|
+
connection.reply(message, {
|
|
58
|
+
MESSAGE_TYPE: `REP_${resourceName}`,
|
|
59
|
+
REPLY: rows,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
const errors = error instanceof NackError
|
|
64
|
+
? error.errors
|
|
65
|
+
: [{ CODE: ERROR_CODE.VALIDATION_ERROR, TEXT: error.message }];
|
|
66
|
+
connection.reply(message, { MESSAGE_TYPE: `REP_${resourceName}`, ERROR: errors });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Connection } from '../protocol/connection.ts';
|
|
2
|
+
import type { ResourceAuthDef, RequestingUser, Row } from '../types.ts';
|
|
3
|
+
export declare function requestingUser(connection: Connection): RequestingUser;
|
|
4
|
+
export declare function hiddenFields(auth: ResourceAuthDef | undefined, user: RequestingUser): Set<string>;
|
|
5
|
+
export declare function applyResourceAuth(rows: Row[], auth: ResourceAuthDef | undefined, user: RequestingUser): Row[];
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The identity a resource-level auth hook (rowFilter/hideFields) sees for the
|
|
2
|
+
// requesting connection. userName is undefined for unauthenticated
|
|
3
|
+
// connections — possible when requireAuth is off, or pre-login.
|
|
4
|
+
export function requestingUser(connection) {
|
|
5
|
+
return {
|
|
6
|
+
userName: connection.userName,
|
|
7
|
+
profile: connection.profile,
|
|
8
|
+
permission: connection.permission,
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export function hiddenFields(auth, user) {
|
|
12
|
+
const fields = typeof auth?.hideFields === 'function' ? auth.hideFields(user) : auth?.hideFields;
|
|
13
|
+
return new Set(fields ?? []);
|
|
14
|
+
}
|
|
15
|
+
// Applies a resource's permissioning to a reply/snapshot row set: drops rows
|
|
16
|
+
// the user's rowFilter rejects, then strips hidden fields from what's left.
|
|
17
|
+
// Mirrors dataserver auth maps + hideFields on the real server.
|
|
18
|
+
export function applyResourceAuth(rows, auth, user) {
|
|
19
|
+
if (!auth)
|
|
20
|
+
return rows;
|
|
21
|
+
let result = auth.rowFilter ? rows.filter((row) => auth.rowFilter(row, user)) : rows;
|
|
22
|
+
const hidden = hiddenFields(auth, user);
|
|
23
|
+
if (hidden.size > 0) {
|
|
24
|
+
result = result.map((row) => Object.fromEntries(Object.entries(row).filter(([field]) => !hidden.has(field))));
|
|
25
|
+
}
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
|
|
2
|
+
// GenesisResources (foundation-comms/src/resources/genesis/genesis.ts) gates
|
|
3
|
+
// every datasource/request-reply/commit call on this list first — an empty
|
|
4
|
+
// or missing RESOURCES_REQUEST_ACK.RESOURCES makes every resource silently
|
|
5
|
+
// "not exist" client-side, before META_REQUEST or DATA_LOGON is ever tried.
|
|
6
|
+
// Auto-derive it from config.queries/requestReplies/eventHandlers (same
|
|
7
|
+
// philosophy as db/metadata.ts's field inference) so projects don't have to
|
|
8
|
+
// hand-maintain a redundant list; set config.resources explicitly to override.
|
|
9
|
+
function deriveResources(config) {
|
|
10
|
+
const resources = [];
|
|
11
|
+
for (const name of Object.keys(config.queries ?? {})) {
|
|
12
|
+
resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'DATASERVER' });
|
|
13
|
+
}
|
|
14
|
+
for (const name of Object.keys(config.requestReplies ?? {})) {
|
|
15
|
+
resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'REQUEST_SERVER' });
|
|
16
|
+
}
|
|
17
|
+
const eventNames = new Set([
|
|
18
|
+
...Object.keys(config.eventHandlers ?? {}),
|
|
19
|
+
// Events served only by eventSchemas + defaultEventHandler still need to
|
|
20
|
+
// be discoverable, or the client-side resource gate blocks them before
|
|
21
|
+
// the commit is ever sent.
|
|
22
|
+
...Object.keys(config.eventSchemas ?? {}),
|
|
23
|
+
]);
|
|
24
|
+
for (const name of eventNames) {
|
|
25
|
+
resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'EVENT_HANDLER' });
|
|
26
|
+
}
|
|
27
|
+
return resources;
|
|
28
|
+
}
|
|
29
|
+
export function handleResourcesRequest(message, connection, config) {
|
|
30
|
+
connection.reply(message, {
|
|
31
|
+
MESSAGE_TYPE: MESSAGE_TYPE.RESOURCES_REQUEST_ACK,
|
|
32
|
+
RESOURCES: config.resources ?? deriveResources(config),
|
|
33
|
+
});
|
|
34
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { createMockServer, type MockServer } from './server.ts';
|
|
2
|
+
export { launchStack, type LaunchStackOptions, type LaunchedStack } from './launch.ts';
|
|
3
|
+
export { Store } from './db/store.ts';
|
|
4
|
+
export { NackError, type NackErrorInput, type NackErrorEntry } from './protocol/errors.ts';
|
|
5
|
+
export { compileCriteria, filterByCriteria, type Predicate } from './db/criteria.ts';
|
|
6
|
+
export type { AntiJoinDef, AuthConfig, AuthUser, BroadcastFn, BroadcastTableChangeFn, EventHandler, EventHandlerCtx, EventHandlerResult, EventSchemaOverride, FieldMetadata, GenesisMessage, HttpRouteDef, JoinDef, MockServerConfig, OnMessageCtx, OnMessageHook, QueryDef, RequestingUser, RequestReplyDef, RequestReplyResolverCtx, ResourceAuthDef, ResourceItem, Row, SocketLike, SsoIdentityProvider, TableDef, ViewDef, } from './types.ts';
|
package/dist/index.js
ADDED
package/dist/launch.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type ChildProcess } from 'node:child_process';
|
|
2
|
+
import { type MockServer } from './server.ts';
|
|
3
|
+
import type { MockServerConfig } from './types.ts';
|
|
4
|
+
export interface LaunchStackOptions {
|
|
5
|
+
config: MockServerConfig;
|
|
6
|
+
clientCommand: string | string[];
|
|
7
|
+
port?: number;
|
|
8
|
+
cwd?: string;
|
|
9
|
+
clientEnv?: (port: number) => Record<string, string>;
|
|
10
|
+
tieLifetimes?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface LaunchedStack {
|
|
13
|
+
server: MockServer;
|
|
14
|
+
port: number;
|
|
15
|
+
client: ChildProcess;
|
|
16
|
+
clientExited: Promise<number | null>;
|
|
17
|
+
stop(): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
export declare function launchStack(options: LaunchStackOptions): Promise<LaunchedStack>;
|
package/dist/launch.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// One-command dev stack: boot a mock server (ephemeral port by default) and
|
|
2
|
+
// spawn the client dev command pointed at it, with tied lifetimes — so
|
|
3
|
+
// several server+client pairs can run on one machine without hand-assigning
|
|
4
|
+
// ports or orphaning processes.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { createMockServer } from "./server.js";
|
|
7
|
+
export async function launchStack(options) {
|
|
8
|
+
const { config, clientCommand, port = 0, cwd, clientEnv, tieLifetimes = true } = options;
|
|
9
|
+
const server = createMockServer(config);
|
|
10
|
+
const boundPort = await server.listen(port);
|
|
11
|
+
const env = {
|
|
12
|
+
...process.env,
|
|
13
|
+
API_HOST: `ws://localhost:${boundPort}`,
|
|
14
|
+
...clientEnv?.(boundPort),
|
|
15
|
+
};
|
|
16
|
+
const client = Array.isArray(clientCommand)
|
|
17
|
+
? spawn(clientCommand[0], clientCommand.slice(1), { cwd, env, stdio: 'inherit' })
|
|
18
|
+
: spawn(clientCommand, { cwd, env, stdio: 'inherit', shell: true });
|
|
19
|
+
let stopping = false;
|
|
20
|
+
async function stop() {
|
|
21
|
+
if (stopping)
|
|
22
|
+
return;
|
|
23
|
+
stopping = true;
|
|
24
|
+
if (client.exitCode === null && !client.killed)
|
|
25
|
+
client.kill('SIGINT');
|
|
26
|
+
await server.stop();
|
|
27
|
+
}
|
|
28
|
+
const clientExited = new Promise((resolve) => {
|
|
29
|
+
client.once('exit', (code) => {
|
|
30
|
+
const finish = () => resolve(code);
|
|
31
|
+
if (tieLifetimes) {
|
|
32
|
+
stopping = true;
|
|
33
|
+
server.stop().then(finish, finish);
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
finish();
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
client.once('error', (error) => {
|
|
40
|
+
console.error('[mock-server] Failed to spawn client command:', error);
|
|
41
|
+
const finish = () => resolve(null);
|
|
42
|
+
if (tieLifetimes) {
|
|
43
|
+
stopping = true;
|
|
44
|
+
server.stop().then(finish, finish);
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
finish();
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
if (tieLifetimes) {
|
|
52
|
+
const onSignal = () => {
|
|
53
|
+
void stop();
|
|
54
|
+
};
|
|
55
|
+
process.once('SIGINT', onSignal);
|
|
56
|
+
process.once('SIGTERM', onSignal);
|
|
57
|
+
}
|
|
58
|
+
return { server, port: boundPort, client, clientExited, stop };
|
|
59
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Predicate } from '../db/criteria.ts';
|
|
2
|
+
import type { GenesisMessage, Row, SocketLike } from '../types.ts';
|
|
3
|
+
export interface Subscription {
|
|
4
|
+
resourceName: string;
|
|
5
|
+
getRowRef: (row: Row) => unknown;
|
|
6
|
+
predicate: Predicate;
|
|
7
|
+
sequenceId: number;
|
|
8
|
+
}
|
|
9
|
+
export declare class Connection {
|
|
10
|
+
readonly ws: SocketLike;
|
|
11
|
+
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
12
|
+
authenticated: boolean;
|
|
13
|
+
sessionAuthToken: string | undefined;
|
|
14
|
+
sessionId: string | undefined;
|
|
15
|
+
userName: string | undefined;
|
|
16
|
+
profile: string[];
|
|
17
|
+
permission: string[];
|
|
18
|
+
readonly subscriptions: Map<string, Subscription>;
|
|
19
|
+
constructor(ws: SocketLike);
|
|
20
|
+
send(payload: Row): void;
|
|
21
|
+
reply(requestMessage: GenesisMessage, payload: Row): void;
|
|
22
|
+
subscribe(sourceRef: string, subscription: Subscription): void;
|
|
23
|
+
unsubscribe(sourceRef: string): void;
|
|
24
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
const WS_OPEN = 1;
|
|
3
|
+
// Wraps one WebSocket client connection: auth state and its live DATA_LOGON
|
|
4
|
+
// subscriptions (keyed by SOURCE_REF, since that's the client's sole correlation
|
|
5
|
+
// key — see README pitfall #1).
|
|
6
|
+
export class Connection {
|
|
7
|
+
ws;
|
|
8
|
+
id = crypto.randomUUID();
|
|
9
|
+
authenticated = false;
|
|
10
|
+
sessionAuthToken;
|
|
11
|
+
sessionId;
|
|
12
|
+
userName;
|
|
13
|
+
profile = [];
|
|
14
|
+
permission = [];
|
|
15
|
+
subscriptions = new Map();
|
|
16
|
+
constructor(ws) {
|
|
17
|
+
this.ws = ws;
|
|
18
|
+
}
|
|
19
|
+
// Every response must echo the request's SOURCE_REF verbatim, or the client's
|
|
20
|
+
// pending promise for that call never resolves (silent hang, no error).
|
|
21
|
+
send(payload) {
|
|
22
|
+
if (this.ws.readyState !== WS_OPEN)
|
|
23
|
+
return;
|
|
24
|
+
this.ws.send(JSON.stringify(payload));
|
|
25
|
+
}
|
|
26
|
+
reply(requestMessage, payload) {
|
|
27
|
+
this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF });
|
|
28
|
+
}
|
|
29
|
+
subscribe(sourceRef, subscription) {
|
|
30
|
+
this.subscriptions.set(sourceRef, subscription);
|
|
31
|
+
}
|
|
32
|
+
unsubscribe(sourceRef) {
|
|
33
|
+
this.subscriptions.delete(sourceRef);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface NackErrorInput {
|
|
2
|
+
CODE?: string;
|
|
3
|
+
code?: string;
|
|
4
|
+
TEXT?: string;
|
|
5
|
+
text?: string;
|
|
6
|
+
FIELD?: string;
|
|
7
|
+
field?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface NackErrorEntry {
|
|
10
|
+
CODE: string;
|
|
11
|
+
TEXT: string;
|
|
12
|
+
FIELD?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare class NackError extends Error {
|
|
15
|
+
readonly errors: NackErrorEntry[];
|
|
16
|
+
constructor(errors: NackErrorInput | NackErrorInput[]);
|
|
17
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Throw this from an event handler / request-reply resolver to produce a
|
|
2
|
+
// protocol-correct *_NACK with ERROR as an array of {CODE, TEXT, FIELD?} —
|
|
3
|
+
// never {error, details} (lowercase, non-array), which crashes real clients
|
|
4
|
+
// calling .forEach on the wrong shape.
|
|
5
|
+
export class NackError extends Error {
|
|
6
|
+
errors;
|
|
7
|
+
constructor(errors) {
|
|
8
|
+
const list = Array.isArray(errors) ? errors : [errors];
|
|
9
|
+
super(list.map((e) => e.TEXT ?? e.text ?? 'Unknown error').join(', '));
|
|
10
|
+
this.errors = list.map((e) => ({
|
|
11
|
+
CODE: e.CODE ?? e.code ?? 'VALIDATION_ERROR',
|
|
12
|
+
TEXT: e.TEXT ?? e.text ?? 'Unknown error',
|
|
13
|
+
...(e.FIELD || e.field ? { FIELD: e.FIELD ?? e.field } : {}),
|
|
14
|
+
}));
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export declare const MESSAGE_TYPE: {
|
|
2
|
+
readonly EVENT_ACK: "EVENT_ACK";
|
|
3
|
+
readonly EVENT_NACK: "EVENT_NACK";
|
|
4
|
+
readonly EVENT_LOGIN_AUTH: "EVENT_LOGIN_AUTH";
|
|
5
|
+
readonly EVENT_LOGIN_AUTH_ACK: "EVENT_LOGIN_AUTH_ACK";
|
|
6
|
+
readonly EVENT_LOGIN_AUTH_NACK: "EVENT_LOGIN_AUTH_NACK";
|
|
7
|
+
readonly EVENT_LOGOUT: "EVENT_LOGOUT";
|
|
8
|
+
readonly LOGOUT_ACK: "LOGOUT_ACK";
|
|
9
|
+
readonly EVENT_LOGOUT_NACK: "EVENT_LOGOUT_NACK";
|
|
10
|
+
readonly HEARTBEAT_PING: "HEARTBEAT_PING";
|
|
11
|
+
readonly HEARTBEAT_PONG: "HEARTBEAT_PONG";
|
|
12
|
+
readonly DATA_LOGON: "DATA_LOGON";
|
|
13
|
+
readonly DATA_LOGOFF: "DATA_LOGOFF";
|
|
14
|
+
readonly QUERY_UPDATE: "QUERY_UPDATE";
|
|
15
|
+
readonly META_REQUEST: "META_REQUEST";
|
|
16
|
+
readonly JSON_SCHEMA_REQUEST: "JSON_SCHEMA_REQUEST";
|
|
17
|
+
readonly RESOURCES_REQUEST: "RESOURCES_REQUEST";
|
|
18
|
+
readonly RESOURCES_REQUEST_ACK: "RESOURCES_REQUEST_ACK";
|
|
19
|
+
readonly RESOURCES_REQUEST_NACK: "RESOURCES_REQUEST_NACK";
|
|
20
|
+
};
|
|
21
|
+
export declare const ERROR_CODE: {
|
|
22
|
+
readonly INCORRECT_CREDENTIALS: "INCORRECT_CREDENTIALS";
|
|
23
|
+
readonly VALIDATION_ERROR: "VALIDATION_ERROR";
|
|
24
|
+
readonly UNKNOWN_RESOURCE: "UNKNOWN_RESOURCE";
|
|
25
|
+
readonly NOT_LOGGED_ON: "NOT_LOGGED_ON";
|
|
26
|
+
};
|
|
27
|
+
export declare function isCommitEvent(messageType: unknown): messageType is string;
|
|
28
|
+
export declare function isRequestReply(messageType: unknown): messageType is string;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export const MESSAGE_TYPE = {
|
|
2
|
+
// Commit events are acked with the GENERIC pair below — the reply is
|
|
3
|
+
// correlated by SOURCE_REF, not by name. Real Genesis never replies
|
|
4
|
+
// <EVENT_NAME>_ACK/_NACK: foundation-comms' kv.service checks
|
|
5
|
+
// MESSAGE_TYPE === 'EVENT_ACK' exactly, and entity-management (and the
|
|
6
|
+
// showcase's customEvents.ts) check MESSAGE_TYPE === 'EVENT_NACK' exactly.
|
|
7
|
+
// Reply with the name-suffixed form and every successful commit renders as
|
|
8
|
+
// a failure toast while every NACK passes silently.
|
|
9
|
+
EVENT_ACK: 'EVENT_ACK',
|
|
10
|
+
EVENT_NACK: 'EVENT_NACK',
|
|
11
|
+
EVENT_LOGIN_AUTH: 'EVENT_LOGIN_AUTH',
|
|
12
|
+
EVENT_LOGIN_AUTH_ACK: 'EVENT_LOGIN_AUTH_ACK',
|
|
13
|
+
EVENT_LOGIN_AUTH_NACK: 'EVENT_LOGIN_AUTH_NACK',
|
|
14
|
+
EVENT_LOGOUT: 'EVENT_LOGOUT',
|
|
15
|
+
LOGOUT_ACK: 'LOGOUT_ACK',
|
|
16
|
+
EVENT_LOGOUT_NACK: 'EVENT_LOGOUT_NACK',
|
|
17
|
+
HEARTBEAT_PING: 'HEARTBEAT_PING',
|
|
18
|
+
HEARTBEAT_PONG: 'HEARTBEAT_PONG',
|
|
19
|
+
DATA_LOGON: 'DATA_LOGON',
|
|
20
|
+
DATA_LOGOFF: 'DATA_LOGOFF',
|
|
21
|
+
QUERY_UPDATE: 'QUERY_UPDATE',
|
|
22
|
+
META_REQUEST: 'META_REQUEST',
|
|
23
|
+
JSON_SCHEMA_REQUEST: 'JSON_SCHEMA_REQUEST',
|
|
24
|
+
RESOURCES_REQUEST: 'RESOURCES_REQUEST',
|
|
25
|
+
RESOURCES_REQUEST_ACK: 'RESOURCES_REQUEST_ACK',
|
|
26
|
+
RESOURCES_REQUEST_NACK: 'RESOURCES_REQUEST_NACK',
|
|
27
|
+
};
|
|
28
|
+
export const ERROR_CODE = {
|
|
29
|
+
INCORRECT_CREDENTIALS: 'INCORRECT_CREDENTIALS',
|
|
30
|
+
VALIDATION_ERROR: 'VALIDATION_ERROR',
|
|
31
|
+
UNKNOWN_RESOURCE: 'UNKNOWN_RESOURCE',
|
|
32
|
+
NOT_LOGGED_ON: 'NOT_LOGGED_ON',
|
|
33
|
+
};
|
|
34
|
+
export function isCommitEvent(messageType) {
|
|
35
|
+
return (typeof messageType === 'string' &&
|
|
36
|
+
messageType.startsWith('EVENT_') &&
|
|
37
|
+
messageType !== MESSAGE_TYPE.EVENT_LOGIN_AUTH &&
|
|
38
|
+
messageType !== MESSAGE_TYPE.EVENT_LOGOUT);
|
|
39
|
+
}
|
|
40
|
+
export function isRequestReply(messageType) {
|
|
41
|
+
return typeof messageType === 'string' && messageType.startsWith('REQ_');
|
|
42
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Store } from '../db/store.ts';
|
|
2
|
+
import { type TokenRegistry } from '../handlers/auth.ts';
|
|
3
|
+
import { type CommitEventCtx } from '../handlers/commitEvent.ts';
|
|
4
|
+
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
5
|
+
import type { Connection } from './connection.ts';
|
|
6
|
+
export declare function routeMessage(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store, ctx: CommitEventCtx, tokens?: TokenRegistry): void;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { handleLogin, handleLogout } from "../handlers/auth.js";
|
|
2
|
+
import { handleCommitEvent } from "../handlers/commitEvent.js";
|
|
3
|
+
import { handleDataLogon, handleDataLogoff } from "../handlers/dataLogon.js";
|
|
4
|
+
import { handleHeartbeat } from "../handlers/heartbeat.js";
|
|
5
|
+
import { handleJsonSchemaRequest } from "../handlers/jsonSchema.js";
|
|
6
|
+
import { handleMetaRequest } from "../handlers/meta.js";
|
|
7
|
+
import { handleRequestReply } from "../handlers/requestReply.js";
|
|
8
|
+
import { handleResourcesRequest } from "../handlers/resources.js";
|
|
9
|
+
import { MESSAGE_TYPE, ERROR_CODE, isCommitEvent, isRequestReply } from "./messageTypes.js";
|
|
10
|
+
// Message types a connection may send before authenticating when the OPT-IN
|
|
11
|
+
// auth gate (config.auth.requireAuth = true) is enabled. Everything else
|
|
12
|
+
// (data subscriptions, request-replies, metadata, commit events) then
|
|
13
|
+
// requires the connection to have logged in over WS — or to present a
|
|
14
|
+
// SESSION_AUTH_TOKEN this server issued (over either transport).
|
|
15
|
+
// RESOURCES_REQUEST is allowed pre-auth so resource discovery can't deadlock
|
|
16
|
+
// a client that fetches it before (or while) logging in.
|
|
17
|
+
//
|
|
18
|
+
// The gate is OFF by default because real clients can't be assumed to
|
|
19
|
+
// satisfy it: browser frame captures show that after logging in over
|
|
20
|
+
// foundation-auth's HTTP transport, the client sends NO SESSION_AUTH_TOKEN
|
|
21
|
+
// on any WebSocket message (session storage's authToken is never populated
|
|
22
|
+
// by that flow, so message.ts's stamp serializes to nothing) — a default-on
|
|
23
|
+
// gate would reject every datasource with NOT_LOGGED_ON. Enable it only for
|
|
24
|
+
// clients that log in over WS (or stamp tokens on WS traffic).
|
|
25
|
+
const PRE_AUTH_MESSAGE_TYPES = new Set([
|
|
26
|
+
MESSAGE_TYPE.EVENT_LOGIN_AUTH,
|
|
27
|
+
MESSAGE_TYPE.EVENT_LOGOUT,
|
|
28
|
+
MESSAGE_TYPE.HEARTBEAT_PING,
|
|
29
|
+
MESSAGE_TYPE.DATA_LOGOFF,
|
|
30
|
+
MESSAGE_TYPE.RESOURCES_REQUEST,
|
|
31
|
+
]);
|
|
32
|
+
function ensureAuthenticated(message, connection, tokens) {
|
|
33
|
+
if (connection.authenticated)
|
|
34
|
+
return true;
|
|
35
|
+
const token = message.SESSION_AUTH_TOKEN;
|
|
36
|
+
const username = typeof token === 'string' ? tokens.get(token) : undefined;
|
|
37
|
+
if (username !== undefined) {
|
|
38
|
+
connection.authenticated = true;
|
|
39
|
+
connection.userName = username;
|
|
40
|
+
connection.sessionAuthToken = token;
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
// Error reply for unauthenticated traffic, shaped per message family the same
|
|
46
|
+
// way each handler's own error paths are (REP_* for REQ_*, *_NACK for events,
|
|
47
|
+
// QUERY_UPDATE for DATA_LOGON, echoed MESSAGE_TYPE for META/JSON_SCHEMA).
|
|
48
|
+
function replyNotLoggedOn(message, connection) {
|
|
49
|
+
const type = message.MESSAGE_TYPE;
|
|
50
|
+
const ERROR = [{ CODE: ERROR_CODE.NOT_LOGGED_ON, TEXT: 'Not logged on' }];
|
|
51
|
+
if (isRequestReply(type)) {
|
|
52
|
+
connection.reply(message, { MESSAGE_TYPE: `REP_${type.replace(/^REQ_/, '')}`, ERROR });
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (type === MESSAGE_TYPE.DATA_LOGON) {
|
|
56
|
+
connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE, ERROR });
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (isCommitEvent(type)) {
|
|
60
|
+
// Generic, not `${type}_NACK` — see the note in messageTypes.ts.
|
|
61
|
+
connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK, ERROR });
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
connection.reply(message, { MESSAGE_TYPE: type, ERROR });
|
|
65
|
+
}
|
|
66
|
+
export function routeMessage(message, connection, config, store, ctx, tokens = new Map()) {
|
|
67
|
+
// Adopt token auth on every message (not just gated ones) so e.g. a
|
|
68
|
+
// HEARTBEAT_PONG's IS_AUTHENTICATED reflects an HTTP-issued token straight
|
|
69
|
+
// away; the gate itself only applies to data traffic.
|
|
70
|
+
ensureAuthenticated(message, connection, tokens);
|
|
71
|
+
const requireAuth = config.auth?.requireAuth ?? false;
|
|
72
|
+
if (requireAuth &&
|
|
73
|
+
!PRE_AUTH_MESSAGE_TYPES.has(message.MESSAGE_TYPE) &&
|
|
74
|
+
!connection.authenticated) {
|
|
75
|
+
return replyNotLoggedOn(message, connection);
|
|
76
|
+
}
|
|
77
|
+
switch (message.MESSAGE_TYPE) {
|
|
78
|
+
case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
|
|
79
|
+
return handleLogin(message, connection, config, tokens);
|
|
80
|
+
case MESSAGE_TYPE.EVENT_LOGOUT:
|
|
81
|
+
return handleLogout(message, connection);
|
|
82
|
+
case MESSAGE_TYPE.HEARTBEAT_PING:
|
|
83
|
+
return handleHeartbeat(message, connection, config);
|
|
84
|
+
case MESSAGE_TYPE.DATA_LOGON:
|
|
85
|
+
return handleDataLogon(message, connection, config, store);
|
|
86
|
+
case MESSAGE_TYPE.DATA_LOGOFF:
|
|
87
|
+
return handleDataLogoff(message, connection);
|
|
88
|
+
case MESSAGE_TYPE.META_REQUEST:
|
|
89
|
+
return handleMetaRequest(message, connection, config, store);
|
|
90
|
+
case MESSAGE_TYPE.JSON_SCHEMA_REQUEST:
|
|
91
|
+
return handleJsonSchemaRequest(message, connection, config, store);
|
|
92
|
+
case MESSAGE_TYPE.RESOURCES_REQUEST:
|
|
93
|
+
return handleResourcesRequest(message, connection, config);
|
|
94
|
+
default:
|
|
95
|
+
if (isRequestReply(message.MESSAGE_TYPE))
|
|
96
|
+
return handleRequestReply(message, connection, config, store);
|
|
97
|
+
if (isCommitEvent(message.MESSAGE_TYPE))
|
|
98
|
+
return handleCommitEvent(message, connection, config, store, ctx);
|
|
99
|
+
console.warn(`[mock-server] Unhandled MESSAGE_TYPE: ${message.MESSAGE_TYPE}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Row } from '../types.ts';
|
|
2
|
+
export type RowOperation = 'INSERT' | 'MODIFY' | 'DELETE';
|
|
3
|
+
export declare function stampRow(row: Row, rowRef: unknown, operation: RowOperation): Row;
|
|
4
|
+
export declare function stampRows(rows: Row[], getRowRef: (row: Row) => unknown, operation: RowOperation): Row[];
|