@cosmneo/onion-lasagna 0.2.1 → 0.3.1
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/dist/chunk-36IO4BM7.js +113 -0
- package/dist/chunk-36IO4BM7.js.map +1 -0
- package/dist/chunk-4BVOLXDJ.js +54 -0
- package/dist/chunk-4BVOLXDJ.js.map +1 -0
- package/dist/chunk-CBTICRSM.js +34 -0
- package/dist/chunk-CBTICRSM.js.map +1 -0
- package/dist/chunk-KJ4JGZOE.js +96 -0
- package/dist/chunk-KJ4JGZOE.js.map +1 -0
- package/dist/chunk-RVSBIYY4.js +1 -0
- package/dist/chunk-RVSBIYY4.js.map +1 -0
- package/dist/{chunk-MF2JDREK.js → chunk-UNVB4INM.js} +1 -1
- package/dist/{chunk-MF2JDREK.js.map → chunk-UNVB4INM.js.map} +1 -1
- package/dist/chunk-XWKHOLIP.js +191 -0
- package/dist/chunk-XWKHOLIP.js.map +1 -0
- package/dist/event-router-definition.type-CP9uTlux.d.cts +150 -0
- package/dist/event-router-definition.type-D8CG-kjZ.d.ts +150 -0
- package/dist/events/asyncapi/index.cjs +143 -0
- package/dist/events/asyncapi/index.cjs.map +1 -0
- package/dist/events/asyncapi/index.d.cts +184 -0
- package/dist/events/asyncapi/index.d.ts +184 -0
- package/dist/events/asyncapi/index.js +8 -0
- package/dist/events/asyncapi/index.js.map +1 -0
- package/dist/events/handler/index.cjs +171 -0
- package/dist/events/handler/index.cjs.map +1 -0
- package/dist/events/handler/index.d.cts +153 -0
- package/dist/events/handler/index.d.ts +153 -0
- package/dist/events/handler/index.js +21 -0
- package/dist/events/handler/index.js.map +1 -0
- package/dist/events/index.cjs +497 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +9 -0
- package/dist/events/index.d.ts +9 -0
- package/dist/events/index.js +41 -0
- package/dist/events/index.js.map +1 -0
- package/dist/events/server/index.cjs +291 -0
- package/dist/events/server/index.cjs.map +1 -0
- package/dist/events/server/index.d.cts +281 -0
- package/dist/events/server/index.d.ts +281 -0
- package/dist/events/server/index.js +16 -0
- package/dist/events/server/index.js.map +1 -0
- package/dist/events/shared/index.cjs +85 -0
- package/dist/events/shared/index.cjs.map +1 -0
- package/dist/events/shared/index.d.cts +35 -0
- package/dist/events/shared/index.d.ts +35 -0
- package/dist/events/shared/index.js +13 -0
- package/dist/events/shared/index.js.map +1 -0
- package/dist/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +2 -1
- package/dist/http/index.d.ts +2 -1
- package/dist/http/index.js +4 -4
- package/dist/http/route/index.cjs.map +1 -1
- package/dist/http/route/index.d.cts +4 -0
- package/dist/http/route/index.d.ts +4 -0
- package/dist/http/route/index.js +1 -1
- package/dist/http/server/index.d.cts +4 -261
- package/dist/http/server/index.d.ts +4 -261
- package/dist/types-B6Q1iCgf.d.ts +262 -0
- package/dist/types-afYpL7Ap.d.cts +262 -0
- package/dist/types-cke61juH.d.cts +42 -0
- package/dist/types-cke61juH.d.ts +42 -0
- package/package.json +35 -2
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import {
|
|
2
|
+
mapErrorToEventResult
|
|
3
|
+
} from "./chunk-4BVOLXDJ.js";
|
|
4
|
+
import {
|
|
5
|
+
collectEventHandlers,
|
|
6
|
+
generateHandlerId,
|
|
7
|
+
isEventRouterDefinition
|
|
8
|
+
} from "./chunk-CBTICRSM.js";
|
|
9
|
+
|
|
10
|
+
// src/presentation/events/server/types.ts
|
|
11
|
+
function isSimpleEventHandlerConfig(config) {
|
|
12
|
+
return "handler" in config && typeof config.handler === "function";
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/presentation/events/server/create-event-routes.ts
|
|
16
|
+
function createEventRoutesInternal(router, handlers, options) {
|
|
17
|
+
const config = isEventRouterDefinition(router) ? router.handlers : router;
|
|
18
|
+
const collectedHandlers = collectEventHandlers(config);
|
|
19
|
+
const result = [];
|
|
20
|
+
const resolvedOptions = {
|
|
21
|
+
...options,
|
|
22
|
+
validatePayload: options?.validatePayload ?? true,
|
|
23
|
+
allowPartial: options?.allowPartial ?? false
|
|
24
|
+
};
|
|
25
|
+
for (const { key, handler: handlerDef } of collectedHandlers) {
|
|
26
|
+
const handlerConfig = handlers[key];
|
|
27
|
+
if (!handlerConfig) {
|
|
28
|
+
if (resolvedOptions.allowPartial) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
throw new Error(
|
|
32
|
+
`Missing handler for event "${key}". All event handlers must have a handler configuration.`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
result.push(createEventHandler(key, handlerDef, handlerConfig, resolvedOptions));
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
function createEventHandler(key, handlerDef, config, options) {
|
|
40
|
+
const middleware = config.middleware ?? [];
|
|
41
|
+
const globalMiddleware = options?.middleware ?? [];
|
|
42
|
+
const allMiddleware = [...globalMiddleware, ...middleware];
|
|
43
|
+
const shouldValidatePayload = options.validatePayload ?? true;
|
|
44
|
+
const errorMapper = options.errorMapper ?? mapErrorToEventResult;
|
|
45
|
+
return {
|
|
46
|
+
eventType: handlerDef.eventType,
|
|
47
|
+
metadata: {
|
|
48
|
+
handlerId: generateHandlerId(key),
|
|
49
|
+
summary: handlerDef.docs.summary,
|
|
50
|
+
description: handlerDef.docs.description,
|
|
51
|
+
tags: handlerDef.docs.tags,
|
|
52
|
+
deprecated: handlerDef.docs.deprecated
|
|
53
|
+
},
|
|
54
|
+
handler: async (rawEvent) => {
|
|
55
|
+
try {
|
|
56
|
+
let validatedContext = rawEvent.metadata;
|
|
57
|
+
if (handlerDef.context) {
|
|
58
|
+
const contextResult = validateContextData(handlerDef, rawEvent.metadata);
|
|
59
|
+
if (!contextResult.success) {
|
|
60
|
+
const errors = contextResult.errors ?? [];
|
|
61
|
+
return {
|
|
62
|
+
outcome: "dlq",
|
|
63
|
+
reason: `Context validation failed: ${errors.map((e) => `${e.path.join(".")}: ${e.message}`).join("; ")}`
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
validatedContext = contextResult.data;
|
|
67
|
+
}
|
|
68
|
+
let validatedPayload = rawEvent.payload;
|
|
69
|
+
if (shouldValidatePayload && handlerDef.payload) {
|
|
70
|
+
const payloadResult = validatePayloadData(handlerDef, rawEvent.payload);
|
|
71
|
+
if (!payloadResult.success) {
|
|
72
|
+
const errors = payloadResult.errors ?? [];
|
|
73
|
+
return {
|
|
74
|
+
outcome: "dlq",
|
|
75
|
+
reason: `Payload validation failed: ${errors.map((e) => `${e.path.join(".")}: ${e.message}`).join("; ")}`
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
validatedPayload = payloadResult.data;
|
|
79
|
+
}
|
|
80
|
+
const validatedEvent = {
|
|
81
|
+
payload: validatedPayload,
|
|
82
|
+
raw: rawEvent
|
|
83
|
+
};
|
|
84
|
+
const executePipeline = async () => {
|
|
85
|
+
if (isSimpleEventHandlerConfig(config)) {
|
|
86
|
+
return config.handler(
|
|
87
|
+
validatedEvent,
|
|
88
|
+
validatedContext
|
|
89
|
+
);
|
|
90
|
+
} else {
|
|
91
|
+
const { payloadMapper, useCase, resultMapper } = config;
|
|
92
|
+
const input = payloadMapper(
|
|
93
|
+
validatedEvent,
|
|
94
|
+
validatedContext
|
|
95
|
+
);
|
|
96
|
+
const output = await useCase.execute(input);
|
|
97
|
+
return resultMapper ? resultMapper(output) : { outcome: "ack" };
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
if (allMiddleware.length === 0) {
|
|
101
|
+
return await executePipeline();
|
|
102
|
+
}
|
|
103
|
+
let index = 0;
|
|
104
|
+
const next = async () => {
|
|
105
|
+
if (index >= allMiddleware.length) {
|
|
106
|
+
return executePipeline();
|
|
107
|
+
}
|
|
108
|
+
const mw = allMiddleware[index++];
|
|
109
|
+
return mw(rawEvent, next);
|
|
110
|
+
};
|
|
111
|
+
return await next();
|
|
112
|
+
} catch (error) {
|
|
113
|
+
return errorMapper(error);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function validatePayloadData(handler, payload) {
|
|
119
|
+
const schema = handler.payload;
|
|
120
|
+
if (!schema) return { success: true, data: payload };
|
|
121
|
+
const result = schema.validate(payload);
|
|
122
|
+
if (result.success) {
|
|
123
|
+
return { success: true, data: result.data };
|
|
124
|
+
}
|
|
125
|
+
const errors = result.issues.map((issue) => ({
|
|
126
|
+
...issue,
|
|
127
|
+
path: ["payload", ...issue.path]
|
|
128
|
+
}));
|
|
129
|
+
return { success: false, errors };
|
|
130
|
+
}
|
|
131
|
+
function validateContextData(handler, metadata) {
|
|
132
|
+
const schema = handler.context;
|
|
133
|
+
if (!schema) return { success: true, data: metadata };
|
|
134
|
+
const result = schema.validate(metadata);
|
|
135
|
+
if (result.success) {
|
|
136
|
+
return { success: true, data: result.data };
|
|
137
|
+
}
|
|
138
|
+
const errors = result.issues.map((issue) => ({
|
|
139
|
+
...issue,
|
|
140
|
+
path: ["context", ...issue.path]
|
|
141
|
+
}));
|
|
142
|
+
return { success: false, errors };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// src/presentation/events/server/event-routes-builder.ts
|
|
146
|
+
var EventRoutesBuilderImpl = class _EventRoutesBuilderImpl {
|
|
147
|
+
router;
|
|
148
|
+
handlers;
|
|
149
|
+
constructor(router, handlers) {
|
|
150
|
+
this.router = router;
|
|
151
|
+
this.handlers = handlers ?? /* @__PURE__ */ new Map();
|
|
152
|
+
}
|
|
153
|
+
handle(key, handlerOrConfig) {
|
|
154
|
+
const config = typeof handlerOrConfig === "function" ? { handler: handlerOrConfig } : handlerOrConfig;
|
|
155
|
+
const newHandlers = new Map(this.handlers);
|
|
156
|
+
newHandlers.set(key, config);
|
|
157
|
+
return new _EventRoutesBuilderImpl(
|
|
158
|
+
this.router,
|
|
159
|
+
newHandlers
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
handleWithUseCase(key, config) {
|
|
163
|
+
const newHandlers = new Map(this.handlers);
|
|
164
|
+
newHandlers.set(
|
|
165
|
+
key,
|
|
166
|
+
config
|
|
167
|
+
);
|
|
168
|
+
return new _EventRoutesBuilderImpl(
|
|
169
|
+
this.router,
|
|
170
|
+
newHandlers
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
build(options) {
|
|
174
|
+
return createEventRoutesInternal(this.router, Object.fromEntries(this.handlers), options);
|
|
175
|
+
}
|
|
176
|
+
buildPartial(options) {
|
|
177
|
+
return createEventRoutesInternal(this.router, Object.fromEntries(this.handlers), {
|
|
178
|
+
...options,
|
|
179
|
+
allowPartial: true
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
function eventRoutes(router) {
|
|
184
|
+
return new EventRoutesBuilderImpl(router);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export {
|
|
188
|
+
isSimpleEventHandlerConfig,
|
|
189
|
+
eventRoutes
|
|
190
|
+
};
|
|
191
|
+
//# sourceMappingURL=chunk-XWKHOLIP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/presentation/events/server/types.ts","../src/presentation/events/server/create-event-routes.ts","../src/presentation/events/server/event-routes-builder.ts"],"sourcesContent":["/**\n * @fileoverview Server types for the event handler system.\n *\n * @module events/server/types\n */\n\nimport type { EventHandlerDefinition, EventRouterConfig, EventRouterKeys } from '../handler/types';\nimport type { EventResult } from '../shared/types';\n\n// Re-export UseCasePort from HTTP — same interface, no duplication\nexport type { UseCasePort } from '../../http/server/types';\n\n// ============================================================================\n// Raw Event (from messaging system)\n// ============================================================================\n\n/**\n * Event metadata provided by the messaging system.\n */\nexport interface EventMetadata {\n /** Unique event identifier for idempotency checks. */\n readonly eventId: string;\n\n /** ISO 8601 timestamp of when the event occurred. */\n readonly timestamp: string;\n\n /** Correlation ID for distributed tracing. */\n readonly correlationId?: string;\n\n /** Source system or bounded context that emitted the event. */\n readonly source?: string;\n\n /** Number of delivery attempts (1-based). */\n readonly attemptCount?: number;\n\n /** Additional metadata from the messaging system. */\n readonly [key: string]: unknown;\n}\n\n/**\n * Raw event from the messaging system.\n * This is the input to event handlers before validation.\n */\nexport interface RawEvent {\n /** Event type string for routing. */\n readonly type: string;\n\n /** Event payload (unvalidated). */\n readonly payload: unknown;\n\n /** Event metadata from the messaging system. */\n readonly metadata: EventMetadata;\n}\n\n// ============================================================================\n// Validated Event\n// ============================================================================\n\n/**\n * A validated event with typed payload.\n * This is what handlers receive after validation passes.\n */\nexport interface ValidatedEvent<THandler extends EventHandlerDefinition> {\n /** Validated event payload. */\n readonly payload: THandler['_types']['payload'];\n\n /** Raw event object for advanced use cases. */\n readonly raw: RawEvent;\n}\n\n/**\n * Typed event context based on handler definition.\n * If the handler defines a context schema, this will be the validated type.\n * Otherwise, it falls back to the generic EventMetadata.\n */\nexport type TypedEventContext<THandler extends EventHandlerDefinition> =\n THandler['_types']['context'] extends undefined ? EventMetadata : THandler['_types']['context'];\n\n// ============================================================================\n// Handler Types\n// ============================================================================\n\n/**\n * Handler configuration using the use case pattern.\n *\n * @typeParam THandler - The event handler definition type\n * @typeParam TInput - Use case input type\n * @typeParam TOutput - Use case output type\n */\nexport interface EventHandlerConfig<\n THandler extends EventHandlerDefinition,\n TInput = void,\n TOutput = void,\n> {\n /**\n * Maps the validated event payload to use case input.\n * Both `event` and `ctx` are fully typed based on handler schemas.\n */\n readonly payloadMapper: (\n event: ValidatedEvent<THandler>,\n ctx: TypedEventContext<THandler>,\n ) => TInput;\n\n /** The use case to execute. */\n readonly useCase: { execute(input?: TInput): Promise<TOutput> };\n\n /**\n * Maps the use case output to an EventResult.\n * If omitted, defaults to `{ outcome: 'ack' }`.\n */\n readonly resultMapper?: (output: TOutput) => EventResult;\n\n /** Middleware to run before the handler. */\n readonly middleware?: readonly EventMiddlewareFunction[];\n}\n\n/**\n * Simple handler function that directly returns an EventResult.\n */\nexport type SimpleEventHandlerFn<THandler extends EventHandlerDefinition> = (\n event: ValidatedEvent<THandler>,\n ctx: TypedEventContext<THandler>,\n) => Promise<EventResult> | EventResult;\n\n/**\n * Configuration for a simple handler (no use case).\n */\nexport interface SimpleEventHandlerConfig<THandler extends EventHandlerDefinition> {\n readonly handler: SimpleEventHandlerFn<THandler>;\n readonly middleware?: readonly EventMiddlewareFunction[];\n}\n\n/**\n * Union of all event handler config types.\n * Used internally to store handlers in the builder.\n */\nexport type AnyEventHandlerConfig<\n THandler extends EventHandlerDefinition,\n TInput = unknown,\n TOutput = unknown,\n> = EventHandlerConfig<THandler, TInput, TOutput> | SimpleEventHandlerConfig<THandler>;\n\n/**\n * Type guard to check if config is a simple event handler.\n */\nexport function isSimpleEventHandlerConfig(\n config: AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>,\n): config is SimpleEventHandlerConfig<EventHandlerDefinition> {\n return 'handler' in config && typeof config.handler === 'function';\n}\n\n/**\n * Event middleware function type.\n */\nexport type EventMiddlewareFunction = (\n event: RawEvent,\n next: () => Promise<EventResult>,\n) => Promise<EventResult>;\n\n// ============================================================================\n// Server Configuration\n// ============================================================================\n\n/**\n * Configuration mapping handler keys to handler configs.\n */\n// TInput/TOutput are user-defined per handler - any is required for heterogeneous configs\nexport type EventRoutesConfig<T extends EventRouterConfig> = Record<\n EventRouterKeys<T>,\n EventHandlerConfig<any, any, any>\n>;\n\n/**\n * Options for creating event routes.\n */\nexport interface CreateEventRoutesOptions {\n /** Global middleware to run before all handlers. */\n readonly middleware?: readonly EventMiddlewareFunction[];\n\n /**\n * Whether to validate incoming event payloads against handler schemas.\n * When enabled, invalid payloads result in a `dlq` outcome.\n * @default true\n */\n readonly validatePayload?: boolean;\n\n /**\n * Custom error mapper to override default error-to-EventResult mapping.\n * If not provided, uses the built-in `mapErrorToEventResult`.\n */\n readonly errorMapper?: (error: unknown) => EventResult;\n\n /**\n * Allow partial handler configuration (not all handlers need to be wired).\n * @default false\n * @internal Used by builder pattern's buildPartial()\n */\n readonly allowPartial?: boolean;\n}\n\n// ============================================================================\n// Unified Event Input (for messaging adapters)\n// ============================================================================\n\n/**\n * Event input compatible with messaging adapters.\n * This is the output of eventRoutes().build().\n */\nexport interface UnifiedEventInput {\n /** Event type string for routing. */\n readonly eventType: string;\n\n /** Handler function. */\n readonly handler: (rawEvent: RawEvent) => Promise<EventResult>;\n\n /** Handler metadata for documentation. */\n readonly metadata: {\n readonly handlerId?: string;\n readonly summary?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly deprecated?: boolean;\n };\n}\n","/**\n * @fileoverview Internal implementation for creating event routes with auto-validation.\n *\n * Generates event handlers from an event router definition.\n * Each handler automatically validates incoming event payloads and context\n * against the handler's schemas.\n *\n * @module events/server/create-event-routes\n * @internal\n */\n\nimport type { SchemaAdapter, ValidationIssue } from '../../http/schema/types';\nimport type {\n EventRouterConfig,\n EventRouterDefinition,\n EventHandlerDefinition,\n} from '../handler/types';\nimport { isEventRouterDefinition, collectEventHandlers } from '../handler/types';\nimport { generateHandlerId } from '../handler/utils';\nimport { mapErrorToEventResult } from '../shared/error-mapping';\nimport type { EventResult } from '../shared/types';\nimport type {\n AnyEventHandlerConfig,\n CreateEventRoutesOptions,\n EventMetadata,\n RawEvent,\n UnifiedEventInput,\n ValidatedEvent,\n} from './types';\nimport { isSimpleEventHandlerConfig } from './types';\n\n/**\n * Internal implementation for creating event routes.\n * Used by the builder pattern (eventRoutes).\n *\n * @internal\n */\nexport function createEventRoutesInternal<T extends EventRouterConfig>(\n router: T | EventRouterDefinition<T>,\n handlers: Record<string, AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>>,\n options?: CreateEventRoutesOptions,\n): UnifiedEventInput[] {\n const config = isEventRouterDefinition(router) ? router.handlers : router;\n const collectedHandlers = collectEventHandlers(config);\n\n const result: UnifiedEventInput[] = [];\n\n const resolvedOptions: CreateEventRoutesOptions = {\n ...options,\n validatePayload: options?.validatePayload ?? true,\n allowPartial: options?.allowPartial ?? false,\n };\n\n for (const { key, handler: handlerDef } of collectedHandlers) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const handlerConfig = handlers[key] as\n | AnyEventHandlerConfig<EventHandlerDefinition, any, any>\n | undefined;\n\n if (!handlerConfig) {\n if (resolvedOptions.allowPartial) {\n continue;\n }\n throw new Error(\n `Missing handler for event \"${key}\". All event handlers must have a handler configuration.`,\n );\n }\n\n result.push(createEventHandler(key, handlerDef, handlerConfig, resolvedOptions));\n }\n\n return result;\n}\n\n/**\n * Creates a single event handler with validation and error mapping.\n */\nfunction createEventHandler(\n key: string,\n handlerDef: EventHandlerDefinition,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: AnyEventHandlerConfig<EventHandlerDefinition, any, any>,\n options: CreateEventRoutesOptions,\n): UnifiedEventInput {\n const middleware = config.middleware ?? [];\n const globalMiddleware = options?.middleware ?? [];\n const allMiddleware = [...globalMiddleware, ...middleware];\n const shouldValidatePayload = options.validatePayload ?? true;\n const errorMapper = options.errorMapper ?? mapErrorToEventResult;\n\n return {\n eventType: handlerDef.eventType,\n metadata: {\n handlerId: generateHandlerId(key),\n summary: handlerDef.docs.summary,\n description: handlerDef.docs.description,\n tags: handlerDef.docs.tags as string[],\n deprecated: handlerDef.docs.deprecated,\n },\n handler: async (rawEvent: RawEvent): Promise<EventResult> => {\n try {\n // Validate context (if schema defined)\n let validatedContext: unknown = rawEvent.metadata;\n if (handlerDef.context) {\n const contextResult = validateContextData(handlerDef, rawEvent.metadata);\n if (!contextResult.success) {\n const errors = contextResult.errors ?? [];\n return {\n outcome: 'dlq',\n reason: `Context validation failed: ${errors.map((e) => `${e.path.join('.')}: ${e.message}`).join('; ')}`,\n };\n }\n validatedContext = contextResult.data;\n }\n\n // Validate payload (if enabled and schema defined)\n let validatedPayload: unknown = rawEvent.payload;\n if (shouldValidatePayload && handlerDef.payload) {\n const payloadResult = validatePayloadData(handlerDef, rawEvent.payload);\n if (!payloadResult.success) {\n const errors = payloadResult.errors ?? [];\n return {\n outcome: 'dlq',\n reason: `Payload validation failed: ${errors.map((e) => `${e.path.join('.')}: ${e.message}`).join('; ')}`,\n };\n }\n validatedPayload = payloadResult.data;\n }\n\n const validatedEvent: ValidatedEventInternal = {\n payload: validatedPayload,\n raw: rawEvent,\n };\n\n // Execute the pipeline\n const executePipeline = async (): Promise<EventResult> => {\n if (isSimpleEventHandlerConfig(config)) {\n return config.handler(\n validatedEvent as unknown as ValidatedEvent<EventHandlerDefinition>,\n validatedContext as EventMetadata,\n );\n } else {\n const { payloadMapper, useCase, resultMapper } = config;\n\n const input = payloadMapper(\n validatedEvent as unknown as ValidatedEvent<EventHandlerDefinition>,\n validatedContext as EventMetadata,\n );\n\n const output = await useCase.execute(input);\n\n return resultMapper ? resultMapper(output) : { outcome: 'ack' };\n }\n };\n\n if (allMiddleware.length === 0) {\n return await executePipeline();\n }\n\n // Build middleware chain\n let index = 0;\n const next = async (): Promise<EventResult> => {\n if (index >= allMiddleware.length) {\n return executePipeline();\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- index bounds checked above\n const mw = allMiddleware[index++]!;\n return mw(rawEvent, next);\n };\n\n return await next();\n } catch (error) {\n return errorMapper(error);\n }\n },\n };\n}\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\ninterface ValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: unknown;\n}\n\n/**\n * Validates event payload against the handler's payload schema.\n */\nfunction validatePayloadData(\n handler: EventHandlerDefinition,\n payload: unknown,\n): ValidationResultInternal {\n const schema = handler.payload as SchemaAdapter | undefined;\n if (!schema) return { success: true, data: payload };\n\n const result = schema.validate(payload);\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['payload', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Validates event metadata against the handler's context schema.\n */\nfunction validateContextData(\n handler: EventHandlerDefinition,\n metadata: EventMetadata,\n): ValidationResultInternal {\n const schema = handler.context as SchemaAdapter | undefined;\n if (!schema) return { success: true, data: metadata };\n\n const result = schema.validate(metadata);\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['context', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Internal validated event type with unknown fields.\n * Used inside createEventHandler where specific types are erased.\n */\ninterface ValidatedEventInternal {\n readonly payload: unknown;\n readonly raw: RawEvent;\n}\n","/**\n * @fileoverview Builder pattern for creating type-safe event routes.\n *\n * The `eventRoutes` function returns a builder that provides 100% type inference\n * for all handler parameters — no manual type annotations required.\n *\n * @module events/server/event-routes-builder\n */\n\nimport type {\n EventRouterConfig,\n EventRouterDefinition,\n GetEventHandler,\n EventRouterKeys,\n EventHandlerDefinition,\n} from '../handler/types';\nimport type { EventResult } from '../shared/types';\nimport type {\n AnyEventHandlerConfig,\n CreateEventRoutesOptions,\n EventHandlerConfig,\n EventMiddlewareFunction,\n SimpleEventHandlerConfig,\n SimpleEventHandlerFn,\n TypedEventContext,\n UnifiedEventInput,\n ValidatedEvent,\n} from './types';\nimport { createEventRoutesInternal } from './create-event-routes';\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/**\n * Error type displayed when attempting to build() with missing handlers.\n * The `___missingHandlers` property shows which handlers are missing.\n */\nexport interface MissingHandlersError<TMissing extends string> {\n /**\n * This error indicates that not all event handlers have been wired.\n * Use buildPartial() to build with only the defined handlers,\n * or add handlers for the missing events.\n */\n (options?: never): never;\n /** Event handlers that are missing. */\n readonly ___missingHandlers: TMissing;\n}\n\n/**\n * Handler configuration for the builder pattern.\n */\nexport interface BuilderEventHandlerConfig<\n THandler extends EventHandlerDefinition,\n TInput,\n TOutput,\n> {\n /**\n * Maps the validated event payload to use case input.\n * Both `event` and `ctx` are fully typed based on handler schemas.\n */\n readonly payloadMapper: (\n event: ValidatedEvent<THandler>,\n ctx: TypedEventContext<THandler>,\n ) => TInput;\n\n /** The use case to execute. */\n readonly useCase: { execute(input?: TInput): Promise<TOutput> };\n\n /**\n * Maps the use case output to an EventResult.\n * If omitted, defaults to `{ outcome: 'ack' }`.\n */\n readonly resultMapper?: (output: TOutput) => EventResult;\n\n /** Middleware to run before the handler. */\n readonly middleware?: readonly EventMiddlewareFunction[];\n}\n\n/**\n * Builder interface for creating type-safe event routes.\n *\n * Each `.handle()` call captures the specific handler type and provides\n * full type inference for payloadMapper and useCase.\n *\n * @typeParam T - The event router configuration type\n * @typeParam THandled - Union of handler keys that have been wired (accumulates)\n *\n * @example\n * ```typescript\n * const routes = eventRoutes(ticketEvents)\n * .handleWithUseCase('created', {\n * payloadMapper: (event, ctx) => ({\n * ticketId: event.payload.ticketId, // Fully typed!\n * correlationId: ctx.correlationId, // Fully typed!\n * }),\n * useCase: sendNotificationUseCase,\n * })\n * .handle('assigned', async (event) => {\n * await notifyAssignee(event.payload);\n * return { outcome: 'ack' as const };\n * })\n * .build();\n * ```\n */\nexport interface EventRoutesBuilder<T extends EventRouterConfig, THandled extends string = never> {\n /**\n * Register a simple handler for an event.\n * The handler receives validated event and context, returns EventResult directly.\n */\n handle<K extends Exclude<EventRouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig:\n | SimpleEventHandlerFn<GetEventHandler<T, K>>\n | SimpleEventHandlerConfig<GetEventHandler<T, K>>,\n ): EventRoutesBuilder<T, THandled | K>;\n\n /**\n * Register a handler using the use case pattern.\n * Follows: payloadMapper → useCase.execute() → resultMapper (or ack)\n */\n handleWithUseCase<K extends Exclude<EventRouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderEventHandlerConfig<GetEventHandler<T, K>, TInput, TOutput>,\n ): EventRoutesBuilder<T, THandled | K>;\n\n /**\n * Build the event routes array for messaging adapter registration.\n *\n * This method is only available when ALL handlers have been wired.\n * If some handlers are missing, use `buildPartial()` instead.\n */\n build: [Exclude<EventRouterKeys<T>, THandled>] extends [never]\n ? (options?: CreateEventRoutesOptions) => UnifiedEventInput[]\n : MissingHandlersError<Exclude<EventRouterKeys<T>, THandled>>;\n\n /**\n * Build event routes for only the defined handlers.\n * No compile-time enforcement of completeness.\n */\n buildPartial(options?: CreateEventRoutesOptions): UnifiedEventInput[];\n}\n\n// ============================================================================\n// Builder Implementation\n// ============================================================================\n\n/**\n * Internal builder implementation.\n *\n * Uses an immutable pattern where each handle() call returns a new\n * builder instance with the updated handlers map.\n */\nclass EventRoutesBuilderImpl<T extends EventRouterConfig, THandled extends string = never> {\n private readonly router: T | EventRouterDefinition<T>;\n private readonly handlers: Map<\n string,\n AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>\n >;\n\n constructor(\n router: T | EventRouterDefinition<T>,\n handlers?: Map<string, AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>>,\n ) {\n this.router = router;\n this.handlers = handlers ?? new Map();\n }\n\n handle<K extends Exclude<EventRouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig:\n | SimpleEventHandlerFn<GetEventHandler<T, K>>\n | SimpleEventHandlerConfig<GetEventHandler<T, K>>,\n ): EventRoutesBuilder<T, THandled | K> {\n const config: SimpleEventHandlerConfig<EventHandlerDefinition> =\n typeof handlerOrConfig === 'function'\n ? { handler: handlerOrConfig as SimpleEventHandlerFn<EventHandlerDefinition> }\n : (handlerOrConfig as SimpleEventHandlerConfig<EventHandlerDefinition>);\n\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config);\n\n return new EventRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as EventRoutesBuilder<T, THandled | K>;\n }\n\n handleWithUseCase<K extends Exclude<EventRouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderEventHandlerConfig<GetEventHandler<T, K>, TInput, TOutput>,\n ): EventRoutesBuilder<T, THandled | K> {\n const newHandlers = new Map(this.handlers);\n newHandlers.set(\n key as string,\n config as EventHandlerConfig<EventHandlerDefinition, unknown, unknown>,\n );\n\n return new EventRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as EventRoutesBuilder<T, THandled | K>;\n }\n\n build(options?: CreateEventRoutesOptions): UnifiedEventInput[] {\n return createEventRoutesInternal(this.router, Object.fromEntries(this.handlers), options);\n }\n\n buildPartial(options?: CreateEventRoutesOptions): UnifiedEventInput[] {\n return createEventRoutesInternal(this.router, Object.fromEntries(this.handlers), {\n ...options,\n allowPartial: true,\n });\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Creates a type-safe event routes builder for an event router.\n *\n * The builder pattern provides 100% type inference for all handler parameters:\n * - `event.payload` is typed from the handler's payload schema\n * - `ctx` is typed from the handler's context schema (or EventMetadata)\n * - `output` in resultMapper is typed from the use case\n *\n * @param router - Event router definition or event router config\n * @returns Builder for registering handlers\n *\n * @example Basic usage\n * ```typescript\n * import { eventRoutes } from '@cosmneo/onion-lasagna/events/server';\n * import { ticketEvents } from './router';\n *\n * const routes = eventRoutes(ticketEvents)\n * .handleWithUseCase('created', {\n * payloadMapper: (event, ctx) => ({\n * ticketId: event.payload.ticketId,\n * correlationId: ctx.correlationId,\n * }),\n * useCase: sendNotificationUseCase,\n * })\n * .handle('assigned', async (event) => {\n * await notifyAssignee(event.payload);\n * return { outcome: 'ack' as const };\n * })\n * .build();\n * ```\n */\nexport function eventRoutes<T extends EventRouterConfig>(\n router: T | EventRouterDefinition<T>,\n): EventRoutesBuilder<T, never> {\n return new EventRoutesBuilderImpl(router) as unknown as EventRoutesBuilder<T, never>;\n}\n"],"mappings":";;;;;;;;;;AAiJO,SAAS,2BACd,QAC4D;AAC5D,SAAO,aAAa,UAAU,OAAO,OAAO,YAAY;AAC1D;;;AChHO,SAAS,0BACd,QACA,UACA,SACqB;AACrB,QAAM,SAAS,wBAAwB,MAAM,IAAI,OAAO,WAAW;AACnE,QAAM,oBAAoB,qBAAqB,MAAM;AAErD,QAAM,SAA8B,CAAC;AAErC,QAAM,kBAA4C;AAAA,IAChD,GAAG;AAAA,IACH,iBAAiB,SAAS,mBAAmB;AAAA,IAC7C,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AAQ;AACzC,gBAAY;AAAA,MACV;AAAA,MACA;AAAA,IACF;AAEA,WAAO,IAAI;AAAA,MACT,KAAK;AAAA,MACL;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,SAAyD;AAC7D,WAAO,0BAA0B,KAAK,QAAQ,OAAO,YAAY,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC1F;AAAA,EAEA,aAAa,SAAyD;AACpE,WAAO,0BAA0B,KAAK,QAAQ,OAAO,YAAY,KAAK,QAAQ,GAAG;AAAA,MAC/E,GAAG;AAAA,MACH,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAqCO,SAAS,YACd,QAC8B;AAC9B,SAAO,IAAI,uBAAuB,MAAM;AAC1C;","names":[]}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { SchemaAdapter } from './http/schema/types.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Core event handler definition types.
|
|
5
|
+
*
|
|
6
|
+
* An event handler definition captures all information needed for:
|
|
7
|
+
* - Type-safe event payload validation
|
|
8
|
+
* - Server-side event routing and dispatching
|
|
9
|
+
* - AsyncAPI / documentation generation
|
|
10
|
+
*
|
|
11
|
+
* @module events/handler/types/event-handler-definition
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Event handler documentation for AsyncAPI / docs generation.
|
|
16
|
+
*/
|
|
17
|
+
interface EventHandlerDocumentation {
|
|
18
|
+
/** Short summary of the handler. */
|
|
19
|
+
readonly summary?: string;
|
|
20
|
+
/** Detailed description. Supports Markdown. */
|
|
21
|
+
readonly description?: string;
|
|
22
|
+
/** Tags for grouping event handlers. */
|
|
23
|
+
readonly tags?: readonly string[];
|
|
24
|
+
/** Whether this handler is deprecated. @default false */
|
|
25
|
+
readonly deprecated?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A fully defined event handler with computed types.
|
|
29
|
+
* This is the output of `defineEventHandler()`.
|
|
30
|
+
*/
|
|
31
|
+
interface EventHandlerDefinition<TEventType extends string = string, TPayload = undefined, TContext = undefined> {
|
|
32
|
+
/** Event type string used for routing (e.g., 'ticket.created'). */
|
|
33
|
+
readonly eventType: TEventType;
|
|
34
|
+
/** Payload validation schema. */
|
|
35
|
+
readonly payload: SchemaAdapter | undefined;
|
|
36
|
+
/** Context validation schema (validates event metadata). */
|
|
37
|
+
readonly context: SchemaAdapter | undefined;
|
|
38
|
+
/** Handler documentation. */
|
|
39
|
+
readonly docs: EventHandlerDocumentation;
|
|
40
|
+
/**
|
|
41
|
+
* Phantom types for TypeScript inference.
|
|
42
|
+
* Never accessed at runtime.
|
|
43
|
+
* @internal
|
|
44
|
+
*/
|
|
45
|
+
readonly _types: {
|
|
46
|
+
readonly eventType: TEventType;
|
|
47
|
+
readonly payload: TPayload;
|
|
48
|
+
readonly context: TContext;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Infers the event type string from a handler definition. */
|
|
52
|
+
type InferEventType<T> = T extends EventHandlerDefinition<infer TEventType, unknown, unknown> ? TEventType : never;
|
|
53
|
+
/** Infers the payload type from a handler definition. */
|
|
54
|
+
type InferEventPayload<T> = T extends EventHandlerDefinition<string, infer TPayload, unknown> ? TPayload : never;
|
|
55
|
+
/** Infers the context type from a handler definition. */
|
|
56
|
+
type InferEventContext<T> = T extends EventHandlerDefinition<string, unknown, infer TContext> ? TContext : never;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @fileoverview Event router definition types for grouping event handlers.
|
|
60
|
+
*
|
|
61
|
+
* Mirrors the HTTP router definition pattern with hierarchical grouping,
|
|
62
|
+
* dotted-key access, and deep merge support.
|
|
63
|
+
*
|
|
64
|
+
* @module events/handler/types/event-router-definition
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A router entry can be an event handler definition, a nested config, or a router definition.
|
|
69
|
+
*/
|
|
70
|
+
type EventRouterEntry = EventHandlerDefinition<string, any, any> | EventRouterConfig | EventRouterDefinition;
|
|
71
|
+
/**
|
|
72
|
+
* Configuration for an event router (group of event handlers).
|
|
73
|
+
*/
|
|
74
|
+
interface EventRouterConfig {
|
|
75
|
+
readonly [key: string]: EventRouterEntry;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Router-level defaults applied to all child event handlers.
|
|
79
|
+
*/
|
|
80
|
+
interface EventRouterDefaults {
|
|
81
|
+
/** Default tags for all handlers. Merged with handler-specific tags. */
|
|
82
|
+
readonly tags?: readonly string[];
|
|
83
|
+
/** Default context schema. Applied to handlers that don't define their own. */
|
|
84
|
+
readonly context?: SchemaAdapter;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A fully defined event router.
|
|
88
|
+
*/
|
|
89
|
+
interface EventRouterDefinition<T extends EventRouterConfig = EventRouterConfig> {
|
|
90
|
+
/** The handlers and nested routers in this router. */
|
|
91
|
+
readonly handlers: T;
|
|
92
|
+
/** Default values applied to all child handlers. */
|
|
93
|
+
readonly defaults?: EventRouterDefaults;
|
|
94
|
+
/**
|
|
95
|
+
* Marker to identify this as an event router.
|
|
96
|
+
* @internal
|
|
97
|
+
*/
|
|
98
|
+
readonly _isEventRouter: true;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Checks if a value is an EventHandlerDefinition.
|
|
102
|
+
*/
|
|
103
|
+
declare function isEventHandlerDefinition(value: unknown): value is EventHandlerDefinition;
|
|
104
|
+
/**
|
|
105
|
+
* Checks if a value is an EventRouterDefinition.
|
|
106
|
+
*/
|
|
107
|
+
declare function isEventRouterDefinition(value: unknown): value is EventRouterDefinition;
|
|
108
|
+
/**
|
|
109
|
+
* Flattens an event router into a map of dotted keys to handler definitions.
|
|
110
|
+
*/
|
|
111
|
+
type FlattenEventRouter<T extends EventRouterConfig, Prefix extends string = ''> = T extends EventRouterConfig ? {
|
|
112
|
+
[K in keyof T]: T[K] extends EventHandlerDefinition<any, any, any> ? {
|
|
113
|
+
[P in `${Prefix}${K & string}`]: T[K];
|
|
114
|
+
} : T[K] extends EventRouterConfig ? FlattenEventRouter<T[K], `${Prefix}${K & string}.`> : never;
|
|
115
|
+
}[keyof T] extends infer U ? U extends Record<string, EventHandlerDefinition<any, any, any>> ? U : never : never : never;
|
|
116
|
+
/**
|
|
117
|
+
* Gets all handler keys from an event router.
|
|
118
|
+
*/
|
|
119
|
+
type EventRouterKeys<T extends EventRouterConfig, Prefix extends string = ''> = T extends EventRouterConfig ? {
|
|
120
|
+
[K in keyof T]: T[K] extends EventHandlerDefinition<any, any, any> ? `${Prefix}${K & string}` : T[K] extends EventRouterConfig ? EventRouterKeys<T[K], `${Prefix}${K & string}.`> : never;
|
|
121
|
+
}[keyof T] : never;
|
|
122
|
+
/**
|
|
123
|
+
* Gets an event handler by its dotted key path.
|
|
124
|
+
*/
|
|
125
|
+
type GetEventHandler<T extends EventRouterConfig, K extends string> = K extends `${infer Head}.${infer Tail}` ? Head extends keyof T ? T[Head] extends EventRouterConfig ? GetEventHandler<T[Head], Tail> : never : never : K extends keyof T ? T[K] extends EventHandlerDefinition<any, any, any> ? T[K] : never : never;
|
|
126
|
+
/**
|
|
127
|
+
* Deep-merges two event router configs at the type level.
|
|
128
|
+
*/
|
|
129
|
+
type DeepMergeTwo<A extends EventRouterConfig, B extends EventRouterConfig> = {
|
|
130
|
+
readonly [K in keyof A | keyof B]: K extends keyof A ? K extends keyof B ? A[K] extends EventRouterConfig ? B[K] extends EventRouterConfig ? DeepMergeTwo<A[K], B[K]> : B[K] : B[K] : A[K] : K extends keyof B ? B[K] : never;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Recursively deep-merges N event router configs left-to-right.
|
|
134
|
+
*/
|
|
135
|
+
type DeepMergeAll<T extends readonly EventRouterConfig[]> = T extends readonly [
|
|
136
|
+
infer Only extends EventRouterConfig
|
|
137
|
+
] ? Only : T extends readonly [
|
|
138
|
+
infer First extends EventRouterConfig,
|
|
139
|
+
infer Second extends EventRouterConfig,
|
|
140
|
+
...infer Rest extends readonly EventRouterConfig[]
|
|
141
|
+
] ? DeepMergeAll<[DeepMergeTwo<First, Second>, ...Rest]> : EventRouterConfig;
|
|
142
|
+
/**
|
|
143
|
+
* Collects all event handlers from a router into a flat array.
|
|
144
|
+
*/
|
|
145
|
+
declare function collectEventHandlers(config: EventRouterConfig, basePath?: string): {
|
|
146
|
+
key: string;
|
|
147
|
+
handler: EventHandlerDefinition;
|
|
148
|
+
}[];
|
|
149
|
+
|
|
150
|
+
export { type DeepMergeTwo as D, type EventHandlerDefinition as E, type FlattenEventRouter as F, type GetEventHandler as G, type InferEventType as I, type EventHandlerDocumentation as a, type EventRouterEntry as b, type EventRouterConfig as c, type EventRouterDefaults as d, type EventRouterDefinition as e, type EventRouterKeys as f, type InferEventPayload as g, type InferEventContext as h, isEventHandlerDefinition as i, isEventRouterDefinition as j, collectEventHandlers as k, type DeepMergeAll as l };
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { SchemaAdapter } from './http/schema/types.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Core event handler definition types.
|
|
5
|
+
*
|
|
6
|
+
* An event handler definition captures all information needed for:
|
|
7
|
+
* - Type-safe event payload validation
|
|
8
|
+
* - Server-side event routing and dispatching
|
|
9
|
+
* - AsyncAPI / documentation generation
|
|
10
|
+
*
|
|
11
|
+
* @module events/handler/types/event-handler-definition
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Event handler documentation for AsyncAPI / docs generation.
|
|
16
|
+
*/
|
|
17
|
+
interface EventHandlerDocumentation {
|
|
18
|
+
/** Short summary of the handler. */
|
|
19
|
+
readonly summary?: string;
|
|
20
|
+
/** Detailed description. Supports Markdown. */
|
|
21
|
+
readonly description?: string;
|
|
22
|
+
/** Tags for grouping event handlers. */
|
|
23
|
+
readonly tags?: readonly string[];
|
|
24
|
+
/** Whether this handler is deprecated. @default false */
|
|
25
|
+
readonly deprecated?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A fully defined event handler with computed types.
|
|
29
|
+
* This is the output of `defineEventHandler()`.
|
|
30
|
+
*/
|
|
31
|
+
interface EventHandlerDefinition<TEventType extends string = string, TPayload = undefined, TContext = undefined> {
|
|
32
|
+
/** Event type string used for routing (e.g., 'ticket.created'). */
|
|
33
|
+
readonly eventType: TEventType;
|
|
34
|
+
/** Payload validation schema. */
|
|
35
|
+
readonly payload: SchemaAdapter | undefined;
|
|
36
|
+
/** Context validation schema (validates event metadata). */
|
|
37
|
+
readonly context: SchemaAdapter | undefined;
|
|
38
|
+
/** Handler documentation. */
|
|
39
|
+
readonly docs: EventHandlerDocumentation;
|
|
40
|
+
/**
|
|
41
|
+
* Phantom types for TypeScript inference.
|
|
42
|
+
* Never accessed at runtime.
|
|
43
|
+
* @internal
|
|
44
|
+
*/
|
|
45
|
+
readonly _types: {
|
|
46
|
+
readonly eventType: TEventType;
|
|
47
|
+
readonly payload: TPayload;
|
|
48
|
+
readonly context: TContext;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Infers the event type string from a handler definition. */
|
|
52
|
+
type InferEventType<T> = T extends EventHandlerDefinition<infer TEventType, unknown, unknown> ? TEventType : never;
|
|
53
|
+
/** Infers the payload type from a handler definition. */
|
|
54
|
+
type InferEventPayload<T> = T extends EventHandlerDefinition<string, infer TPayload, unknown> ? TPayload : never;
|
|
55
|
+
/** Infers the context type from a handler definition. */
|
|
56
|
+
type InferEventContext<T> = T extends EventHandlerDefinition<string, unknown, infer TContext> ? TContext : never;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @fileoverview Event router definition types for grouping event handlers.
|
|
60
|
+
*
|
|
61
|
+
* Mirrors the HTTP router definition pattern with hierarchical grouping,
|
|
62
|
+
* dotted-key access, and deep merge support.
|
|
63
|
+
*
|
|
64
|
+
* @module events/handler/types/event-router-definition
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A router entry can be an event handler definition, a nested config, or a router definition.
|
|
69
|
+
*/
|
|
70
|
+
type EventRouterEntry = EventHandlerDefinition<string, any, any> | EventRouterConfig | EventRouterDefinition;
|
|
71
|
+
/**
|
|
72
|
+
* Configuration for an event router (group of event handlers).
|
|
73
|
+
*/
|
|
74
|
+
interface EventRouterConfig {
|
|
75
|
+
readonly [key: string]: EventRouterEntry;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Router-level defaults applied to all child event handlers.
|
|
79
|
+
*/
|
|
80
|
+
interface EventRouterDefaults {
|
|
81
|
+
/** Default tags for all handlers. Merged with handler-specific tags. */
|
|
82
|
+
readonly tags?: readonly string[];
|
|
83
|
+
/** Default context schema. Applied to handlers that don't define their own. */
|
|
84
|
+
readonly context?: SchemaAdapter;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A fully defined event router.
|
|
88
|
+
*/
|
|
89
|
+
interface EventRouterDefinition<T extends EventRouterConfig = EventRouterConfig> {
|
|
90
|
+
/** The handlers and nested routers in this router. */
|
|
91
|
+
readonly handlers: T;
|
|
92
|
+
/** Default values applied to all child handlers. */
|
|
93
|
+
readonly defaults?: EventRouterDefaults;
|
|
94
|
+
/**
|
|
95
|
+
* Marker to identify this as an event router.
|
|
96
|
+
* @internal
|
|
97
|
+
*/
|
|
98
|
+
readonly _isEventRouter: true;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Checks if a value is an EventHandlerDefinition.
|
|
102
|
+
*/
|
|
103
|
+
declare function isEventHandlerDefinition(value: unknown): value is EventHandlerDefinition;
|
|
104
|
+
/**
|
|
105
|
+
* Checks if a value is an EventRouterDefinition.
|
|
106
|
+
*/
|
|
107
|
+
declare function isEventRouterDefinition(value: unknown): value is EventRouterDefinition;
|
|
108
|
+
/**
|
|
109
|
+
* Flattens an event router into a map of dotted keys to handler definitions.
|
|
110
|
+
*/
|
|
111
|
+
type FlattenEventRouter<T extends EventRouterConfig, Prefix extends string = ''> = T extends EventRouterConfig ? {
|
|
112
|
+
[K in keyof T]: T[K] extends EventHandlerDefinition<any, any, any> ? {
|
|
113
|
+
[P in `${Prefix}${K & string}`]: T[K];
|
|
114
|
+
} : T[K] extends EventRouterConfig ? FlattenEventRouter<T[K], `${Prefix}${K & string}.`> : never;
|
|
115
|
+
}[keyof T] extends infer U ? U extends Record<string, EventHandlerDefinition<any, any, any>> ? U : never : never : never;
|
|
116
|
+
/**
|
|
117
|
+
* Gets all handler keys from an event router.
|
|
118
|
+
*/
|
|
119
|
+
type EventRouterKeys<T extends EventRouterConfig, Prefix extends string = ''> = T extends EventRouterConfig ? {
|
|
120
|
+
[K in keyof T]: T[K] extends EventHandlerDefinition<any, any, any> ? `${Prefix}${K & string}` : T[K] extends EventRouterConfig ? EventRouterKeys<T[K], `${Prefix}${K & string}.`> : never;
|
|
121
|
+
}[keyof T] : never;
|
|
122
|
+
/**
|
|
123
|
+
* Gets an event handler by its dotted key path.
|
|
124
|
+
*/
|
|
125
|
+
type GetEventHandler<T extends EventRouterConfig, K extends string> = K extends `${infer Head}.${infer Tail}` ? Head extends keyof T ? T[Head] extends EventRouterConfig ? GetEventHandler<T[Head], Tail> : never : never : K extends keyof T ? T[K] extends EventHandlerDefinition<any, any, any> ? T[K] : never : never;
|
|
126
|
+
/**
|
|
127
|
+
* Deep-merges two event router configs at the type level.
|
|
128
|
+
*/
|
|
129
|
+
type DeepMergeTwo<A extends EventRouterConfig, B extends EventRouterConfig> = {
|
|
130
|
+
readonly [K in keyof A | keyof B]: K extends keyof A ? K extends keyof B ? A[K] extends EventRouterConfig ? B[K] extends EventRouterConfig ? DeepMergeTwo<A[K], B[K]> : B[K] : B[K] : A[K] : K extends keyof B ? B[K] : never;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Recursively deep-merges N event router configs left-to-right.
|
|
134
|
+
*/
|
|
135
|
+
type DeepMergeAll<T extends readonly EventRouterConfig[]> = T extends readonly [
|
|
136
|
+
infer Only extends EventRouterConfig
|
|
137
|
+
] ? Only : T extends readonly [
|
|
138
|
+
infer First extends EventRouterConfig,
|
|
139
|
+
infer Second extends EventRouterConfig,
|
|
140
|
+
...infer Rest extends readonly EventRouterConfig[]
|
|
141
|
+
] ? DeepMergeAll<[DeepMergeTwo<First, Second>, ...Rest]> : EventRouterConfig;
|
|
142
|
+
/**
|
|
143
|
+
* Collects all event handlers from a router into a flat array.
|
|
144
|
+
*/
|
|
145
|
+
declare function collectEventHandlers(config: EventRouterConfig, basePath?: string): {
|
|
146
|
+
key: string;
|
|
147
|
+
handler: EventHandlerDefinition;
|
|
148
|
+
}[];
|
|
149
|
+
|
|
150
|
+
export { type DeepMergeTwo as D, type EventHandlerDefinition as E, type FlattenEventRouter as F, type GetEventHandler as G, type InferEventType as I, type EventHandlerDocumentation as a, type EventRouterEntry as b, type EventRouterConfig as c, type EventRouterDefaults as d, type EventRouterDefinition as e, type EventRouterKeys as f, type InferEventPayload as g, type InferEventContext as h, isEventHandlerDefinition as i, isEventRouterDefinition as j, collectEventHandlers as k, type DeepMergeAll as l };
|