tr-apisrv 0.2.0 → 2.1.0

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/test/test.js CHANGED
@@ -1,3 +1,1204 @@
1
1
  'use strict';
2
- const x = require('../index');
3
- process.exit(0);
2
+
3
+ const { test } = require('node:test');
4
+ const assert = require('node:assert');
5
+ const http = require('http');
6
+ const net = require('net');
7
+ const ApiSrv = require('..');
8
+
9
+ function httpRequest(port, { method = 'GET', path = '/', headers = {}, body } = {}) {
10
+ return new Promise((resolve, reject) => {
11
+ const req = http.request({
12
+ port,
13
+ hostname: '127.0.0.1',
14
+ method,
15
+ path,
16
+ headers
17
+ }, (res) => {
18
+ let data = '';
19
+ res.on('data', (d) => data += d);
20
+ res.on('end', () => resolve({ status: res.statusCode, data, headers: res.headers }));
21
+ });
22
+ req.on('error', reject);
23
+ if (body) {
24
+ req.write(body);
25
+ }
26
+ req.end();
27
+ });
28
+ }
29
+
30
+ function rawRequest(port, raw) {
31
+ return new Promise((resolve, reject) => {
32
+ const socket = net.connect(port, '127.0.0.1');
33
+ let data = '';
34
+ socket.on('connect', () => socket.end(raw));
35
+ socket.on('data', (d) => data += d.toString());
36
+ socket.on('end', () => {
37
+ const m = data.match(/^HTTP\/1\.1\s+(\d+)/);
38
+ resolve(parseInt(m[1], 10));
39
+ });
40
+ socket.on('error', reject);
41
+ });
42
+ }
43
+
44
+ test('handles GET requests', async () => {
45
+ const port = 12350;
46
+ const srv = new ApiSrv({
47
+ port,
48
+ callback: (r) => r.jsonResponse({
49
+ method: r.method,
50
+ params: r.params,
51
+ pathParams: r.pathParams,
52
+ urlParams: r.urlParams,
53
+ bodyParams: r.bodyParams
54
+ })
55
+ });
56
+ try {
57
+ const res = await httpRequest(port, { method: 'GET', path: '/?a=1' });
58
+ assert.strictEqual(res.status, 200);
59
+ assert.deepStrictEqual(JSON.parse(res.data), {
60
+ method: 'GET',
61
+ params: { a: '1' },
62
+ pathParams: {},
63
+ urlParams: { a: '1' },
64
+ bodyParams: {}
65
+ });
66
+ } finally {
67
+ await srv.shutdown();
68
+ }
69
+ });
70
+
71
+ test('handles POST requests', async () => {
72
+ const port = 12351;
73
+ const srv = new ApiSrv({
74
+ port,
75
+ callback: (r) => r.jsonResponse({
76
+ method: r.method,
77
+ params: r.params,
78
+ pathParams: r.pathParams,
79
+ urlParams: r.urlParams,
80
+ bodyParams: r.bodyParams
81
+ })
82
+ });
83
+ try {
84
+ const res = await httpRequest(port, {
85
+ method: 'POST',
86
+ path: '/',
87
+ headers: { 'Content-Type': 'application/json' },
88
+ body: JSON.stringify({ a: 1 })
89
+ });
90
+ assert.strictEqual(res.status, 200);
91
+ assert.deepStrictEqual(JSON.parse(res.data), {
92
+ method: 'POST',
93
+ params: { a: 1 },
94
+ pathParams: {},
95
+ urlParams: {},
96
+ bodyParams: { a: 1 }
97
+ });
98
+ } finally {
99
+ await srv.shutdown();
100
+ }
101
+ });
102
+
103
+ test('handles PUT requests', async () => {
104
+ const port = 12352;
105
+ const srv = new ApiSrv({
106
+ port,
107
+ callback: (r) => r.jsonResponse({
108
+ method: r.method,
109
+ params: r.params,
110
+ pathParams: r.pathParams,
111
+ urlParams: r.urlParams,
112
+ bodyParams: r.bodyParams
113
+ })
114
+ });
115
+ try {
116
+ const res = await httpRequest(port, {
117
+ method: 'PUT',
118
+ path: '/',
119
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
120
+ body: 'a=1'
121
+ });
122
+ assert.strictEqual(res.status, 200);
123
+ assert.deepStrictEqual(JSON.parse(res.data), {
124
+ method: 'PUT',
125
+ params: { a: '1' },
126
+ pathParams: {},
127
+ urlParams: {},
128
+ bodyParams: { a: '1' }
129
+ });
130
+ } finally {
131
+ await srv.shutdown();
132
+ }
133
+ });
134
+
135
+ test('handles DELETE requests', async () => {
136
+ const port = 12353;
137
+ const srv = new ApiSrv({
138
+ port,
139
+ callback: (r) => r.jsonResponse({
140
+ method: r.method,
141
+ params: r.params,
142
+ pathParams: r.pathParams,
143
+ urlParams: r.urlParams,
144
+ bodyParams: r.bodyParams
145
+ })
146
+ });
147
+ try {
148
+ const res = await httpRequest(port, { method: 'DELETE', path: '/?a=1' });
149
+ assert.strictEqual(res.status, 200);
150
+ assert.deepStrictEqual(JSON.parse(res.data), {
151
+ method: 'DELETE',
152
+ params: { a: '1' },
153
+ pathParams: {},
154
+ urlParams: { a: '1' },
155
+ bodyParams: {}
156
+ });
157
+ } finally {
158
+ await srv.shutdown();
159
+ }
160
+ });
161
+
162
+ test('handlers can respond with JSON errors via errorResponse', async () => {
163
+ const port = 12354;
164
+ const srv = new ApiSrv({
165
+ port,
166
+ requestHandlers: {
167
+ POST: {
168
+ '/items': (r) => r.errorResponse(400, 'Input data is too complex')
169
+ },
170
+ GET: {
171
+ '/items': (r) => r.errorResponse(404)
172
+ }
173
+ }
174
+ });
175
+ try {
176
+ const invalid = await httpRequest(port, {
177
+ method: 'POST',
178
+ path: '/items',
179
+ headers: { 'Content-Type': 'application/json' },
180
+ body: '{}'
181
+ });
182
+ assert.strictEqual(invalid.status, 400);
183
+ const invalidBody = JSON.parse(invalid.data);
184
+ assert.strictEqual(invalidBody.code, 400);
185
+ assert.strictEqual(invalidBody.message, 'Bad Request (Input data is too complex)');
186
+
187
+ const missing = await httpRequest(port, { method: 'GET', path: '/items' });
188
+ assert.strictEqual(missing.status, 404);
189
+ const missingBody = JSON.parse(missing.data);
190
+ assert.strictEqual(missingBody.code, 404);
191
+ assert.strictEqual(missingBody.message, 'Not Found');
192
+ } finally {
193
+ await srv.shutdown();
194
+ }
195
+ });
196
+
197
+ test('requestHandlers take precedence over callback', async () => {
198
+ const port = 12361;
199
+ const srv = new ApiSrv({
200
+ port,
201
+ callback: (r) => r.jsonResponse({ handled: 'callback' }),
202
+ requestHandlers: {
203
+ GET: {
204
+ '/': (r) => r.jsonResponse({ handled: 'requestHandlers' })
205
+ }
206
+ }
207
+ });
208
+ try {
209
+ const res = await httpRequest(port, { method: 'GET', path: '/' });
210
+ assert.strictEqual(res.status, 200);
211
+ assert.deepStrictEqual(JSON.parse(res.data), { handled: 'requestHandlers' });
212
+ } finally {
213
+ await srv.shutdown();
214
+ }
215
+ });
216
+
217
+ test('requestHandlers support path templates', async (t) => {
218
+ const port = 12362;
219
+ const warnings = [];
220
+ const warnMock = t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
221
+ const srv = new ApiSrv({
222
+ port,
223
+ callback: (r) => r.jsonResponse({ handled: 'callback' }),
224
+ requestHandlers: {
225
+ GET: {
226
+ '/user/{userId}': (r) => r.jsonResponse({
227
+ handled: 'requestHandlers',
228
+ params: r.params,
229
+ pathParams: r.pathParams,
230
+ urlParams: r.urlParams,
231
+ bodyParams: r.bodyParams
232
+ })
233
+ }
234
+ }
235
+ });
236
+ try {
237
+ const res = await httpRequest(port, { method: 'GET', path: '/user/123?foo=bar&userId=query' });
238
+ assert.strictEqual(res.status, 200);
239
+ assert.deepStrictEqual(JSON.parse(res.data), {
240
+ handled: 'requestHandlers',
241
+ params: { foo: 'bar', userId: '123' },
242
+ pathParams: { userId: '123' },
243
+ urlParams: { foo: 'bar', userId: 'query' },
244
+ bodyParams: {}
245
+ });
246
+ assert.strictEqual(warnings.length, 1);
247
+ assert.match(warnings[0], /userId/);
248
+ assert.match(warnings[0], /query string/);
249
+ } finally {
250
+ t.mock.restoreAll();
251
+ await srv.shutdown();
252
+ }
253
+ });
254
+
255
+ test('requestHandlers match trailing slash when template omits it', async () => {
256
+ const port = 12370;
257
+ const srv = new ApiSrv({
258
+ port,
259
+ requestHandlers: {
260
+ GET: {
261
+ '/slashless': (r) => r.jsonResponse({ handled: 'slashless', path: r.url })
262
+ }
263
+ }
264
+ });
265
+ try {
266
+ let res = await httpRequest(port, { method: 'GET', path: '/slashless' });
267
+ assert.strictEqual(res.status, 200);
268
+ assert.deepStrictEqual(JSON.parse(res.data), { handled: 'slashless', path: '/slashless' });
269
+
270
+ res = await httpRequest(port, { method: 'GET', path: '/slashless/' });
271
+ assert.strictEqual(res.status, 200);
272
+ assert.deepStrictEqual(JSON.parse(res.data), { handled: 'slashless', path: '/slashless/' });
273
+ } finally {
274
+ await srv.shutdown();
275
+ }
276
+ });
277
+
278
+ test('requestHandlers require trailing slash when template includes it', async () => {
279
+ const port = 12371;
280
+ const srv = new ApiSrv({
281
+ port,
282
+ requestHandlers: {
283
+ GET: {
284
+ '/needs-slash/': (r) => r.jsonResponse({ handled: 'needs-slash' })
285
+ }
286
+ }
287
+ });
288
+ try {
289
+ const withSlash = await httpRequest(port, { method: 'GET', path: '/needs-slash/' });
290
+ assert.strictEqual(withSlash.status, 200);
291
+ assert.deepStrictEqual(JSON.parse(withSlash.data), { handled: 'needs-slash' });
292
+
293
+ const withoutSlash = await httpRequest(port, { method: 'GET', path: '/needs-slash' });
294
+ assert.strictEqual(withoutSlash.status, 404);
295
+ const body = JSON.parse(withoutSlash.data);
296
+ assert.strictEqual(body.code, 404);
297
+ assert.strictEqual(body.message, 'Not Found');
298
+ } finally {
299
+ await srv.shutdown();
300
+ }
301
+ });
302
+
303
+ test('dynamic template without trailing slash matches both forms', async () => {
304
+ const port = 12372;
305
+ const srv = new ApiSrv({
306
+ port,
307
+ requestHandlers: {
308
+ GET: {
309
+ '/user/{userId}': (r) => r.jsonResponse({
310
+ params: r.params,
311
+ pathParams: r.pathParams,
312
+ urlParams: r.urlParams,
313
+ bodyParams: r.bodyParams
314
+ })
315
+ }
316
+ }
317
+ });
318
+ try {
319
+ let res = await httpRequest(port, { method: 'GET', path: '/user/abc' });
320
+ assert.strictEqual(res.status, 200);
321
+ assert.deepStrictEqual(JSON.parse(res.data), {
322
+ params: { userId: 'abc' },
323
+ pathParams: { userId: 'abc' },
324
+ urlParams: {},
325
+ bodyParams: {}
326
+ });
327
+
328
+ res = await httpRequest(port, { method: 'GET', path: '/user/abc/' });
329
+ assert.strictEqual(res.status, 200);
330
+ assert.deepStrictEqual(JSON.parse(res.data), {
331
+ params: { userId: 'abc' },
332
+ pathParams: { userId: 'abc' },
333
+ urlParams: {},
334
+ bodyParams: {}
335
+ });
336
+ } finally {
337
+ await srv.shutdown();
338
+ }
339
+ });
340
+
341
+ test('dynamic template with trailing slash requires trailing slash in request', async () => {
342
+ const port = 12373;
343
+ const srv = new ApiSrv({
344
+ port,
345
+ requestHandlers: {
346
+ GET: {
347
+ '/user/{userId}/': (r) => r.jsonResponse({ params: r.params })
348
+ }
349
+ }
350
+ });
351
+ try {
352
+ const withSlash = await httpRequest(port, { method: 'GET', path: '/user/abc/' });
353
+ assert.strictEqual(withSlash.status, 200);
354
+ assert.deepStrictEqual(JSON.parse(withSlash.data), { params: { userId: 'abc' } });
355
+
356
+ const withoutSlash = await httpRequest(port, { method: 'GET', path: '/user/abc' });
357
+ assert.strictEqual(withoutSlash.status, 404);
358
+ const body = JSON.parse(withoutSlash.data);
359
+ assert.strictEqual(body.code, 404);
360
+ assert.strictEqual(body.message, 'Not Found');
361
+ } finally {
362
+ await srv.shutdown();
363
+ }
364
+ });
365
+
366
+ test('requestHandlers reject invalid path parameter names', () => {
367
+ assert.throws(() => {
368
+ new ApiSrv({
369
+ port: 12394,
370
+ requestHandlers: {
371
+ GET: {
372
+ '/users/{1bad}': () => {}
373
+ }
374
+ }
375
+ });
376
+ }, /Invalid path parameter name/);
377
+
378
+ assert.throws(() => {
379
+ new ApiSrv({
380
+ port: 12395,
381
+ requestHandlers: {
382
+ GET: {
383
+ '/files/[bad-name]': () => {}
384
+ }
385
+ }
386
+ });
387
+ }, /Invalid path parameter name|Invalid path parameter segment/);
388
+ });
389
+
390
+ test('requestHandlers reject invalid array constraints', () => {
391
+ assert.throws(() => {
392
+ new ApiSrv({
393
+ port: 12396,
394
+ requestHandlers: {
395
+ GET: {
396
+ '/files/[segments:0]': () => {}
397
+ }
398
+ }
399
+ });
400
+ }, /Invalid minimum length/);
401
+
402
+ assert.throws(() => {
403
+ new ApiSrv({
404
+ port: 12397,
405
+ requestHandlers: {
406
+ GET: {
407
+ '/files/[segments:5:2]': () => {}
408
+ }
409
+ }
410
+ });
411
+ }, /Invalid length range/);
412
+
413
+ assert.throws(() => {
414
+ new ApiSrv({
415
+ port: 12398,
416
+ requestHandlers: {
417
+ GET: {
418
+ '/files/[segments:4:four]': () => {}
419
+ }
420
+ }
421
+ });
422
+ }, /Invalid path parameter segment/);
423
+ });
424
+
425
+ test('falls back to callback when requestHandlers do not match', async () => {
426
+ const port = 12363;
427
+ const srv = new ApiSrv({
428
+ port,
429
+ callback: (r) => r.jsonResponse({ handled: 'callback' }),
430
+ requestHandlers: {
431
+ GET: {
432
+ '/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
433
+ }
434
+ }
435
+ });
436
+ try {
437
+ const res = await httpRequest(port, { method: 'GET', path: '/' });
438
+ assert.strictEqual(res.status, 200);
439
+ assert.deepStrictEqual(JSON.parse(res.data), { handled: 'callback' });
440
+ } finally {
441
+ await srv.shutdown();
442
+ }
443
+ });
444
+
445
+ test('request handler definition objects apply validators', async () => {
446
+ const port = 12376;
447
+ const srv = new ApiSrv({
448
+ port,
449
+ requestHandlers: {
450
+ GET: {
451
+ '/validate/{userId}': {
452
+ callback: (r) => r.jsonResponse({
453
+ params: r.params,
454
+ pathParams: r.pathParams,
455
+ urlParams: r.urlParams
456
+ }),
457
+ options: {
458
+ pathParamsValidator: (pathParams) => ({ userId: Number(pathParams.userId) }),
459
+ urlParamsValidator: async (urlParams) => ({ limit: Number(urlParams.limit) }),
460
+ paramsValidator: async (params) => ({ ...params, validated: true })
461
+ }
462
+ }
463
+ }
464
+ }
465
+ });
466
+ try {
467
+ const res = await httpRequest(port, { method: 'GET', path: '/validate/42?limit=5' });
468
+ assert.strictEqual(res.status, 200);
469
+ assert.deepStrictEqual(JSON.parse(res.data), {
470
+ params: { limit: 5, userId: 42, validated: true },
471
+ pathParams: { userId: 42 },
472
+ urlParams: { limit: 5 }
473
+ });
474
+ } finally {
475
+ await srv.shutdown();
476
+ }
477
+ });
478
+
479
+ test('requestHandlers capture array segments with [variable]', async () => {
480
+ const port = 12367;
481
+ const srv = new ApiSrv({
482
+ port,
483
+ requestHandlers: {
484
+ GET: {
485
+ '/files/[pathParts]': (r) => r.jsonResponse({ params: r.params, pathParams: r.pathParams })
486
+ }
487
+ }
488
+ });
489
+ try {
490
+ const res = await httpRequest(port, { method: 'GET', path: '/files/foo/bar/baz' });
491
+ assert.strictEqual(res.status, 200);
492
+ assert.deepStrictEqual(JSON.parse(res.data), {
493
+ params: { pathParts: ['foo', 'bar', 'baz'] },
494
+ pathParams: { pathParts: ['foo', 'bar', 'baz'] }
495
+ });
496
+ } finally {
497
+ await srv.shutdown();
498
+ }
499
+ });
500
+
501
+ test('requestHandlers capture [variable] segments in the middle of a template', async () => {
502
+ const port = 12368;
503
+ const srv = new ApiSrv({
504
+ port,
505
+ requestHandlers: {
506
+ GET: {
507
+ '/{cmd}/[zap]/{bar}/{pup}': (r) => r.jsonResponse({ params: r.params, pathParams: r.pathParams })
508
+ }
509
+ }
510
+ });
511
+ try {
512
+ const res = await httpRequest(port, { method: 'GET', path: '/do/one/two/three/four' });
513
+ assert.strictEqual(res.status, 200);
514
+ assert.deepStrictEqual(JSON.parse(res.data), {
515
+ params: {
516
+ cmd: 'do',
517
+ zap: ['one', 'two'],
518
+ bar: 'three',
519
+ pup: 'four'
520
+ },
521
+ pathParams: {
522
+ cmd: 'do',
523
+ zap: ['one', 'two'],
524
+ bar: 'three',
525
+ pup: 'four'
526
+ }
527
+ });
528
+ } finally {
529
+ await srv.shutdown();
530
+ }
531
+ });
532
+
533
+ test('array path parameter enforces default length constraints', async () => {
534
+ const port = 12390;
535
+ const srv = new ApiSrv({
536
+ port,
537
+ requestHandlers: {
538
+ GET: {
539
+ '/files/[segments]': (r) => r.jsonResponse({ pathParams: r.pathParams })
540
+ }
541
+ }
542
+ });
543
+ const exactly32 = Array.from({ length: 32 }, (_, i) => `part${i}`);
544
+ const tooMany = Array.from({ length: 33 }, (_, i) => `part${i}`);
545
+ try {
546
+ const within = await httpRequest(port, { method: 'GET', path: `/files/${exactly32.join('/')}` });
547
+ assert.strictEqual(within.status, 200);
548
+ const parsedWithin = JSON.parse(within.data);
549
+ assert.deepStrictEqual(parsedWithin.pathParams.segments, exactly32);
550
+
551
+ const overLimit = await httpRequest(port, { method: 'GET', path: `/files/${tooMany.join('/')}` });
552
+ assert.strictEqual(overLimit.status, 404);
553
+ const body = JSON.parse(overLimit.data);
554
+ assert.strictEqual(body.code, 404);
555
+ assert.strictEqual(body.message, 'Not Found');
556
+ } finally {
557
+ await srv.shutdown();
558
+ }
559
+ });
560
+
561
+ test('array path parameter enforces exact length constraint', async () => {
562
+ const port = 12391;
563
+ const srv = new ApiSrv({
564
+ port,
565
+ requestHandlers: {
566
+ GET: {
567
+ '/files/[segments:4]': (r) => r.jsonResponse({ pathParams: r.pathParams })
568
+ }
569
+ }
570
+ });
571
+ const exactlyFour = Array.from({ length: 4 }, (_, i) => `p${i}`);
572
+ const three = exactlyFour.slice(0, 3);
573
+ const five = [...exactlyFour, 'extra'];
574
+ try {
575
+ const exact = await httpRequest(port, { method: 'GET', path: `/files/${exactlyFour.join('/')}` });
576
+ assert.strictEqual(exact.status, 200);
577
+ const parsedExact = JSON.parse(exact.data);
578
+ assert.deepStrictEqual(parsedExact.pathParams.segments, exactlyFour);
579
+
580
+ const tooFew = await httpRequest(port, { method: 'GET', path: `/files/${three.join('/')}` });
581
+ assert.strictEqual(tooFew.status, 404);
582
+ const bodyFew = JSON.parse(tooFew.data);
583
+ assert.strictEqual(bodyFew.code, 404);
584
+ assert.strictEqual(bodyFew.message, 'Not Found');
585
+
586
+ const tooMany = await httpRequest(port, { method: 'GET', path: `/files/${five.join('/')}` });
587
+ assert.strictEqual(tooMany.status, 404);
588
+ const bodyMany = JSON.parse(tooMany.data);
589
+ assert.strictEqual(bodyMany.code, 404);
590
+ assert.strictEqual(bodyMany.message, 'Not Found');
591
+ } finally {
592
+ await srv.shutdown();
593
+ }
594
+ });
595
+
596
+ test('array path parameter enforces min and max constraints', async () => {
597
+ const port = 12392;
598
+ const srv = new ApiSrv({
599
+ port,
600
+ requestHandlers: {
601
+ GET: {
602
+ '/files/[segments:2:4]': (r) => r.jsonResponse({ pathParams: r.pathParams })
603
+ }
604
+ }
605
+ });
606
+ const two = ['a', 'b'];
607
+ const four = ['a', 'b', 'c', 'd'];
608
+ try {
609
+ const minOk = await httpRequest(port, { method: 'GET', path: `/files/${two.join('/')}` });
610
+ assert.strictEqual(minOk.status, 200);
611
+ const parsedMin = JSON.parse(minOk.data);
612
+ assert.deepStrictEqual(parsedMin.pathParams.segments, two);
613
+
614
+ const maxOk = await httpRequest(port, { method: 'GET', path: `/files/${four.join('/')}` });
615
+ assert.strictEqual(maxOk.status, 200);
616
+ const parsedMax = JSON.parse(maxOk.data);
617
+ assert.deepStrictEqual(parsedMax.pathParams.segments, four);
618
+
619
+ const tooFew = await httpRequest(port, { method: 'GET', path: '/files/a' });
620
+ assert.strictEqual(tooFew.status, 404);
621
+ const bodyFew = JSON.parse(tooFew.data);
622
+ assert.strictEqual(bodyFew.code, 404);
623
+ assert.strictEqual(bodyFew.message, 'Not Found');
624
+
625
+ const tooMany = await httpRequest(port, { method: 'GET', path: '/files/a/b/c/d/e' });
626
+ assert.strictEqual(tooMany.status, 404);
627
+ const bodyMany = JSON.parse(tooMany.data);
628
+ assert.strictEqual(bodyMany.code, 404);
629
+ assert.strictEqual(bodyMany.message, 'Not Found');
630
+ } finally {
631
+ await srv.shutdown();
632
+ }
633
+ });
634
+
635
+ test('array path parameter allows raising the default maximum', async () => {
636
+ const port = 12393;
637
+ const srv = new ApiSrv({
638
+ port,
639
+ requestHandlers: {
640
+ GET: {
641
+ '/files/[segments:10:50]': (r) => r.jsonResponse({ pathParams: r.pathParams })
642
+ }
643
+ }
644
+ });
645
+ const ten = Array.from({ length: 10 }, (_, i) => `s${i}`);
646
+ const forty = Array.from({ length: 40 }, (_, i) => `s${i}`);
647
+ const nine = ten.slice(0, 9);
648
+ const fiftyOne = Array.from({ length: 51 }, (_, i) => `s${i}`);
649
+ try {
650
+ const minOk = await httpRequest(port, { method: 'GET', path: `/files/${ten.join('/')}` });
651
+ assert.strictEqual(minOk.status, 200);
652
+ const parsedMin = JSON.parse(minOk.data);
653
+ assert.deepStrictEqual(parsedMin.pathParams.segments, ten);
654
+
655
+ const extended = await httpRequest(port, { method: 'GET', path: `/files/${forty.join('/')}` });
656
+ assert.strictEqual(extended.status, 200);
657
+ const parsedExtended = JSON.parse(extended.data);
658
+ assert.deepStrictEqual(parsedExtended.pathParams.segments, forty);
659
+
660
+ const belowMin = await httpRequest(port, { method: 'GET', path: `/files/${nine.join('/')}` });
661
+ assert.strictEqual(belowMin.status, 404);
662
+ const bodyLow = JSON.parse(belowMin.data);
663
+ assert.strictEqual(bodyLow.code, 404);
664
+ assert.strictEqual(bodyLow.message, 'Not Found');
665
+
666
+ const aboveMax = await httpRequest(port, { method: 'GET', path: `/files/${fiftyOne.join('/')}` });
667
+ assert.strictEqual(aboveMax.status, 404);
668
+ const bodyHigh = JSON.parse(aboveMax.data);
669
+ assert.strictEqual(bodyHigh.code, 404);
670
+ assert.strictEqual(bodyHigh.message, 'Not Found');
671
+ } finally {
672
+ await srv.shutdown();
673
+ }
674
+ });
675
+
676
+ test('ignoreUrlParams prevents query parsing', async () => {
677
+ const port = 12377;
678
+ let urlValidatorCalled = false;
679
+ const srv = new ApiSrv({
680
+ port,
681
+ requestHandlers: {
682
+ GET: {
683
+ '/items/{itemId}': {
684
+ callback: (r) => r.jsonResponse({
685
+ params: r.params,
686
+ pathParams: r.pathParams,
687
+ hasUrlParams: Object.prototype.hasOwnProperty.call(r, 'urlParams')
688
+ }),
689
+ options: {
690
+ ignoreUrlParams: true,
691
+ urlParamsValidator: () => {
692
+ urlValidatorCalled = true;
693
+ return {};
694
+ }
695
+ }
696
+ }
697
+ }
698
+ }
699
+ });
700
+ try {
701
+ const res = await httpRequest(port, { method: 'GET', path: '/items/abc?foo=bar' });
702
+ assert.strictEqual(res.status, 200);
703
+ assert.deepStrictEqual(JSON.parse(res.data), {
704
+ params: { itemId: 'abc' },
705
+ pathParams: { itemId: 'abc' },
706
+ hasUrlParams: false
707
+ });
708
+ assert.strictEqual(urlValidatorCalled, false);
709
+ } finally {
710
+ await srv.shutdown();
711
+ }
712
+ });
713
+
714
+ test('path parameters override body parameters with warning', async (t) => {
715
+ const port = 12369;
716
+ const warnings = [];
717
+ const warnMock = t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
718
+ const srv = new ApiSrv({
719
+ port,
720
+ requestHandlers: {
721
+ POST: {
722
+ '/user/{userId}': (r) => r.jsonResponse({
723
+ params: r.params,
724
+ pathParams: r.pathParams,
725
+ urlParams: r.urlParams,
726
+ bodyParams: r.bodyParams
727
+ })
728
+ }
729
+ }
730
+ });
731
+ try {
732
+ const res = await httpRequest(port, {
733
+ method: 'POST',
734
+ path: '/user/123',
735
+ headers: { 'Content-Type': 'application/json' },
736
+ body: JSON.stringify({ userId: 'fromBody', name: 'alice' })
737
+ });
738
+ assert.strictEqual(res.status, 200);
739
+ assert.deepStrictEqual(JSON.parse(res.data), {
740
+ params: { userId: '123', name: 'alice' },
741
+ pathParams: { userId: '123' },
742
+ urlParams: {},
743
+ bodyParams: { userId: 'fromBody', name: 'alice' }
744
+ });
745
+ assert.strictEqual(warnings.length, 1);
746
+ assert.match(warnings[0], /userId/);
747
+ assert.match(warnings[0], /request body/);
748
+ } finally {
749
+ t.mock.restoreAll();
750
+ await srv.shutdown();
751
+ }
752
+ });
753
+
754
+ test('returns 404 when no handler matches and callback missing', async () => {
755
+ const port = 12364;
756
+ const srv = new ApiSrv({
757
+ port,
758
+ requestHandlers: {
759
+ GET: {
760
+ '/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
761
+ }
762
+ }
763
+ });
764
+ try {
765
+ const res = await httpRequest(port, { method: 'GET', path: '/bar' });
766
+ assert.strictEqual(res.status, 404);
767
+ assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
768
+ const body = JSON.parse(res.data);
769
+ assert.strictEqual(body.code, 404);
770
+ assert.strictEqual(body.message, 'Not Found');
771
+ } finally {
772
+ await srv.shutdown();
773
+ }
774
+ });
775
+
776
+ test('returns 405 when path matches other method and callback missing', async () => {
777
+ const port = 12365;
778
+ const srv = new ApiSrv({
779
+ port,
780
+ requestHandlers: {
781
+ GET: {
782
+ '/foo': (r) => r.jsonResponse({ handled: 'requestHandlers' })
783
+ }
784
+ }
785
+ });
786
+ try {
787
+ const res = await httpRequest(port, {
788
+ method: 'POST',
789
+ path: '/foo',
790
+ headers: { 'Content-Type': 'application/json' },
791
+ body: JSON.stringify({})
792
+ });
793
+ assert.strictEqual(res.status, 405);
794
+ assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
795
+ const body = JSON.parse(res.data);
796
+ assert.strictEqual(body.code, 405);
797
+ assert.strictEqual(body.message, 'Method Not Allowed');
798
+ } finally {
799
+ await srv.shutdown();
800
+ }
801
+ });
802
+
803
+ test('rejects dangerous paths by default', async () => {
804
+ const port = 12367;
805
+ let handled = 0;
806
+ const srv = new ApiSrv({
807
+ port,
808
+ callback: (r) => {
809
+ handled++;
810
+ r.jsonResponse({ ok: true });
811
+ }
812
+ });
813
+ try {
814
+ const cases = [
815
+ { path: '/foo//bar', message: 'Bad Request (empty path segment)' },
816
+ { path: '/foo/./bar', message: 'Bad Request (dangerous path segment ".")' },
817
+ { path: '/foo/../bar', message: 'Bad Request (dangerous path segment "..")' }
818
+ ];
819
+ for (const { path, message } of cases) {
820
+ const res = await httpRequest(port, { method: 'GET', path });
821
+ assert.strictEqual(res.status, 400);
822
+ assert.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8');
823
+ const body = JSON.parse(res.data);
824
+ assert.strictEqual(body.code, 400);
825
+ assert.strictEqual(body.message, message);
826
+ }
827
+ assert.strictEqual(handled, 0);
828
+ } finally {
829
+ await srv.shutdown();
830
+ }
831
+ });
832
+
833
+ test('dangerous path rejection can be disabled', async () => {
834
+ const port = 12368;
835
+ let handled = 0;
836
+ const srv = new ApiSrv({
837
+ port,
838
+ rejectDangerousPaths: false,
839
+ callback: (r) => {
840
+ handled++;
841
+ r.jsonResponse({ url: r.url });
842
+ }
843
+ });
844
+ try {
845
+ const res = await httpRequest(port, { method: 'GET', path: '/foo//bar' });
846
+ assert.strictEqual(res.status, 200);
847
+ assert.deepStrictEqual(JSON.parse(res.data), { url: '/foo//bar' });
848
+ assert.strictEqual(handled, 1);
849
+ } finally {
850
+ await srv.shutdown();
851
+ }
852
+ });
853
+
854
+ test('requestHandleAdd and requestHandleDelete modify handlers at runtime', async () => {
855
+ const port = 12366;
856
+ const srv = new ApiSrv({ port });
857
+ srv.requestHandleAdd('GET', '/dynamic', (r) => r.jsonResponse({ method: r.method }));
858
+ srv.requestHandleAdd('POST', '/dynamic', (r) => r.jsonResponse({ method: r.method }));
859
+ try {
860
+ let res = await httpRequest(port, { method: 'GET', path: '/dynamic' });
861
+ assert.strictEqual(res.status, 200);
862
+ assert.deepStrictEqual(JSON.parse(res.data), { method: 'GET' });
863
+
864
+ res = await httpRequest(port, {
865
+ method: 'POST',
866
+ path: '/dynamic',
867
+ headers: { 'Content-Type': 'application/json' },
868
+ body: JSON.stringify({})
869
+ });
870
+ assert.strictEqual(res.status, 200);
871
+ assert.deepStrictEqual(JSON.parse(res.data), { method: 'POST' });
872
+
873
+ srv.requestHandleDelete('GET', '/dynamic');
874
+ res = await httpRequest(port, { method: 'GET', path: '/dynamic' });
875
+ assert.strictEqual(res.status, 405);
876
+ let body = JSON.parse(res.data);
877
+ assert.strictEqual(body.code, 405);
878
+ assert.strictEqual(body.message, 'Method Not Allowed');
879
+
880
+ srv.requestHandleDelete('*', '/dynamic');
881
+ res = await httpRequest(port, {
882
+ method: 'POST',
883
+ path: '/dynamic',
884
+ headers: { 'Content-Type': 'application/json' },
885
+ body: JSON.stringify({})
886
+ });
887
+ assert.strictEqual(res.status, 404);
888
+ body = JSON.parse(res.data);
889
+ assert.strictEqual(body.code, 404);
890
+ assert.strictEqual(body.message, 'Not Found');
891
+ } finally {
892
+ await srv.shutdown();
893
+ }
894
+ });
895
+
896
+ test('requestHandleAdd supports validator options', async () => {
897
+ const port = 12378;
898
+ const srv = new ApiSrv({ port });
899
+ srv.requestHandleAdd('POST', '/items/{itemId}', (r) => r.jsonResponse({
900
+ params: r.params,
901
+ pathParams: r.pathParams,
902
+ bodyParams: r.bodyParams,
903
+ urlParams: r.urlParams
904
+ }), {
905
+ pathParamsValidator: (pathParams) => ({ itemId: Number(pathParams.itemId) }),
906
+ bodyParamsValidator: async (bodyParams) => ({
907
+ name: bodyParams.name.toUpperCase(),
908
+ count: Number(bodyParams.count)
909
+ }),
910
+ paramsValidator: (params) => ({ ...params, validated: true })
911
+ });
912
+ try {
913
+ const res = await httpRequest(port, {
914
+ method: 'POST',
915
+ path: '/items/5',
916
+ headers: { 'Content-Type': 'application/json' },
917
+ body: JSON.stringify({ name: 'foo', count: '3' })
918
+ });
919
+ assert.strictEqual(res.status, 200);
920
+ assert.deepStrictEqual(JSON.parse(res.data), {
921
+ params: { name: 'FOO', count: 3, itemId: 5, validated: true },
922
+ pathParams: { itemId: 5 },
923
+ bodyParams: { name: 'FOO', count: 3 },
924
+ urlParams: {}
925
+ });
926
+ } finally {
927
+ await srv.shutdown();
928
+ }
929
+ });
930
+
931
+ test('requestHandleAdd enforces path template constraints', async () => {
932
+ const port = 12399;
933
+ const srv = new ApiSrv({ port });
934
+ try {
935
+ assert.throws(() => {
936
+ srv.requestHandleAdd('GET', '/bad/{1foo}', () => {});
937
+ }, /Invalid path parameter name/);
938
+
939
+ assert.throws(() => {
940
+ srv.requestHandleAdd('GET', '/bad/[parts:0]', () => {});
941
+ }, /Invalid minimum length/);
942
+ } finally {
943
+ await srv.shutdown();
944
+ }
945
+ });
946
+
947
+ test('authentication runs before parameter parsing', async () => {
948
+ const port = 12379;
949
+ let authSnapshot;
950
+ let handlerSnapshot;
951
+ const srv = new ApiSrv({
952
+ port,
953
+ requestHandlers: {
954
+ POST: {
955
+ '/items/{itemId}': {
956
+ callback: (r) => {
957
+ const normalizedPath = r.pathParams === undefined ? undefined : { ...r.pathParams };
958
+ const normalizedUrl = r.urlParams === undefined ? undefined : { ...r.urlParams };
959
+ handlerSnapshot = {
960
+ bodyParams: r.bodyParams,
961
+ pathParams: normalizedPath,
962
+ urlParams: normalizedUrl,
963
+ params: r.params
964
+ };
965
+ r.jsonResponse({ ok: true });
966
+ }
967
+ }
968
+ }
969
+ },
970
+ authCallback: (r) => {
971
+ authSnapshot = {
972
+ bodyParams: r.bodyParams,
973
+ pathParams: r.pathParams,
974
+ urlParams: r.urlParams,
975
+ params: r.params
976
+ };
977
+ return true;
978
+ }
979
+ });
980
+ try {
981
+ const res = await httpRequest(port, {
982
+ method: 'POST',
983
+ path: '/items/10',
984
+ headers: { 'Content-Type': 'application/json' },
985
+ body: JSON.stringify({ name: 'foo' })
986
+ });
987
+ assert.strictEqual(res.status, 200);
988
+ assert.deepStrictEqual(authSnapshot, {
989
+ bodyParams: undefined,
990
+ pathParams: undefined,
991
+ urlParams: undefined,
992
+ params: undefined
993
+ });
994
+ assert.deepStrictEqual(handlerSnapshot, {
995
+ bodyParams: { name: 'foo' },
996
+ pathParams: { itemId: '10' },
997
+ urlParams: {},
998
+ params: { name: 'foo', itemId: '10' }
999
+ });
1000
+ } finally {
1001
+ await srv.shutdown();
1002
+ }
1003
+ });
1004
+
1005
+ test('authentication failure skips parameter parsing', async () => {
1006
+ const port = 12380;
1007
+ let authCalls = 0;
1008
+ let authSnapshot;
1009
+ const srv = new ApiSrv({
1010
+ port,
1011
+ requestHandlers: {
1012
+ POST: {
1013
+ '/items': {
1014
+ callback: () => {
1015
+ throw new Error('handler must not be invoked');
1016
+ }
1017
+ }
1018
+ }
1019
+ },
1020
+ authCallback: (r) => {
1021
+ authCalls++;
1022
+ authSnapshot = {
1023
+ bodyParams: r.bodyParams,
1024
+ pathParams: r.pathParams,
1025
+ urlParams: r.urlParams,
1026
+ params: r.params
1027
+ };
1028
+ r.res.writeHead(401, { 'Content-Type': 'text/plain' });
1029
+ r.res.end('unauthorized');
1030
+ return false;
1031
+ }
1032
+ });
1033
+ try {
1034
+ const res = await httpRequest(port, {
1035
+ method: 'POST',
1036
+ path: '/items',
1037
+ headers: { 'Content-Type': 'application/json' },
1038
+ body: '{'
1039
+ });
1040
+ assert.strictEqual(res.status, 401);
1041
+ assert.strictEqual(res.data, 'unauthorized');
1042
+ assert.strictEqual(authCalls, 1);
1043
+ assert.deepStrictEqual(authSnapshot, {
1044
+ bodyParams: undefined,
1045
+ pathParams: undefined,
1046
+ urlParams: undefined,
1047
+ params: undefined
1048
+ });
1049
+ } finally {
1050
+ await srv.shutdown();
1051
+ }
1052
+ });
1053
+
1054
+ test('authentication callback controls access', async () => {
1055
+ const port = 12354;
1056
+ let handled = 0;
1057
+ let authCalls = 0;
1058
+ const srv = new ApiSrv({
1059
+ port,
1060
+ callback: (r) => {
1061
+ handled++;
1062
+ r.jsonResponse({ ok: true });
1063
+ },
1064
+ authCallback: (r) => {
1065
+ authCalls++;
1066
+ return r.url !== '/deny';
1067
+ }
1068
+ });
1069
+ try {
1070
+ const okRes = await httpRequest(port, { method: 'GET', path: '/allow' });
1071
+ assert.strictEqual(okRes.status, 200);
1072
+ assert.strictEqual(handled, 1);
1073
+ assert.strictEqual(authCalls, 1);
1074
+
1075
+ const unauthorized = new Promise((resolve, reject) => {
1076
+ const req = http.request({ port, hostname: '127.0.0.1', method: 'GET', path: '/deny' });
1077
+ req.on('response', (res) => {
1078
+ res.resume();
1079
+ res.on('end', resolve);
1080
+ });
1081
+ req.on('error', reject);
1082
+ req.end();
1083
+ setTimeout(() => req.destroy(), 50);
1084
+ });
1085
+ await assert.rejects(unauthorized);
1086
+ assert.strictEqual(handled, 1);
1087
+ assert.strictEqual(authCalls, 2);
1088
+ } finally {
1089
+ await srv.shutdown();
1090
+ }
1091
+ });
1092
+
1093
+ test('body read timeout returns 408', async () => {
1094
+ const port = 12355;
1095
+ const srv = new ApiSrv({
1096
+ port,
1097
+ bodyReadTimeoutMs: 50,
1098
+ callback: () => {}
1099
+ });
1100
+ try {
1101
+ const res = await new Promise((resolve, reject) => {
1102
+ const req = http.request({
1103
+ port,
1104
+ method: 'POST',
1105
+ path: '/',
1106
+ hostname: '127.0.0.1'
1107
+ }, (res) => {
1108
+ let data = '';
1109
+ res.on('data', (d) => data += d);
1110
+ res.on('end', () => resolve({ status: res.statusCode, data }));
1111
+ });
1112
+ req.on('error', reject);
1113
+ req.write('123'); // intentionally never calling end to trigger timeout
1114
+ });
1115
+ assert.strictEqual(res.status, 408);
1116
+ const body = JSON.parse(res.data);
1117
+ assert.strictEqual(body.code, 408);
1118
+ assert.strictEqual(body.message, 'Request Timeout');
1119
+ } finally {
1120
+ await srv.shutdown();
1121
+ }
1122
+ });
1123
+
1124
+ test('shutdown stops listening', async () => {
1125
+ const port = 12356;
1126
+ const srv = new ApiSrv({
1127
+ port,
1128
+ callback: () => {}
1129
+ });
1130
+ await new Promise((resolve) => srv.server.on('listening', resolve));
1131
+ await srv.shutdown();
1132
+ await assert.rejects(httpRequest(port, { method: 'GET', path: '/' }));
1133
+ });
1134
+
1135
+ test('rejects requests exceeding Content-Length limit without reading body', async () => {
1136
+ const port = 12357;
1137
+ const srv = new ApiSrv({
1138
+ port,
1139
+ maxBodySize: 5,
1140
+ callback: () => {}
1141
+ });
1142
+ try {
1143
+ const status = await rawRequest(port,
1144
+ 'POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: 10\r\n\r\n');
1145
+ assert.strictEqual(status, 413);
1146
+ } finally {
1147
+ await srv.shutdown();
1148
+ }
1149
+ });
1150
+
1151
+ test('enforces Content-Length to match body length', async () => {
1152
+ const port = 12358;
1153
+ const srv = new ApiSrv({
1154
+ port,
1155
+ callback: () => {}
1156
+ });
1157
+ try {
1158
+ const status = await rawRequest(port,
1159
+ 'POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: 5\r\n\r\nabcd');
1160
+ assert.strictEqual(status, 400);
1161
+ } finally {
1162
+ await srv.shutdown();
1163
+ }
1164
+ });
1165
+
1166
+ test('allows additional Content-Type parameters', async () => {
1167
+ const port = 12359;
1168
+ const srv = new ApiSrv({
1169
+ port,
1170
+ callback: (r) => r.jsonResponse(r.params)
1171
+ });
1172
+ try {
1173
+ const res = await httpRequest(port, {
1174
+ method: 'POST',
1175
+ path: '/',
1176
+ headers: { 'Content-Type': 'application/json; charset=utf-8; version=1' },
1177
+ body: JSON.stringify({ a: 1 })
1178
+ });
1179
+ assert.strictEqual(res.status, 200);
1180
+ assert.deepStrictEqual(JSON.parse(res.data), { a: 1 });
1181
+ } finally {
1182
+ await srv.shutdown();
1183
+ }
1184
+ });
1185
+
1186
+ test('rejects unsupported charset parameter', async () => {
1187
+ const port = 12360;
1188
+ const srv = new ApiSrv({
1189
+ port,
1190
+ callback: () => {}
1191
+ });
1192
+ try {
1193
+ const res = await httpRequest(port, {
1194
+ method: 'POST',
1195
+ path: '/',
1196
+ headers: { 'Content-Type': 'application/json; charset=iso-8859-1' },
1197
+ body: JSON.stringify({ a: 1 })
1198
+ });
1199
+ assert.strictEqual(res.status, 400);
1200
+ } finally {
1201
+ await srv.shutdown();
1202
+ }
1203
+ });
1204
+