ts-typed-api 0.2.19 → 0.2.20
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/handler.js +74 -2
- package/dist/hono-cloudflare-workers.js +86 -2
- package/dist/router.d.ts +3 -0
- package/examples/simple/definitions.ts +23 -0
- package/examples/simple/server.ts +27 -0
- package/package.json +1 -1
- package/src/handler.ts +80 -2
- package/src/hono-cloudflare-workers.ts +90 -2
- package/src/router.ts +4 -0
- package/tests/setup.ts +27 -0
- package/tests/simple-api.test.ts +130 -0
package/dist/handler.js
CHANGED
|
@@ -6,6 +6,55 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.registerRouteHandlers = registerRouteHandlers;
|
|
7
7
|
const zod_1 = require("zod");
|
|
8
8
|
const multer_1 = __importDefault(require("multer"));
|
|
9
|
+
// Helper function to preprocess parameters for type coercion
|
|
10
|
+
function preprocessParams(params, paramsSchema) {
|
|
11
|
+
if (!paramsSchema || !params)
|
|
12
|
+
return params;
|
|
13
|
+
// Create a copy to avoid mutating the original
|
|
14
|
+
const processedParams = { ...params };
|
|
15
|
+
// Get the shape of the schema if it's a ZodObject
|
|
16
|
+
if (paramsSchema instanceof zod_1.z.ZodObject) {
|
|
17
|
+
const shape = paramsSchema.shape;
|
|
18
|
+
for (const [key, value] of Object.entries(processedParams)) {
|
|
19
|
+
if (typeof value === 'string' && shape[key]) {
|
|
20
|
+
const fieldSchema = shape[key];
|
|
21
|
+
// Handle ZodOptional and ZodDefault wrappers
|
|
22
|
+
let innerSchema = fieldSchema;
|
|
23
|
+
if (fieldSchema instanceof zod_1.z.ZodOptional) {
|
|
24
|
+
innerSchema = fieldSchema._def.innerType;
|
|
25
|
+
}
|
|
26
|
+
if (fieldSchema instanceof zod_1.z.ZodDefault) {
|
|
27
|
+
innerSchema = fieldSchema._def.innerType;
|
|
28
|
+
}
|
|
29
|
+
// Handle nested ZodOptional/ZodDefault combinations
|
|
30
|
+
while (innerSchema instanceof zod_1.z.ZodOptional || innerSchema instanceof zod_1.z.ZodDefault) {
|
|
31
|
+
if (innerSchema instanceof zod_1.z.ZodOptional) {
|
|
32
|
+
innerSchema = innerSchema._def.innerType;
|
|
33
|
+
}
|
|
34
|
+
else if (innerSchema instanceof zod_1.z.ZodDefault) {
|
|
35
|
+
innerSchema = innerSchema._def.innerType;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Convert based on the inner schema type
|
|
39
|
+
if (innerSchema instanceof zod_1.z.ZodNumber) {
|
|
40
|
+
const numValue = Number(value);
|
|
41
|
+
if (!isNaN(numValue)) {
|
|
42
|
+
processedParams[key] = numValue;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
else if (innerSchema instanceof zod_1.z.ZodBoolean) {
|
|
46
|
+
if (value === 'true') {
|
|
47
|
+
processedParams[key] = true;
|
|
48
|
+
}
|
|
49
|
+
else if (value === 'false') {
|
|
50
|
+
processedParams[key] = false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return processedParams;
|
|
57
|
+
}
|
|
9
58
|
// Helper function to preprocess query parameters for type coercion
|
|
10
59
|
function preprocessQueryParams(query, querySchema) {
|
|
11
60
|
if (!querySchema || !query)
|
|
@@ -277,9 +326,12 @@ middlewares) {
|
|
|
277
326
|
try {
|
|
278
327
|
// Ensure TDef is correctly used for type inference if this section needs it.
|
|
279
328
|
// Currently, parsedParams,Query,Body are based on runtime routeDefinition.
|
|
280
|
-
const
|
|
281
|
-
?
|
|
329
|
+
const preprocessedParams = ('params' in routeDefinition && routeDefinition.params)
|
|
330
|
+
? preprocessParams(expressReq.params, routeDefinition.params)
|
|
282
331
|
: expressReq.params;
|
|
332
|
+
const parsedParams = ('params' in routeDefinition && routeDefinition.params)
|
|
333
|
+
? routeDefinition.params.parse(preprocessedParams)
|
|
334
|
+
: preprocessedParams;
|
|
283
335
|
// Preprocess query parameters to handle type coercion from strings
|
|
284
336
|
const preprocessedQuery = ('query' in routeDefinition && routeDefinition.query)
|
|
285
337
|
? preprocessQueryParams(expressReq.query, routeDefinition.query)
|
|
@@ -380,6 +432,26 @@ middlewares) {
|
|
|
380
432
|
Object.getPrototypeOf(expressRes).setHeader.call(expressRes, name, value);
|
|
381
433
|
return typedExpressRes;
|
|
382
434
|
};
|
|
435
|
+
// SSE streaming methods
|
|
436
|
+
typedExpressRes.startSSE = () => {
|
|
437
|
+
typedExpressRes.setHeader('Content-Type', 'text/event-stream');
|
|
438
|
+
typedExpressRes.setHeader('Cache-Control', 'no-cache');
|
|
439
|
+
typedExpressRes.setHeader('Connection', 'keep-alive');
|
|
440
|
+
typedExpressRes.setHeader('Access-Control-Allow-Origin', '*');
|
|
441
|
+
typedExpressRes.setHeader('Access-Control-Allow-Headers', 'Cache-Control');
|
|
442
|
+
};
|
|
443
|
+
typedExpressRes.streamSSE = (eventName, data, id) => {
|
|
444
|
+
let event = '';
|
|
445
|
+
if (eventName)
|
|
446
|
+
event += `event: ${eventName}\n`;
|
|
447
|
+
if (id)
|
|
448
|
+
event += `id: ${id}\n`;
|
|
449
|
+
event += `data: ${JSON.stringify(data)}\n\n`;
|
|
450
|
+
expressRes.write(event);
|
|
451
|
+
};
|
|
452
|
+
typedExpressRes.endStream = () => {
|
|
453
|
+
expressRes.end();
|
|
454
|
+
};
|
|
383
455
|
const specificHandlerFn = handler;
|
|
384
456
|
await specificHandlerFn(finalTypedReq, typedExpressRes);
|
|
385
457
|
}
|
|
@@ -19,6 +19,55 @@ exports.honoFileSchema = zod_1.z.object({
|
|
|
19
19
|
path: zod_1.z.string().optional(),
|
|
20
20
|
stream: zod_1.z.any().optional(),
|
|
21
21
|
});
|
|
22
|
+
// Helper function to preprocess parameters for type coercion
|
|
23
|
+
function preprocessParams(params, paramsSchema) {
|
|
24
|
+
if (!paramsSchema || !params)
|
|
25
|
+
return params;
|
|
26
|
+
// Create a copy to avoid mutating the original
|
|
27
|
+
const processedParams = { ...params };
|
|
28
|
+
// Get the shape of the schema if it's a ZodObject
|
|
29
|
+
if (paramsSchema instanceof zod_1.z.ZodObject) {
|
|
30
|
+
const shape = paramsSchema.shape;
|
|
31
|
+
for (const [key, value] of Object.entries(processedParams)) {
|
|
32
|
+
if (typeof value === 'string' && shape[key]) {
|
|
33
|
+
const fieldSchema = shape[key];
|
|
34
|
+
// Handle ZodOptional and ZodDefault wrappers
|
|
35
|
+
let innerSchema = fieldSchema;
|
|
36
|
+
if (fieldSchema instanceof zod_1.z.ZodOptional) {
|
|
37
|
+
innerSchema = fieldSchema._def.innerType;
|
|
38
|
+
}
|
|
39
|
+
if (fieldSchema instanceof zod_1.z.ZodDefault) {
|
|
40
|
+
innerSchema = fieldSchema._def.innerType;
|
|
41
|
+
}
|
|
42
|
+
// Handle nested ZodOptional/ZodDefault combinations
|
|
43
|
+
while (innerSchema instanceof zod_1.z.ZodOptional || innerSchema instanceof zod_1.z.ZodDefault) {
|
|
44
|
+
if (innerSchema instanceof zod_1.z.ZodOptional) {
|
|
45
|
+
innerSchema = innerSchema._def.innerType;
|
|
46
|
+
}
|
|
47
|
+
else if (innerSchema instanceof zod_1.z.ZodDefault) {
|
|
48
|
+
innerSchema = innerSchema._def.innerType;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// Convert based on the inner schema type
|
|
52
|
+
if (innerSchema instanceof zod_1.z.ZodNumber) {
|
|
53
|
+
const numValue = Number(value);
|
|
54
|
+
if (!isNaN(numValue)) {
|
|
55
|
+
processedParams[key] = numValue;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
else if (innerSchema instanceof zod_1.z.ZodBoolean) {
|
|
59
|
+
if (value === 'true') {
|
|
60
|
+
processedParams[key] = true;
|
|
61
|
+
}
|
|
62
|
+
else if (value === 'false') {
|
|
63
|
+
processedParams[key] = false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return processedParams;
|
|
70
|
+
}
|
|
22
71
|
// Helper function to preprocess query parameters for type coercion
|
|
23
72
|
function preprocessQueryParams(query, querySchema) {
|
|
24
73
|
if (!querySchema || !query)
|
|
@@ -240,9 +289,12 @@ function registerHonoRouteHandlers(app, apiDefinition, routeHandlers, middleware
|
|
|
240
289
|
const honoMiddleware = async (c) => {
|
|
241
290
|
try {
|
|
242
291
|
// Parse and validate request
|
|
243
|
-
const
|
|
244
|
-
?
|
|
292
|
+
const preprocessedParams = ('params' in routeDefinition && routeDefinition.params)
|
|
293
|
+
? preprocessParams(c.req.param(), routeDefinition.params)
|
|
245
294
|
: c.req.param();
|
|
295
|
+
const parsedParams = ('params' in routeDefinition && routeDefinition.params)
|
|
296
|
+
? routeDefinition.params.parse(preprocessedParams)
|
|
297
|
+
: preprocessedParams;
|
|
246
298
|
const preprocessedQuery = ('query' in routeDefinition && routeDefinition.query)
|
|
247
299
|
? preprocessQueryParams(c.req.query(), routeDefinition.query)
|
|
248
300
|
: c.req.query();
|
|
@@ -351,6 +403,38 @@ function registerHonoRouteHandlers(app, apiDefinition, routeHandlers, middleware
|
|
|
351
403
|
setHeader: (name, value) => {
|
|
352
404
|
c.header(name, value);
|
|
353
405
|
return fakeRes;
|
|
406
|
+
},
|
|
407
|
+
// SSE streaming methods for Hono
|
|
408
|
+
startSSE: () => {
|
|
409
|
+
c.header('Content-Type', 'text/event-stream');
|
|
410
|
+
c.header('Cache-Control', 'no-cache');
|
|
411
|
+
c.header('Connection', 'keep-alive');
|
|
412
|
+
c.header('Access-Control-Allow-Origin', '*');
|
|
413
|
+
c.header('Access-Control-Allow-Headers', 'Cache-Control');
|
|
414
|
+
},
|
|
415
|
+
streamSSE: (eventName, data, id) => {
|
|
416
|
+
let event = '';
|
|
417
|
+
if (eventName)
|
|
418
|
+
event += `event: ${eventName}\n`;
|
|
419
|
+
if (id)
|
|
420
|
+
event += `id: ${id}\n`;
|
|
421
|
+
event += `data: ${JSON.stringify(data)}\n\n`;
|
|
422
|
+
// For Hono, we need to accumulate the response
|
|
423
|
+
if (!c.__sseBuffer) {
|
|
424
|
+
c.__sseBuffer = '';
|
|
425
|
+
}
|
|
426
|
+
c.__sseBuffer += event;
|
|
427
|
+
},
|
|
428
|
+
endStream: () => {
|
|
429
|
+
// Send the accumulated SSE data
|
|
430
|
+
const sseData = c.__sseBuffer || '';
|
|
431
|
+
c.__response = new Response(sseData, {
|
|
432
|
+
headers: {
|
|
433
|
+
'Content-Type': 'text/event-stream',
|
|
434
|
+
'Cache-Control': 'no-cache',
|
|
435
|
+
'Connection': 'keep-alive'
|
|
436
|
+
}
|
|
437
|
+
});
|
|
354
438
|
}
|
|
355
439
|
};
|
|
356
440
|
const specificHandlerFn = handler;
|
package/dist/router.d.ts
CHANGED
|
@@ -17,6 +17,9 @@ export interface TypedResponse<TDef extends ApiDefinitionSchema, TDomain extends
|
|
|
17
17
|
respondContentType: (status: number, data: any, contentType: string) => void;
|
|
18
18
|
setHeader: (name: string, value: string) => this;
|
|
19
19
|
json: <B = any>(body: B) => this;
|
|
20
|
+
startSSE: () => void;
|
|
21
|
+
streamSSE: (eventName?: string, data?: any, id?: string) => void;
|
|
22
|
+
endStream: () => void;
|
|
20
23
|
}
|
|
21
24
|
export declare function createRouteHandler<TDef extends ApiDefinitionSchema, TDomain extends keyof TDef['endpoints'], TRouteKey extends keyof TDef['endpoints'][TDomain], // Using direct keyof for simplicity
|
|
22
25
|
Ctx extends Record<string, any> = Record<string, any>>(domain: TDomain, routeKey: TRouteKey, handler: (req: TypedRequest<TDef, TDomain, TRouteKey, ApiParams<TDef, TDomain, TRouteKey>, ApiBody<TDef, TDomain, TRouteKey>, ApiQuery<TDef, TDomain, TRouteKey>, Record<string, any>, Ctx>, res: TypedResponse<TDef, TDomain, TRouteKey>) => Promise<void> | void): {
|
|
@@ -54,6 +54,29 @@ export const PublicApiDefinition = CreateApiDefinition({
|
|
|
54
54
|
}),
|
|
55
55
|
})
|
|
56
56
|
},
|
|
57
|
+
longpoll: {
|
|
58
|
+
method: 'GET',
|
|
59
|
+
path: '/longpoll/:sequence',
|
|
60
|
+
description: 'Long polling endpoint that simulates delayed response',
|
|
61
|
+
params: z.object({
|
|
62
|
+
sequence: z.number().int().min(1)
|
|
63
|
+
}),
|
|
64
|
+
responses: CreateResponses({
|
|
65
|
+
200: z.object({
|
|
66
|
+
sequence: z.number(),
|
|
67
|
+
data: z.string(),
|
|
68
|
+
timestamp: z.number()
|
|
69
|
+
}),
|
|
70
|
+
})
|
|
71
|
+
},
|
|
72
|
+
stream: {
|
|
73
|
+
method: 'GET',
|
|
74
|
+
path: '/stream',
|
|
75
|
+
description: 'Server-Sent Events streaming endpoint',
|
|
76
|
+
responses: CreateResponses({
|
|
77
|
+
200: z.string() // Raw SSE data
|
|
78
|
+
})
|
|
79
|
+
},
|
|
57
80
|
}
|
|
58
81
|
}
|
|
59
82
|
})
|
|
@@ -49,6 +49,33 @@ RegisterHandlers(app, PublicApiDefinition, {
|
|
|
49
49
|
res.setHeader('x-custom-test', 'test-value');
|
|
50
50
|
res.setHeader('x-another-header', 'another-value');
|
|
51
51
|
res.respond(200, { message: "headers set" });
|
|
52
|
+
},
|
|
53
|
+
longpoll: async (req, res) => {
|
|
54
|
+
const sequence = req.params.sequence;
|
|
55
|
+
// Simulate long polling delay based on sequence
|
|
56
|
+
const delay = sequence * 100; // 100ms per sequence number
|
|
57
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
58
|
+
res.respond(200, {
|
|
59
|
+
sequence,
|
|
60
|
+
data: `object ${sequence}`,
|
|
61
|
+
timestamp: Date.now()
|
|
62
|
+
});
|
|
63
|
+
},
|
|
64
|
+
stream: async (req, res) => {
|
|
65
|
+
// Initialize SSE with proper headers
|
|
66
|
+
res.startSSE();
|
|
67
|
+
|
|
68
|
+
// Send SSE events with JSON data at intervals
|
|
69
|
+
await res.streamSSE('update', { sequence: 1, data: 'object 1' });
|
|
70
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
71
|
+
|
|
72
|
+
await res.streamSSE('update', { sequence: 2, data: 'object 2' });
|
|
73
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
74
|
+
|
|
75
|
+
await res.streamSSE('update', { sequence: 3, data: 'object 3' });
|
|
76
|
+
|
|
77
|
+
// Close the stream
|
|
78
|
+
res.endStream();
|
|
52
79
|
}
|
|
53
80
|
},
|
|
54
81
|
status: {
|
package/package.json
CHANGED
package/src/handler.ts
CHANGED
|
@@ -27,6 +27,59 @@ export type EndpointMiddleware<TDef extends ApiDefinitionSchema = ApiDefinitionS
|
|
|
27
27
|
}[keyof TDef['endpoints']]
|
|
28
28
|
) => void | Promise<void>;
|
|
29
29
|
|
|
30
|
+
// Helper function to preprocess parameters for type coercion
|
|
31
|
+
function preprocessParams(params: any, paramsSchema?: z.ZodTypeAny): any {
|
|
32
|
+
if (!paramsSchema || !params) return params;
|
|
33
|
+
|
|
34
|
+
// Create a copy to avoid mutating the original
|
|
35
|
+
const processedParams = { ...params };
|
|
36
|
+
|
|
37
|
+
// Get the shape of the schema if it's a ZodObject
|
|
38
|
+
if (paramsSchema instanceof z.ZodObject) {
|
|
39
|
+
const shape = paramsSchema.shape;
|
|
40
|
+
|
|
41
|
+
for (const [key, value] of Object.entries(processedParams)) {
|
|
42
|
+
if (typeof value === 'string' && shape[key]) {
|
|
43
|
+
const fieldSchema = shape[key];
|
|
44
|
+
|
|
45
|
+
// Handle ZodOptional and ZodDefault wrappers
|
|
46
|
+
let innerSchema = fieldSchema;
|
|
47
|
+
if (fieldSchema instanceof z.ZodOptional) {
|
|
48
|
+
innerSchema = fieldSchema._def.innerType;
|
|
49
|
+
}
|
|
50
|
+
if (fieldSchema instanceof z.ZodDefault) {
|
|
51
|
+
innerSchema = fieldSchema._def.innerType;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Handle nested ZodOptional/ZodDefault combinations
|
|
55
|
+
while (innerSchema instanceof z.ZodOptional || innerSchema instanceof z.ZodDefault) {
|
|
56
|
+
if (innerSchema instanceof z.ZodOptional) {
|
|
57
|
+
innerSchema = innerSchema._def.innerType;
|
|
58
|
+
} else if (innerSchema instanceof z.ZodDefault) {
|
|
59
|
+
innerSchema = innerSchema._def.innerType;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Convert based on the inner schema type
|
|
64
|
+
if (innerSchema instanceof z.ZodNumber) {
|
|
65
|
+
const numValue = Number(value);
|
|
66
|
+
if (!isNaN(numValue)) {
|
|
67
|
+
processedParams[key] = numValue;
|
|
68
|
+
}
|
|
69
|
+
} else if (innerSchema instanceof z.ZodBoolean) {
|
|
70
|
+
if (value === 'true') {
|
|
71
|
+
processedParams[key] = true;
|
|
72
|
+
} else if (value === 'false') {
|
|
73
|
+
processedParams[key] = false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return processedParams;
|
|
81
|
+
}
|
|
82
|
+
|
|
30
83
|
// Helper function to preprocess query parameters for type coercion
|
|
31
84
|
function preprocessQueryParams(query: any, querySchema?: z.ZodTypeAny): any {
|
|
32
85
|
if (!querySchema || !query) return query;
|
|
@@ -326,10 +379,14 @@ export function registerRouteHandlers<TDef extends ApiDefinitionSchema>(
|
|
|
326
379
|
try {
|
|
327
380
|
// Ensure TDef is correctly used for type inference if this section needs it.
|
|
328
381
|
// Currently, parsedParams,Query,Body are based on runtime routeDefinition.
|
|
329
|
-
const
|
|
330
|
-
? (routeDefinition.params as z.ZodTypeAny)
|
|
382
|
+
const preprocessedParams = ('params' in routeDefinition && routeDefinition.params)
|
|
383
|
+
? preprocessParams(expressReq.params, routeDefinition.params as z.ZodTypeAny)
|
|
331
384
|
: expressReq.params;
|
|
332
385
|
|
|
386
|
+
const parsedParams = ('params' in routeDefinition && routeDefinition.params)
|
|
387
|
+
? (routeDefinition.params as z.ZodTypeAny).parse(preprocessedParams)
|
|
388
|
+
: preprocessedParams;
|
|
389
|
+
|
|
333
390
|
// Preprocess query parameters to handle type coercion from strings
|
|
334
391
|
const preprocessedQuery = ('query' in routeDefinition && routeDefinition.query)
|
|
335
392
|
? preprocessQueryParams(expressReq.query, routeDefinition.query as z.ZodTypeAny)
|
|
@@ -444,6 +501,27 @@ export function registerRouteHandlers<TDef extends ApiDefinitionSchema>(
|
|
|
444
501
|
return typedExpressRes;
|
|
445
502
|
};
|
|
446
503
|
|
|
504
|
+
// SSE streaming methods
|
|
505
|
+
typedExpressRes.startSSE = () => {
|
|
506
|
+
typedExpressRes.setHeader('Content-Type', 'text/event-stream');
|
|
507
|
+
typedExpressRes.setHeader('Cache-Control', 'no-cache');
|
|
508
|
+
typedExpressRes.setHeader('Connection', 'keep-alive');
|
|
509
|
+
typedExpressRes.setHeader('Access-Control-Allow-Origin', '*');
|
|
510
|
+
typedExpressRes.setHeader('Access-Control-Allow-Headers', 'Cache-Control');
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
typedExpressRes.streamSSE = (eventName?: string, data?: any, id?: string) => {
|
|
514
|
+
let event = '';
|
|
515
|
+
if (eventName) event += `event: ${eventName}\n`;
|
|
516
|
+
if (id) event += `id: ${id}\n`;
|
|
517
|
+
event += `data: ${JSON.stringify(data)}\n\n`;
|
|
518
|
+
expressRes.write(event);
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
typedExpressRes.endStream = () => {
|
|
522
|
+
expressRes.end();
|
|
523
|
+
};
|
|
524
|
+
|
|
447
525
|
const specificHandlerFn = handler as (
|
|
448
526
|
req: TypedRequest<TDef, typeof currentDomain, typeof currentRouteKey>,
|
|
449
527
|
res: TypedResponse<TDef, typeof currentDomain, typeof currentRouteKey>
|
|
@@ -45,6 +45,59 @@ export type HonoTypedContext<
|
|
|
45
45
|
respond: TypedResponse<TDef, TDomain, TRouteKey>['respond'];
|
|
46
46
|
};
|
|
47
47
|
|
|
48
|
+
// Helper function to preprocess parameters for type coercion
|
|
49
|
+
function preprocessParams(params: any, paramsSchema?: z.ZodTypeAny): any {
|
|
50
|
+
if (!paramsSchema || !params) return params;
|
|
51
|
+
|
|
52
|
+
// Create a copy to avoid mutating the original
|
|
53
|
+
const processedParams = { ...params };
|
|
54
|
+
|
|
55
|
+
// Get the shape of the schema if it's a ZodObject
|
|
56
|
+
if (paramsSchema instanceof z.ZodObject) {
|
|
57
|
+
const shape = paramsSchema.shape;
|
|
58
|
+
|
|
59
|
+
for (const [key, value] of Object.entries(processedParams)) {
|
|
60
|
+
if (typeof value === 'string' && shape[key]) {
|
|
61
|
+
const fieldSchema = shape[key];
|
|
62
|
+
|
|
63
|
+
// Handle ZodOptional and ZodDefault wrappers
|
|
64
|
+
let innerSchema = fieldSchema;
|
|
65
|
+
if (fieldSchema instanceof z.ZodOptional) {
|
|
66
|
+
innerSchema = fieldSchema._def.innerType;
|
|
67
|
+
}
|
|
68
|
+
if (fieldSchema instanceof z.ZodDefault) {
|
|
69
|
+
innerSchema = fieldSchema._def.innerType;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Handle nested ZodOptional/ZodDefault combinations
|
|
73
|
+
while (innerSchema instanceof z.ZodOptional || innerSchema instanceof z.ZodDefault) {
|
|
74
|
+
if (innerSchema instanceof z.ZodOptional) {
|
|
75
|
+
innerSchema = innerSchema._def.innerType;
|
|
76
|
+
} else if (innerSchema instanceof z.ZodDefault) {
|
|
77
|
+
innerSchema = innerSchema._def.innerType;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Convert based on the inner schema type
|
|
82
|
+
if (innerSchema instanceof z.ZodNumber) {
|
|
83
|
+
const numValue = Number(value);
|
|
84
|
+
if (!isNaN(numValue)) {
|
|
85
|
+
processedParams[key] = numValue;
|
|
86
|
+
}
|
|
87
|
+
} else if (innerSchema instanceof z.ZodBoolean) {
|
|
88
|
+
if (value === 'true') {
|
|
89
|
+
processedParams[key] = true;
|
|
90
|
+
} else if (value === 'false') {
|
|
91
|
+
processedParams[key] = false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return processedParams;
|
|
99
|
+
}
|
|
100
|
+
|
|
48
101
|
// Helper function to preprocess query parameters for type coercion
|
|
49
102
|
function preprocessQueryParams(query: any, querySchema?: z.ZodTypeAny): any {
|
|
50
103
|
if (!querySchema || !query) return query;
|
|
@@ -304,10 +357,14 @@ export function registerHonoRouteHandlers<
|
|
|
304
357
|
) => {
|
|
305
358
|
try {
|
|
306
359
|
// Parse and validate request
|
|
307
|
-
const
|
|
308
|
-
? (routeDefinition.params as z.ZodTypeAny)
|
|
360
|
+
const preprocessedParams = ('params' in routeDefinition && routeDefinition.params)
|
|
361
|
+
? preprocessParams(c.req.param(), routeDefinition.params as z.ZodTypeAny)
|
|
309
362
|
: c.req.param();
|
|
310
363
|
|
|
364
|
+
const parsedParams = ('params' in routeDefinition && routeDefinition.params)
|
|
365
|
+
? (routeDefinition.params as z.ZodTypeAny).parse(preprocessedParams)
|
|
366
|
+
: preprocessedParams;
|
|
367
|
+
|
|
311
368
|
const preprocessedQuery = ('query' in routeDefinition && routeDefinition.query)
|
|
312
369
|
? preprocessQueryParams(c.req.query(), routeDefinition.query as z.ZodTypeAny)
|
|
313
370
|
: c.req.query();
|
|
@@ -429,6 +486,37 @@ export function registerHonoRouteHandlers<
|
|
|
429
486
|
setHeader: (name: string, value: string) => {
|
|
430
487
|
c.header(name, value);
|
|
431
488
|
return fakeRes;
|
|
489
|
+
},
|
|
490
|
+
// SSE streaming methods for Hono
|
|
491
|
+
startSSE: () => {
|
|
492
|
+
c.header('Content-Type', 'text/event-stream');
|
|
493
|
+
c.header('Cache-Control', 'no-cache');
|
|
494
|
+
c.header('Connection', 'keep-alive');
|
|
495
|
+
c.header('Access-Control-Allow-Origin', '*');
|
|
496
|
+
c.header('Access-Control-Allow-Headers', 'Cache-Control');
|
|
497
|
+
},
|
|
498
|
+
streamSSE: (eventName?: string, data?: any, id?: string) => {
|
|
499
|
+
let event = '';
|
|
500
|
+
if (eventName) event += `event: ${eventName}\n`;
|
|
501
|
+
if (id) event += `id: ${id}\n`;
|
|
502
|
+
event += `data: ${JSON.stringify(data)}\n\n`;
|
|
503
|
+
|
|
504
|
+
// For Hono, we need to accumulate the response
|
|
505
|
+
if (!(c as any).__sseBuffer) {
|
|
506
|
+
(c as any).__sseBuffer = '';
|
|
507
|
+
}
|
|
508
|
+
(c as any).__sseBuffer += event;
|
|
509
|
+
},
|
|
510
|
+
endStream: () => {
|
|
511
|
+
// Send the accumulated SSE data
|
|
512
|
+
const sseData = (c as any).__sseBuffer || '';
|
|
513
|
+
(c as any).__response = new Response(sseData, {
|
|
514
|
+
headers: {
|
|
515
|
+
'Content-Type': 'text/event-stream',
|
|
516
|
+
'Cache-Control': 'no-cache',
|
|
517
|
+
'Connection': 'keep-alive'
|
|
518
|
+
}
|
|
519
|
+
});
|
|
432
520
|
}
|
|
433
521
|
} as TypedResponse<TDef, typeof currentDomain, typeof currentRouteKey>;
|
|
434
522
|
|
package/src/router.ts
CHANGED
|
@@ -62,6 +62,10 @@ export interface TypedResponse<
|
|
|
62
62
|
respondContentType: (status: number, data: any, contentType: string) => void;
|
|
63
63
|
setHeader: (name: string, value: string) => this;
|
|
64
64
|
json: <B = any>(body: B) => this; // Keep original json
|
|
65
|
+
// SSE streaming methods
|
|
66
|
+
startSSE: () => void;
|
|
67
|
+
streamSSE: (eventName?: string, data?: any, id?: string) => void;
|
|
68
|
+
endStream: () => void;
|
|
65
69
|
}
|
|
66
70
|
|
|
67
71
|
// Type-safe route handler creation function, now generic over TDef and Ctx
|
package/tests/setup.ts
CHANGED
|
@@ -23,6 +23,33 @@ const simplePublicHandlers = {
|
|
|
23
23
|
res.setHeader('X-Custom-Test', 'test-value');
|
|
24
24
|
res.setHeader('X-Another-Header', 'another-value');
|
|
25
25
|
res.respond(200, { message: "headers set" });
|
|
26
|
+
},
|
|
27
|
+
longpoll: async (req: any, res: any) => {
|
|
28
|
+
const sequence = req.params.sequence;
|
|
29
|
+
// Simulate long polling delay based on sequence
|
|
30
|
+
const delay = sequence * 100; // 100ms per sequence number
|
|
31
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
32
|
+
res.respond(200, {
|
|
33
|
+
sequence,
|
|
34
|
+
data: `object ${sequence}`,
|
|
35
|
+
timestamp: Date.now()
|
|
36
|
+
});
|
|
37
|
+
},
|
|
38
|
+
stream: async (req: any, res: any) => {
|
|
39
|
+
// Initialize SSE with proper headers
|
|
40
|
+
res.startSSE();
|
|
41
|
+
|
|
42
|
+
// Send SSE events with JSON data at intervals
|
|
43
|
+
await res.streamSSE('update', { sequence: 1, data: 'object 1' });
|
|
44
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
45
|
+
|
|
46
|
+
await res.streamSSE('update', { sequence: 2, data: 'object 2' });
|
|
47
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
48
|
+
|
|
49
|
+
await res.streamSSE('update', { sequence: 3, data: 'object 3' });
|
|
50
|
+
|
|
51
|
+
// Close the stream
|
|
52
|
+
res.endStream();
|
|
26
53
|
}
|
|
27
54
|
},
|
|
28
55
|
status: {
|
package/tests/simple-api.test.ts
CHANGED
|
@@ -121,6 +121,136 @@ describe.each([
|
|
|
121
121
|
expect(anotherHeader).toBe('another-value');
|
|
122
122
|
});
|
|
123
123
|
|
|
124
|
+
test('should handle long polling with delayed responses', async () => {
|
|
125
|
+
const startTime = Date.now();
|
|
126
|
+
|
|
127
|
+
// Test multiple sequences to simulate intervals
|
|
128
|
+
for (let seq = 1; seq <= 3; seq++) {
|
|
129
|
+
const result = await client.callApi('common', 'longpoll', {
|
|
130
|
+
params: { sequence: seq }
|
|
131
|
+
}, {
|
|
132
|
+
200: ({ data }) => {
|
|
133
|
+
expect(data.sequence).toBe(seq);
|
|
134
|
+
expect(data.data).toBe(`object ${seq}`);
|
|
135
|
+
expect(typeof data.timestamp).toBe('number');
|
|
136
|
+
expect(data.timestamp).toBeGreaterThan(startTime);
|
|
137
|
+
return data;
|
|
138
|
+
},
|
|
139
|
+
422: ({ error }) => {
|
|
140
|
+
throw new Error(`Validation error: ${JSON.stringify(error)}`);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
expect(result.sequence).toBe(seq);
|
|
145
|
+
expect(result.data).toBe(`object ${seq}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Verify that total time is at least the sum of delays (100ms * 1 + 100ms * 2 + 100ms * 3 = 600ms)
|
|
149
|
+
const elapsed = Date.now() - startTime;
|
|
150
|
+
expect(elapsed).toBeGreaterThanOrEqual(600); // Allow some tolerance for test execution
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test('should handle SSE streaming with multiple JSON objects', async () => {
|
|
154
|
+
// Test SSE streaming by making a fetch request and parsing the response
|
|
155
|
+
const response = await fetch(`${baseUrl}/api/v1/public/stream`);
|
|
156
|
+
expect(response.status).toBe(200);
|
|
157
|
+
expect(response.headers.get('content-type')).toBe('text/event-stream');
|
|
158
|
+
|
|
159
|
+
const responseText = await response.text();
|
|
160
|
+
|
|
161
|
+
// Parse SSE events from the response
|
|
162
|
+
const events = responseText.trim().split('\n\n');
|
|
163
|
+
expect(events).toHaveLength(3);
|
|
164
|
+
|
|
165
|
+
// Verify each event
|
|
166
|
+
for (let i = 0; i < events.length; i++) {
|
|
167
|
+
const event = events[i];
|
|
168
|
+
const lines = event.split('\n');
|
|
169
|
+
expect(lines[0]).toBe('event: update');
|
|
170
|
+
|
|
171
|
+
const dataLine = lines.find(line => line.startsWith('data: '));
|
|
172
|
+
expect(dataLine).toBeDefined();
|
|
173
|
+
|
|
174
|
+
const data = JSON.parse(dataLine!.substring(6)); // Remove 'data: ' prefix
|
|
175
|
+
expect(data.sequence).toBe(i + 1);
|
|
176
|
+
expect(data.data).toBe(`object ${i + 1}`);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
test('should handle SSE streaming incrementally', async () => {
|
|
181
|
+
const response = await fetch(`${baseUrl}/api/v1/public/stream`);
|
|
182
|
+
expect(response.status).toBe(200);
|
|
183
|
+
expect(response.headers.get('content-type')).toBe('text/event-stream');
|
|
184
|
+
|
|
185
|
+
return new Promise<void>((resolve, reject) => {
|
|
186
|
+
// node-fetch returns a Node.js stream, cast properly
|
|
187
|
+
const stream = response.body as any; // Node.js Readable stream
|
|
188
|
+
let buffer = '';
|
|
189
|
+
const events: any[] = [];
|
|
190
|
+
|
|
191
|
+
stream.on('data', (chunk: Buffer) => {
|
|
192
|
+
buffer += chunk.toString();
|
|
193
|
+
|
|
194
|
+
// Parse complete SSE events from buffer
|
|
195
|
+
const lines = buffer.split('\n');
|
|
196
|
+
buffer = lines.pop() || ''; // Keep incomplete line in buffer
|
|
197
|
+
|
|
198
|
+
let currentEvent = '';
|
|
199
|
+
for (const line of lines) {
|
|
200
|
+
if (line === '') {
|
|
201
|
+
// Empty line = end of event
|
|
202
|
+
if (currentEvent.trim()) {
|
|
203
|
+
const eventData = parseSSEEvent(currentEvent);
|
|
204
|
+
if (eventData) events.push(eventData);
|
|
205
|
+
}
|
|
206
|
+
currentEvent = '';
|
|
207
|
+
} else {
|
|
208
|
+
currentEvent += line + '\n';
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Check if we have all expected events
|
|
213
|
+
if (events.length >= 3) {
|
|
214
|
+
// For Node.js streams, just remove listeners to "close"
|
|
215
|
+
stream.removeAllListeners('data');
|
|
216
|
+
stream.removeAllListeners('error');
|
|
217
|
+
stream.removeAllListeners('end');
|
|
218
|
+
|
|
219
|
+
try {
|
|
220
|
+
expect(events).toHaveLength(3);
|
|
221
|
+
expect(events[0]).toEqual({ sequence: 1, data: 'object 1' });
|
|
222
|
+
expect(events[1]).toEqual({ sequence: 2, data: 'object 2' });
|
|
223
|
+
expect(events[2]).toEqual({ sequence: 3, data: 'object 3' });
|
|
224
|
+
resolve();
|
|
225
|
+
} catch (error) {
|
|
226
|
+
reject(error);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
stream.on('error', reject);
|
|
232
|
+
stream.on('end', () => {
|
|
233
|
+
// If we get here without 3 events, test failed
|
|
234
|
+
if (events.length < 3) {
|
|
235
|
+
reject(new Error(`Expected 3 events, got ${events.length}`));
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
function parseSSEEvent(eventText: string): any | null {
|
|
242
|
+
const lines = eventText.split('\n');
|
|
243
|
+
let data = '';
|
|
244
|
+
|
|
245
|
+
for (const line of lines) {
|
|
246
|
+
if (line.startsWith('data: ')) {
|
|
247
|
+
data = line.substring(6);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return data ? JSON.parse(data) : null;
|
|
252
|
+
}
|
|
253
|
+
|
|
124
254
|
test('generateUrl should return correct URL for ping', () => {
|
|
125
255
|
const url = client.generateUrl('common', 'ping');
|
|
126
256
|
expect(url).toBe(`${baseUrl}/api/v1/public/ping`);
|