@signaltree/events 7.3.5 → 7.3.6

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/index.cjs.js ADDED
@@ -0,0 +1,207 @@
1
+ 'use strict';
2
+
3
+ var factory = require('./factory.cjs.js');
4
+ var zod = require('zod');
5
+ var idempotency = require('./idempotency.cjs.js');
6
+
7
+ /**
8
+ * Event validation using Zod schemas
9
+ *
10
+ * Provides:
11
+ * - Base schemas for common event fields
12
+ * - Factory function to create event schemas
13
+ * - Runtime validation with detailed errors
14
+ */
15
+ // ============================================================================
16
+ // Base Schemas
17
+ // ============================================================================
18
+ /**
19
+ * Schema for event actor
20
+ */
21
+ const EventActorSchema = zod.z.object({
22
+ id: zod.z.string().min(1),
23
+ type: zod.z.enum(['user', 'system', 'admin', 'webhook']),
24
+ name: zod.z.string().optional()
25
+ });
26
+ /**
27
+ * Schema for event version
28
+ */
29
+ const EventVersionSchema = zod.z.object({
30
+ major: zod.z.number().int().min(1),
31
+ minor: zod.z.number().int().min(0)
32
+ });
33
+ /**
34
+ * Schema for event metadata
35
+ */
36
+ const EventMetadataSchema = zod.z.object({
37
+ source: zod.z.string().min(1),
38
+ environment: zod.z.string().min(1),
39
+ ip: zod.z.string().optional(),
40
+ userAgent: zod.z.string().optional()
41
+ }).passthrough(); // Allow additional properties
42
+ /**
43
+ * Schema for aggregate info
44
+ */
45
+ const AggregateSchema = zod.z.object({
46
+ type: zod.z.string().min(1),
47
+ id: zod.z.string().min(1)
48
+ }).optional();
49
+ /**
50
+ * Base event schema without data field
51
+ */
52
+ const BaseEventSchema = zod.z.object({
53
+ id: zod.z.string().uuid(),
54
+ type: zod.z.string().min(1),
55
+ version: EventVersionSchema,
56
+ timestamp: zod.z.string().datetime(),
57
+ correlationId: zod.z.string().uuid(),
58
+ causationId: zod.z.string().uuid().optional(),
59
+ actor: EventActorSchema,
60
+ metadata: EventMetadataSchema,
61
+ priority: zod.z.enum(['critical', 'high', 'normal', 'low', 'bulk']).optional(),
62
+ aggregate: AggregateSchema
63
+ });
64
+ // ============================================================================
65
+ // Schema Factory
66
+ // ============================================================================
67
+ /**
68
+ * Create a typed event schema with Zod validation
69
+ *
70
+ * @param eventType - The event type string (e.g., 'TradeProposalCreated')
71
+ * @param dataSchema - Zod schema for the event's data field
72
+ * @returns Complete event schema
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * const TradeProposalCreatedSchema = createEventSchema('TradeProposalCreated', {
77
+ * tradeId: z.string().uuid(),
78
+ * initiatorId: z.string().uuid(),
79
+ * recipientId: z.string().uuid(),
80
+ * vehicleOfferedId: z.string().uuid(),
81
+ * terms: z.object({
82
+ * cashDifference: z.number().optional(),
83
+ * }),
84
+ * });
85
+ *
86
+ * type TradeProposalCreated = z.infer<typeof TradeProposalCreatedSchema>;
87
+ * ```
88
+ */
89
+ function createEventSchema(eventType, dataSchema) {
90
+ return BaseEventSchema.extend({
91
+ type: zod.z.literal(eventType),
92
+ data: zod.z.object(dataSchema)
93
+ });
94
+ }
95
+ /**
96
+ * Create event schema from existing Zod object
97
+ */
98
+ function createEventSchemaFromZod(eventType, dataSchema) {
99
+ return BaseEventSchema.extend({
100
+ type: zod.z.literal(eventType),
101
+ data: dataSchema
102
+ });
103
+ }
104
+ // ============================================================================
105
+ // Validation Functions
106
+ // ============================================================================
107
+ /**
108
+ * Custom error class for event validation failures
109
+ */
110
+ class EventValidationError extends Error {
111
+ zodError;
112
+ event;
113
+ constructor(message, zodError, event) {
114
+ super(message);
115
+ this.zodError = zodError;
116
+ this.event = event;
117
+ this.name = 'EventValidationError';
118
+ }
119
+ /**
120
+ * Get formatted error messages
121
+ */
122
+ get issues() {
123
+ return this.zodError.issues.map(issue => {
124
+ const path = issue.path.join('.');
125
+ return path ? `${path}: ${issue.message}` : issue.message;
126
+ });
127
+ }
128
+ }
129
+ /**
130
+ * Validate an event against a schema, throwing on failure
131
+ *
132
+ * @param schema - Zod schema to validate against
133
+ * @param event - Event to validate
134
+ * @returns Validated and typed event
135
+ * @throws EventValidationError if validation fails
136
+ *
137
+ * @example
138
+ * ```typescript
139
+ * try {
140
+ * const validEvent = validateEvent(TradeProposalCreatedSchema, rawEvent);
141
+ * // validEvent is typed as TradeProposalCreated
142
+ * } catch (error) {
143
+ * if (error instanceof EventValidationError) {
144
+ * console.error('Validation failed:', error.issues);
145
+ * }
146
+ * }
147
+ * ```
148
+ */
149
+ function validateEvent(schema, event) {
150
+ const result = schema.safeParse(event);
151
+ if (!result.success) {
152
+ throw new EventValidationError(`Event validation failed: ${result.error.issues.map(i => i.message).join(', ')}`, result.error, event);
153
+ }
154
+ return result.data;
155
+ }
156
+ /**
157
+ * Check if an event is valid without throwing
158
+ *
159
+ * @param schema - Zod schema to validate against
160
+ * @param event - Event to check
161
+ * @returns true if valid, false otherwise
162
+ */
163
+ function isValidEvent(schema, event) {
164
+ return schema.safeParse(event).success;
165
+ }
166
+ /**
167
+ * Parse an event, returning result with success/error
168
+ *
169
+ * @param schema - Zod schema to parse with
170
+ * @param event - Event to parse
171
+ * @returns SafeParseResult with data or error
172
+ */
173
+ function parseEvent(schema, event) {
174
+ return schema.safeParse(event);
175
+ }
176
+
177
+ exports.DEFAULT_EVENT_VERSION = factory.DEFAULT_EVENT_VERSION;
178
+ exports.EVENT_PRIORITIES = factory.EVENT_PRIORITIES;
179
+ exports.createEvent = factory.createEvent;
180
+ exports.createEventFactory = factory.createEventFactory;
181
+ exports.generateCorrelationId = factory.generateCorrelationId;
182
+ exports.generateEventId = factory.generateEventId;
183
+ Object.defineProperty(exports, "z", {
184
+ enumerable: true,
185
+ get: function () { return zod.z; }
186
+ });
187
+ exports.DEFAULT_RETRY_CONFIGS = idempotency.DEFAULT_RETRY_CONFIGS;
188
+ exports.EventRegistry = idempotency.EventRegistry;
189
+ exports.InMemoryIdempotencyStore = idempotency.InMemoryIdempotencyStore;
190
+ exports.classifyError = idempotency.classifyError;
191
+ exports.createErrorClassifier = idempotency.createErrorClassifier;
192
+ exports.createEventRegistry = idempotency.createEventRegistry;
193
+ exports.createInMemoryIdempotencyStore = idempotency.createInMemoryIdempotencyStore;
194
+ exports.defaultErrorClassifier = idempotency.defaultErrorClassifier;
195
+ exports.generateCorrelationKey = idempotency.generateCorrelationKey;
196
+ exports.generateIdempotencyKey = idempotency.generateIdempotencyKey;
197
+ exports.isRetryableError = idempotency.isRetryableError;
198
+ exports.BaseEventSchema = BaseEventSchema;
199
+ exports.EventActorSchema = EventActorSchema;
200
+ exports.EventMetadataSchema = EventMetadataSchema;
201
+ exports.EventValidationError = EventValidationError;
202
+ exports.EventVersionSchema = EventVersionSchema;
203
+ exports.createEventSchema = createEventSchema;
204
+ exports.createEventSchemaFromZod = createEventSchemaFromZod;
205
+ exports.isValidEvent = isValidEvent;
206
+ exports.parseEvent = parseEvent;
207
+ exports.validateEvent = validateEvent;