@crossdelta/cloudevents 0.1.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.
Files changed (58) hide show
  1. package/README.md +125 -0
  2. package/dist/src/adapters/cloudevents/cloudevents.d.ts +14 -0
  3. package/dist/src/adapters/cloudevents/cloudevents.js +58 -0
  4. package/dist/src/adapters/cloudevents/index.d.ts +8 -0
  5. package/dist/src/adapters/cloudevents/index.js +7 -0
  6. package/dist/src/adapters/cloudevents/parsers/binary-mode.d.ts +5 -0
  7. package/dist/src/adapters/cloudevents/parsers/binary-mode.js +32 -0
  8. package/dist/src/adapters/cloudevents/parsers/pubsub.d.ts +5 -0
  9. package/dist/src/adapters/cloudevents/parsers/pubsub.js +54 -0
  10. package/dist/src/adapters/cloudevents/parsers/raw-event.d.ts +5 -0
  11. package/dist/src/adapters/cloudevents/parsers/raw-event.js +17 -0
  12. package/dist/src/adapters/cloudevents/parsers/structured-mode.d.ts +5 -0
  13. package/dist/src/adapters/cloudevents/parsers/structured-mode.js +18 -0
  14. package/dist/src/adapters/cloudevents/types.d.ts +29 -0
  15. package/dist/src/adapters/cloudevents/types.js +1 -0
  16. package/dist/src/domain/discovery.d.ts +24 -0
  17. package/dist/src/domain/discovery.js +137 -0
  18. package/dist/src/domain/handler-factory.d.ts +24 -0
  19. package/dist/src/domain/handler-factory.js +62 -0
  20. package/dist/src/domain/index.d.ts +5 -0
  21. package/dist/src/domain/index.js +3 -0
  22. package/dist/src/domain/types.d.ts +52 -0
  23. package/dist/src/domain/types.js +6 -0
  24. package/dist/src/domain/validation.d.ts +37 -0
  25. package/dist/src/domain/validation.js +53 -0
  26. package/dist/src/index.d.ts +5 -0
  27. package/dist/src/index.js +4 -0
  28. package/dist/src/infrastructure/errors.d.ts +53 -0
  29. package/dist/src/infrastructure/errors.js +54 -0
  30. package/dist/src/infrastructure/index.d.ts +4 -0
  31. package/dist/src/infrastructure/index.js +2 -0
  32. package/dist/src/infrastructure/logging.d.ts +18 -0
  33. package/dist/src/infrastructure/logging.js +27 -0
  34. package/dist/src/middlewares/cloudevents-middleware.d.ts +171 -0
  35. package/dist/src/middlewares/cloudevents-middleware.js +276 -0
  36. package/dist/src/middlewares/index.d.ts +1 -0
  37. package/dist/src/middlewares/index.js +1 -0
  38. package/dist/src/processing/dlq-safe.d.ts +34 -0
  39. package/dist/src/processing/dlq-safe.js +91 -0
  40. package/dist/src/processing/handler-cache.d.ts +36 -0
  41. package/dist/src/processing/handler-cache.js +94 -0
  42. package/dist/src/processing/index.d.ts +3 -0
  43. package/dist/src/processing/index.js +3 -0
  44. package/dist/src/processing/validation.d.ts +41 -0
  45. package/dist/src/processing/validation.js +48 -0
  46. package/dist/src/publishing/index.d.ts +2 -0
  47. package/dist/src/publishing/index.js +2 -0
  48. package/dist/src/publishing/nats.publisher.d.ts +22 -0
  49. package/dist/src/publishing/nats.publisher.js +66 -0
  50. package/dist/src/publishing/pubsub.publisher.d.ts +39 -0
  51. package/dist/src/publishing/pubsub.publisher.js +84 -0
  52. package/dist/src/transports/nats/index.d.ts +2 -0
  53. package/dist/src/transports/nats/index.js +2 -0
  54. package/dist/src/transports/nats/nats-consumer.d.ts +30 -0
  55. package/dist/src/transports/nats/nats-consumer.js +54 -0
  56. package/dist/src/transports/nats/nats-message-processor.d.ts +22 -0
  57. package/dist/src/transports/nats/nats-message-processor.js +95 -0
  58. package/package.json +46 -0
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Domain Types
3
+ *
4
+ * Core business logic types for handlers, events, and domain operations
5
+ */
6
+ import type { ZodTypeAny } from 'zod';
7
+ import type { EventContext } from '../adapters/cloudevents/types';
8
+ /**
9
+ * Event handler interface
10
+ */
11
+ export interface EventHandler<T = unknown> {
12
+ handle(payload: T, context?: unknown): Promise<void> | void;
13
+ }
14
+ /**
15
+ * Constructor type for event handler classes that implement the EventHandler interface
16
+ */
17
+ export type HandlerConstructor<T = unknown> = (new (...args: unknown[]) => EventHandler<T>) & {
18
+ __eventarcMetadata?: {
19
+ schema: ZodTypeAny;
20
+ declaredType?: string;
21
+ match?: (event: EnrichedEvent<T>) => boolean;
22
+ safeParse?: boolean;
23
+ };
24
+ };
25
+ /**
26
+ * Enriched event with both data and context
27
+ */
28
+ export interface EnrichedEvent<T> extends EventContext {
29
+ data: T;
30
+ }
31
+ /**
32
+ * Match function type for custom event matching
33
+ */
34
+ export type MatchFn<T> = (event: EnrichedEvent<T>) => boolean;
35
+ /**
36
+ * Handler metadata attached to handler constructors
37
+ */
38
+ export type HandlerMetadata<S extends ZodTypeAny> = {
39
+ schema: S;
40
+ declaredType?: string;
41
+ match?: MatchFn<unknown>;
42
+ safeParse: boolean;
43
+ };
44
+ /**
45
+ * Options for creating event handlers
46
+ */
47
+ export interface HandleEventOptions<S extends ZodTypeAny> {
48
+ schema: S;
49
+ type?: string;
50
+ match?: MatchFn<unknown>;
51
+ safeParse?: boolean;
52
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Domain Types
3
+ *
4
+ * Core business logic types for handlers, events, and domain operations
5
+ */
6
+ export {};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Domain Validation
3
+ *
4
+ * Core business logic for validating events, handlers, and schemas
5
+ * Contains no infrastructure concerns - pure domain logic
6
+ */
7
+ import type { ZodTypeAny } from 'zod';
8
+ /**
9
+ * Validation error detail for individual field errors
10
+ */
11
+ export interface ValidationErrorDetail {
12
+ code?: string;
13
+ message: string;
14
+ path?: (string | number)[];
15
+ expected?: string;
16
+ received?: string;
17
+ validation?: string;
18
+ }
19
+ /**
20
+ * Handler validation error with handler information
21
+ */
22
+ export interface HandlerValidationError {
23
+ handlerName: string;
24
+ validationErrors: ValidationErrorDetail[];
25
+ }
26
+ /**
27
+ * Validates whether an exported value is a valid event handler
28
+ * Checks for either eventarc metadata or a handle method in the prototype
29
+ */
30
+ export declare function isValidHandler(value: unknown): boolean;
31
+ /**
32
+ * Extracts the event type from a Zod schema by looking for a literal 'type' field
33
+ *
34
+ * @param schema - Zod schema to extract type from
35
+ * @returns Event type string or undefined if not found
36
+ */
37
+ export declare const extractTypeFromSchema: (schema: ZodTypeAny) => string | undefined;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Domain Validation
3
+ *
4
+ * Core business logic for validating events, handlers, and schemas
5
+ * Contains no infrastructure concerns - pure domain logic
6
+ */
7
+ /**
8
+ * Type guards for schema shape analysis
9
+ */
10
+ const hasShape = (schema) => 'shape' in schema &&
11
+ schema.shape !== null &&
12
+ schema.shape !== undefined &&
13
+ typeof schema.shape === 'object';
14
+ const hasTypeField = (shape) => 'type' in shape &&
15
+ shape.type !== null &&
16
+ shape.type !== undefined &&
17
+ typeof shape.type === 'object' &&
18
+ 'value' in shape.type;
19
+ const extractTypeValue = (typeField) => typeof typeField.value === 'string' ? typeField.value : undefined;
20
+ /**
21
+ * Safely extracts type from schema shape
22
+ */
23
+ const safeExtractType = (schema) => {
24
+ if (!hasShape(schema))
25
+ return undefined;
26
+ if (!hasTypeField(schema.shape))
27
+ return undefined;
28
+ return extractTypeValue(schema.shape.type);
29
+ };
30
+ /**
31
+ * Validates whether an exported value is a valid event handler
32
+ * Checks for either eventarc metadata or a handle method in the prototype
33
+ */
34
+ export function isValidHandler(value) {
35
+ if (typeof value !== 'function')
36
+ return false;
37
+ const handler = value;
38
+ return !!(handler.__eventarcMetadata || handler.prototype?.handle);
39
+ }
40
+ /**
41
+ * Extracts the event type from a Zod schema by looking for a literal 'type' field
42
+ *
43
+ * @param schema - Zod schema to extract type from
44
+ * @returns Event type string or undefined if not found
45
+ */
46
+ export const extractTypeFromSchema = (schema) => {
47
+ try {
48
+ return safeExtractType(schema);
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ };
@@ -0,0 +1,5 @@
1
+ export type { EventContext } from './adapters/cloudevents';
2
+ export { parseEventFromContext } from './adapters/cloudevents';
3
+ export { eventSchema, extractTypeFromSchema, handleEvent } from './domain';
4
+ export { clearHandlerCache, cloudEvents } from './middlewares';
5
+ export * from './publishing';
@@ -0,0 +1,4 @@
1
+ export { parseEventFromContext } from './adapters/cloudevents';
2
+ export { eventSchema, extractTypeFromSchema, handleEvent } from './domain';
3
+ export { clearHandlerCache, cloudEvents } from './middlewares';
4
+ export * from './publishing';
@@ -0,0 +1,53 @@
1
+ import type { Context } from 'hono';
2
+ import type { HandlerValidationError } from '../domain';
3
+ export type ErrorResponse = {
4
+ error: {
5
+ type: string;
6
+ message: string;
7
+ timestamp: string;
8
+ details?: unknown;
9
+ };
10
+ };
11
+ export type SuccessResponse = {
12
+ message: string;
13
+ timestamp: string;
14
+ };
15
+ export type ValidationError = {
16
+ type: 'ValidationError';
17
+ eventType: string;
18
+ message: string;
19
+ details: HandlerValidationError[];
20
+ };
21
+ export type NoHandlerFoundError = {
22
+ type: 'NoHandlerFoundError';
23
+ eventType: string;
24
+ message: string;
25
+ };
26
+ export type CloudEventParseError = {
27
+ type: 'CloudEventParseError';
28
+ message: string;
29
+ cause?: Error;
30
+ };
31
+ /**
32
+ * Handles errors with full context logging
33
+ */
34
+ export declare const handleErrorWithContext: (error: Error, context: Context, additionalInfo?: Record<string, unknown>) => {
35
+ message: string;
36
+ stack: string | undefined;
37
+ url: string;
38
+ method: string;
39
+ headers: {
40
+ [k: string]: string;
41
+ };
42
+ };
43
+ /**
44
+ * Converts an error to a standardized response format
45
+ */
46
+ export declare const errorToResponse: (error: Error, type?: string) => ErrorResponse;
47
+ /**
48
+ * Creates a standardized error response
49
+ */
50
+ export declare const createErrorResponse: (type: string, message: string, details?: unknown) => ErrorResponse;
51
+ export declare const createValidationError: (eventType: string, details: HandlerValidationError[]) => ValidationError;
52
+ export declare const createNoHandlerFoundError: (eventType: string) => NoHandlerFoundError;
53
+ export declare const createCloudEventParseError: (message: string, cause?: Error) => CloudEventParseError;
@@ -0,0 +1,54 @@
1
+ // HTTP Response Functions
2
+ /**
3
+ * Handles errors with full context logging
4
+ */
5
+ export const handleErrorWithContext = (error, context, additionalInfo) => {
6
+ const errorInfo = {
7
+ message: error.message,
8
+ stack: error.stack,
9
+ url: context.req.url,
10
+ method: context.req.method,
11
+ headers: Object.fromEntries(context.req.raw.headers.entries()),
12
+ ...additionalInfo,
13
+ };
14
+ console.error('[Error Handler]', JSON.stringify(errorInfo, null, 2));
15
+ return errorInfo;
16
+ };
17
+ /**
18
+ * Converts an error to a standardized response format
19
+ */
20
+ export const errorToResponse = (error, type = 'InternalError') => ({
21
+ error: {
22
+ type,
23
+ message: error.message,
24
+ timestamp: new Date().toISOString(),
25
+ },
26
+ });
27
+ /**
28
+ * Creates a standardized error response
29
+ */
30
+ export const createErrorResponse = (type, message, details) => ({
31
+ error: {
32
+ type,
33
+ message,
34
+ timestamp: new Date().toISOString(),
35
+ details,
36
+ },
37
+ });
38
+ // Application Error Factory Functions
39
+ export const createValidationError = (eventType, details) => ({
40
+ type: 'ValidationError',
41
+ eventType,
42
+ message: `Validation failed for event type: ${eventType}`,
43
+ details,
44
+ });
45
+ export const createNoHandlerFoundError = (eventType) => ({
46
+ type: 'NoHandlerFoundError',
47
+ eventType,
48
+ message: `No handler found for event type: ${eventType}`,
49
+ });
50
+ export const createCloudEventParseError = (message, cause) => ({
51
+ type: 'CloudEventParseError',
52
+ message,
53
+ cause,
54
+ });
@@ -0,0 +1,4 @@
1
+ export type { CloudEventParseError, ErrorResponse, NoHandlerFoundError, SuccessResponse, ValidationError, } from './errors';
2
+ export { createCloudEventParseError, createErrorResponse, createNoHandlerFoundError, createValidationError, errorToResponse, handleErrorWithContext, } from './errors';
3
+ export type { Logger } from './logging';
4
+ export { createLogger, logger } from './logging';
@@ -0,0 +1,2 @@
1
+ export { createCloudEventParseError, createErrorResponse, createNoHandlerFoundError, createValidationError, errorToResponse, handleErrorWithContext, } from './errors';
2
+ export { createLogger, logger } from './logging';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Logger interface for structured logging
3
+ */
4
+ export interface Logger {
5
+ log: (message: string, args?: unknown) => void;
6
+ info: (message: string, args?: unknown) => void;
7
+ warn: (message: string, error?: unknown) => void;
8
+ error: (message: string, error?: unknown) => void;
9
+ debug: (message: string, args?: unknown) => void;
10
+ }
11
+ /**
12
+ * Creates a logger with configurable output based on enabled flag
13
+ */
14
+ export declare const createLogger: (enabled: boolean) => Logger;
15
+ /**
16
+ * Default logger instance (enabled by default)
17
+ */
18
+ export declare const logger: Logger;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Logging Infrastructure
3
+ *
4
+ * Provides structured logging with configurable output levels
5
+ * and CloudEvents-specific logging utilities
6
+ */
7
+ const LOG_PREFIX = 'cloudevents';
8
+ /**
9
+ * Creates a logger with configurable output based on enabled flag
10
+ */
11
+ export const createLogger = (enabled) => {
12
+ const logWithArgs = (consoleFn, message, args) => {
13
+ const formattedMessage = `[${LOG_PREFIX}] ${message}`;
14
+ args !== undefined ? consoleFn(formattedMessage, args) : consoleFn(formattedMessage);
15
+ };
16
+ return {
17
+ log: (message, args) => enabled && logWithArgs(console.log, message, args),
18
+ info: (message, args) => enabled && logWithArgs(console.info, message, args),
19
+ warn: (message, error) => enabled && logWithArgs(console.warn, message, error),
20
+ error: (message, error) => logWithArgs(console.error, message, error),
21
+ debug: (message, args) => logWithArgs(console.debug, message, args),
22
+ };
23
+ };
24
+ /**
25
+ * Default logger instance (enabled by default)
26
+ */
27
+ export const logger = createLogger(true);
@@ -0,0 +1,171 @@
1
+ /**
2
+ * CloudEvents Middleware for Hono - Simplified Core
3
+ *
4
+ * Supports automatic handler discovery and manual registration.
5
+ * Handles event validation, routing, and safeParse mode for graceful degradation.
6
+ * Includes optional DLQ-Safe mode for Pub/Sub Push endpoints.
7
+ */
8
+ import type { Context } from 'hono';
9
+ import type { HandlerConstructor } from '../domain';
10
+ import { clearHandlerCache } from '../processing';
11
+ /**
12
+ * Configuration options for CloudEvents middleware
13
+ *
14
+ * @interface CloudEventsOptions
15
+ */
16
+ export interface CloudEventsOptions {
17
+ /**
18
+ * Directory path for automatic handler discovery
19
+ *
20
+ * @example './src/events' or './handlers'
21
+ * @default undefined
22
+ */
23
+ discover?: string;
24
+ /**
25
+ * Array of handler constructors for manual registration
26
+ *
27
+ * @example [CustomerCreatedHandler, OrderProcessedHandler]
28
+ * @default []
29
+ */
30
+ handlers?: HandlerConstructor[];
31
+ /**
32
+ * Logging configuration
33
+ *
34
+ * - `false`: No logging (production default)
35
+ * - `true`: Basic structured logging
36
+ * - `'pretty'`: Human-readable format (development)
37
+ * - `'structured'`: JSON format (production)
38
+ *
39
+ * @default false
40
+ */
41
+ log?: boolean | 'pretty' | 'structured';
42
+ /**
43
+ * Google Cloud Pub/Sub topic for quarantining invalid messages
44
+ *
45
+ * When specified, enables DLQ-Safe mode:
46
+ * - Always returns HTTP 204 to prevent redelivery
47
+ * - Quarantines validation errors and malformed events
48
+ * - Non-blocking background processing
49
+ *
50
+ * @example 'projects/my-project/topics/quarantine-topic'
51
+ * @default undefined
52
+ */
53
+ quarantineTopic?: string;
54
+ /**
55
+ * Google Cloud Pub/Sub topic for publishing recoverable handler errors
56
+ *
57
+ * Used in DLQ-Safe mode to publish errors that can be retried later:
58
+ * - Handler execution failures
59
+ * - Temporary processing errors
60
+ * - Network timeouts
61
+ *
62
+ * @example 'projects/my-project/topics/error-topic'
63
+ * @default undefined
64
+ */
65
+ errorTopic?: string;
66
+ /**
67
+ * Google Cloud Project ID
68
+ *
69
+ * @example 'my-production-project'
70
+ * @default Detected from environment (GOOGLE_CLOUD_PROJECT, etc.)
71
+ */
72
+ projectId?: string;
73
+ /**
74
+ * CloudEvent source identifier
75
+ *
76
+ * @example 'my-service' or 'https://my-domain.com/service'
77
+ * @default Auto-detected from environment
78
+ */
79
+ source?: string;
80
+ /**
81
+ * Set for message deduplication based on CloudEvent ID
82
+ *
83
+ * Automatically managed by the middleware to prevent duplicate processing.
84
+ * Can be provided for custom deduplication logic.
85
+ *
86
+ * @default new Set<string>()
87
+ */
88
+ processedMessageIds?: Set<string>;
89
+ }
90
+ export { clearHandlerCache };
91
+ /**
92
+ * CloudEvents middleware for Hono applications
93
+ *
94
+ * Provides automatic CloudEvent processing with handler discovery, validation,
95
+ * and optional DLQ-Safe mode for Google Cloud Pub/Sub Push endpoints.
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * import { Hono } from 'hono'
100
+ * import { cloudEvents } from '@orderboss/cloudevents'
101
+ *
102
+ * const app = new Hono()
103
+ *
104
+ * // Basic usage with handler discovery
105
+ * app.use('*', cloudEvents({
106
+ * discover: './src/events/*.event.{ts,js}',
107
+ * log: true
108
+ * }))
109
+ *
110
+ * // Manual handler registration
111
+ * app.use('*', cloudEvents({
112
+ * handlers: [CustomerCreatedHandler, OrderProcessedHandler],
113
+ * log: 'pretty'
114
+ * }))
115
+ *
116
+ * // DLQ-Safe mode for Pub/Sub Push
117
+ * app.use('*', cloudEvents({
118
+ * discover: './src/events/*.event.{ts,js}',
119
+ * quarantineTopic: 'quarantine-topic',
120
+ * errorTopic: 'error-topic',
121
+ * projectId: 'my-project',
122
+ * log: 'structured'
123
+ * }))
124
+ * ```
125
+ *
126
+ * @param options - Configuration options for the middleware
127
+ * @param options.discover - Directory path for automatic handler discovery (e.g., './src/events')
128
+ * @param options.handlers - Array of handler constructors for manual registration
129
+ * @param options.log - Enable logging: false (default), true, 'pretty' (dev), or 'structured' (prod)
130
+ * @param options.quarantineTopic - Pub/Sub topic for quarantining invalid messages (enables DLQ-Safe mode)
131
+ * @param options.errorTopic - Pub/Sub topic for publishing recoverable handler errors
132
+ * @param options.projectId - Google Cloud Project ID (defaults to environment detection)
133
+ * @param options.source - CloudEvent source identifier (defaults to auto-detection)
134
+ * @param options.processedMessageIds - Set for message deduplication (automatically managed)
135
+ *
136
+ * @returns Hono middleware function that processes CloudEvents
137
+ *
138
+ * @remarks
139
+ * **Handler Discovery:**
140
+ * - Automatically discovers handlers in the specified directory
141
+ * - Handlers must export a class that extends the base handler pattern
142
+ * - Supports nested directories and TypeScript files
143
+ *
144
+ * **Event Format Support:**
145
+ * - CloudEvents Structured mode (JSON with specversion)
146
+ * - CloudEvents Binary mode (headers + data)
147
+ * - Google Pub/Sub Push format
148
+ * - Raw event data (wrapped in CloudEvent)
149
+ *
150
+ * **DLQ-Safe Mode:**
151
+ * - Activated when `quarantineTopic` is specified
152
+ * - Always returns HTTP 204 to prevent Pub/Sub redelivery
153
+ * - Quarantines invalid messages to specified topic
154
+ * - Publishes handler errors to error topic
155
+ * - All DLQ operations are non-blocking for optimal performance
156
+ *
157
+ * **Standard Mode:**
158
+ * - Returns HTTP 200 for successful processing
159
+ * - Returns HTTP 422 for validation errors
160
+ * - Returns HTTP 500 for handler errors
161
+ * - Allows Pub/Sub DLQ behavior for unhandled errors
162
+ *
163
+ * **Performance Features:**
164
+ * - Handler caching for improved startup time
165
+ * - Dynamic parser loading for optimal bundle size
166
+ * - Message deduplication based on CloudEvent ID
167
+ * - Background processing for DLQ operations
168
+ *
169
+ * @since 1.0.0
170
+ */
171
+ export declare function cloudEvents(options?: CloudEventsOptions): (ctx: Context, next: () => Promise<void>) => Promise<void | Response>;