-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp-server.zod.ts
More file actions
366 lines (310 loc) · 10 KB
/
http-server.zod.ts
File metadata and controls
366 lines (310 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { HttpMethod, CorsConfigSchema, RateLimitConfigSchema, StaticMountSchema } from '../shared/http.zod';
/**
* HTTP Server Protocol
*
* Defines the runtime HTTP server configuration and capabilities.
* Provides abstractions for HTTP server implementations (Express, Fastify, Hono, etc.)
*
* Architecture alignment:
* - Kubernetes: Service and Ingress resources
* - AWS: API Gateway configuration
* - Spring Boot: Application properties
*/
// ==========================================
// Server Configuration
// ==========================================
/**
* HTTP Server Configuration Schema
* Core configuration for HTTP server instances
*
* @example
* {
* "port": 3000,
* "host": "0.0.0.0",
* "cors": {
* "enabled": true,
* "origins": ["http://localhost:3000"]
* },
* "compression": true,
* "requestTimeout": 30000
* }
*/
export const HttpServerConfigSchema = z.object({
/**
* Server port number
*/
port: z.number().int().min(1).max(65535).default(3000).describe('Port number to listen on'),
/**
* Server host address
*/
host: z.string().default('0.0.0.0').describe('Host address to bind to'),
/**
* CORS configuration
*/
cors: CorsConfigSchema.optional().describe('CORS configuration'),
/**
* Request handling options
*/
requestTimeout: z.number().int().default(30000).describe('Request timeout in milliseconds'),
bodyLimit: z.string().default('10mb').describe('Maximum request body size'),
/**
* Compression settings
*/
compression: z.boolean().default(true).describe('Enable response compression'),
/**
* Security headers
*/
security: z.object({
helmet: z.boolean().default(true).describe('Enable security headers via helmet'),
rateLimit: RateLimitConfigSchema.optional().describe('Global rate limiting configuration'),
}).optional().describe('Security configuration'),
/**
* Static file serving
*/
static: z.array(StaticMountSchema).optional().describe('Static file serving configuration'),
/**
* Trust proxy settings
*/
trustProxy: z.boolean().default(false).describe('Trust X-Forwarded-* headers'),
});
export type HttpServerConfig = z.infer<typeof HttpServerConfigSchema>;
export type HttpServerConfigInput = z.input<typeof HttpServerConfigSchema>;
// ==========================================
// Route Registration
// ==========================================
/**
* Route Handler Metadata Schema
* Metadata for route handlers used in registration
*/
export const RouteHandlerMetadataSchema = z.object({
/**
* HTTP method
*/
method: HttpMethod.describe('HTTP method'),
/**
* URL path pattern (supports parameters like /api/users/:id)
*/
path: z.string().describe('URL path pattern'),
/**
* Handler function name or identifier
*/
handler: z.string().describe('Handler identifier or name'),
/**
* Route metadata
*/
metadata: z.object({
summary: z.string().optional().describe('Route summary for documentation'),
description: z.string().optional().describe('Route description'),
tags: z.array(z.string()).optional().describe('Tags for grouping'),
operationId: z.string().optional().describe('Unique operation identifier'),
}).optional(),
/**
* Security requirements
*/
security: z.object({
authRequired: z.boolean().default(true).describe('Require authentication'),
permissions: z.array(z.string()).optional().describe('Required permissions'),
rateLimit: z.string().optional().describe('Rate limit policy override'),
}).optional(),
});
export type RouteHandlerMetadata = z.infer<typeof RouteHandlerMetadataSchema>;
export type RouteHandlerMetadataInput = z.input<typeof RouteHandlerMetadataSchema>;
// ==========================================
// Middleware Configuration
// ==========================================
/**
* Middleware Type Enum
*/
export const MiddlewareType = z.enum([
'authentication', // Authentication middleware
'authorization', // Authorization/permission checks
'logging', // Request/response logging
'validation', // Input validation
'transformation', // Request/response transformation
'error', // Error handling
'custom', // Custom middleware
]);
export type MiddlewareType = z.infer<typeof MiddlewareType>;
/**
* Middleware Configuration Schema
* Defines middleware execution order and configuration
*
* @example
* {
* "name": "auth_middleware",
* "type": "authentication",
* "enabled": true,
* "order": 10,
* "config": {
* "jwtSecret": "secret",
* "excludePaths": ["/health", "/metrics"]
* }
* }
*/
export const MiddlewareConfigSchema = z.object({
/**
* Middleware identifier
*/
name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Middleware name (snake_case)'),
/**
* Middleware type
*/
type: MiddlewareType.describe('Middleware type'),
/**
* Enable/disable middleware
*/
enabled: z.boolean().default(true).describe('Whether middleware is enabled'),
/**
* Execution order (lower numbers execute first)
*/
order: z.number().int().default(100).describe('Execution order priority'),
/**
* Middleware-specific configuration
*/
config: z.record(z.string(), z.unknown()).optional().describe('Middleware configuration object'),
/**
* Path patterns to apply middleware to
*/
paths: z.object({
include: z.array(z.string()).optional().describe('Include path patterns (glob)'),
exclude: z.array(z.string()).optional().describe('Exclude path patterns (glob)'),
}).optional().describe('Path filtering'),
});
export type MiddlewareConfig = z.infer<typeof MiddlewareConfigSchema>;
export type MiddlewareConfigInput = z.input<typeof MiddlewareConfigSchema>;
// ==========================================
// Server Lifecycle Events
// ==========================================
/**
* Server Event Type Enum
*/
export const ServerEventType = z.enum([
'starting', // Server is starting
'started', // Server has started and is listening
'stopping', // Server is stopping
'stopped', // Server has stopped
'request', // Request received
'response', // Response sent
'error', // Error occurred
]);
export type ServerEventType = z.infer<typeof ServerEventType>;
/**
* Server Event Schema
* Events emitted by the HTTP server during lifecycle
*/
export const ServerEventSchema = z.object({
/**
* Event type
*/
type: ServerEventType.describe('Event type'),
/**
* Timestamp
*/
timestamp: z.string().datetime().describe('Event timestamp (ISO 8601)'),
/**
* Event payload
*/
data: z.record(z.string(), z.unknown()).optional().describe('Event-specific data'),
});
export type ServerEvent = z.infer<typeof ServerEventSchema>;
// ==========================================
// Server Capability Declaration
// ==========================================
/**
* Server Capabilities Schema
* Declares what features a server implementation supports
*/
export const ServerCapabilitiesSchema = z.object({
/**
* Supported HTTP versions
*/
httpVersions: z.array(z.enum(['1.0', '1.1', '2.0', '3.0'])).default(['1.1']).describe('Supported HTTP versions'),
/**
* WebSocket support
*/
websocket: z.boolean().default(false).describe('WebSocket support'),
/**
* Server-Sent Events support
*/
sse: z.boolean().default(false).describe('Server-Sent Events support'),
/**
* HTTP/2 Server Push
*/
serverPush: z.boolean().default(false).describe('HTTP/2 Server Push support'),
/**
* Streaming support
*/
streaming: z.boolean().default(true).describe('Response streaming support'),
/**
* Middleware support
*/
middleware: z.boolean().default(true).describe('Middleware chain support'),
/**
* Route parameterization
*/
routeParams: z.boolean().default(true).describe('URL parameter support (/users/:id)'),
/**
* Built-in compression
*/
compression: z.boolean().default(true).describe('Built-in compression support'),
});
export type ServerCapabilities = z.infer<typeof ServerCapabilitiesSchema>;
export type ServerCapabilitiesInput = z.input<typeof ServerCapabilitiesSchema>;
// ==========================================
// Server Status & Metrics
// ==========================================
/**
* Server Status Schema
* Current operational status of the server
*/
export const ServerStatusSchema = z.object({
/**
* Server state
*/
state: z.enum(['stopped', 'starting', 'running', 'stopping', 'error']).describe('Current server state'),
/**
* Uptime in milliseconds
*/
uptime: z.number().int().optional().describe('Server uptime in milliseconds'),
/**
* Server information
*/
server: z.object({
port: z.number().int().describe('Listening port'),
host: z.string().describe('Bound host'),
url: z.string().optional().describe('Full server URL'),
}).optional(),
/**
* Connection metrics
*/
connections: z.object({
active: z.number().int().describe('Active connections'),
total: z.number().int().describe('Total connections handled'),
}).optional(),
/**
* Request metrics
*/
requests: z.object({
total: z.number().int().describe('Total requests processed'),
success: z.number().int().describe('Successful requests'),
errors: z.number().int().describe('Failed requests'),
}).optional(),
});
export type ServerStatus = z.infer<typeof ServerStatusSchema>;
// ==========================================
// Helper Functions
// ==========================================
/**
* Helper to create HTTP server configuration
*/
export const HttpServerConfig = Object.assign(HttpServerConfigSchema, {
create: <T extends z.input<typeof HttpServerConfigSchema>>(config: T) => config,
});
/**
* Helper to create middleware configuration
*/
export const MiddlewareConfig = Object.assign(MiddlewareConfigSchema, {
create: <T extends z.input<typeof MiddlewareConfigSchema>>(config: T) => config,
});