UNPKG

45.5 kBTypeScriptView Raw
1/// <reference types="node" />
2import http = require("http");
3import https = require("https");
4import Logger = require("bunyan");
5import url = require("url");
6import spdy = require("spdy");
7import stream = require("stream");
8import zlib = require("zlib");
9import { File } from "formidable";
10
11export interface ServerOptions {
12 ca?: string | Buffer | ReadonlyArray<string | Buffer> | undefined;
13
14 certificate?: string | Buffer | ReadonlyArray<string | Buffer> | undefined;
15
16 cert?: string | Buffer | ReadonlyArray<string | Buffer> | undefined;
17
18 key?: string | Buffer | ReadonlyArray<string | Buffer> | undefined;
19
20 passphrase?: string | undefined;
21
22 requestCert?: boolean | undefined;
23
24 ciphers?: string | undefined;
25
26 formatters?: Formatters | undefined;
27
28 log?: Logger | undefined;
29
30 name?: string | undefined;
31
32 spdy?: spdy.ServerOptions | undefined;
33
34 version?: string | undefined;
35
36 versions?: string[] | undefined;
37
38 handleUpgrades?: boolean | undefined;
39
40 httpsServerOptions?: https.ServerOptions | undefined;
41
42 handleUncaughtExceptions?: boolean | undefined;
43
44 router?: Router | undefined;
45
46 socketio?: boolean | undefined;
47
48 noWriteContinue?: boolean | undefined;
49
50 rejectUnauthorized?: boolean | undefined;
51
52 secureOptions?: number | undefined;
53
54 http2?: any;
55
56 dtrace?: boolean | undefined;
57
58 onceNext?: boolean | undefined;
59
60 strictNext?: boolean | undefined;
61
62 ignoreTrailingSlash?: boolean | undefined;
63
64 maxParamLength?: number | undefined;
65
66 strictFormatters?: boolean | undefined;
67}
68
69export interface AddressInterface {
70 port: number;
71
72 family: string;
73
74 address: string;
75}
76
77export interface Server extends http.Server {
78 /**
79 * Returns the server address. Wraps node's address().
80 */
81 address(): AddressInterface;
82
83 /**
84 * Gets the server up and listening. Wraps node's listen().
85 *
86 * You can call like:
87 * server.listen(80)
88 * server.listen(80, '127.0.0.1')
89 * server.listen('/tmp/server.sock')
90 *
91 * @throws {TypeError}
92 * @param callback optionally get notified when listening.
93 */
94 listen(...args: any[]): any;
95
96 /**
97 * Shuts down this server, and invokes callback (optionally) when done.
98 * Wraps node's close().
99 * @param callback optional callback to invoke when done.
100 */
101 close(callback?: () => any): any;
102
103 /**
104 * Returns the number of currently inflight requests.
105 */
106 inflightRequests(): number;
107
108 /**
109 * Mounts a chain on the given path against this HTTP verb
110 *
111 * @param opts if string, the URL to handle.
112 * if options, the URL to handle, at minimum.
113 * @returns the newly created route.
114 */
115 del(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean;
116
117 /**
118 * Mounts a chain on the given path against this HTTP verb
119 *
120 * @param opts if string, the URL to handle.
121 * if options, the URL to handle, at minimum.
122 * @returns the newly created route.
123 */
124 get(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean;
125
126 /**
127 * Mounts a chain on the given path against this HTTP verb
128 *
129 * @param opts if string, the URL to handle.
130 * if options, the URL to handle, at minimum.
131 * @returns the newly created route.
132 */
133 head(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean;
134
135 /**
136 * Mounts a chain on the given path against this HTTP verb
137 *
138 * @param opts if string, the URL to handle.
139 * if options, the URL to handle, at minimum.
140 * @returns the newly created route.
141 */
142 opts(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean;
143
144 /**
145 * Mounts a chain on the given path against this HTTP verb
146 *
147 * @param opts if string, the URL to handle.
148 * if options, the URL to handle, at minimum.
149 * @returns the newly created route.
150 */
151 post(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean;
152
153 /**
154 * Mounts a chain on the given path against this HTTP verb
155 *
156 * @param opts if string, the URL to handle.
157 * if options, the URL to handle, at minimum.
158 * @returns the newly created route.
159 */
160 put(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean;
161
162 /**
163 * Mounts a chain on the given path against this HTTP verb
164 *
165 * @param opts if string, the URL to handle.
166 * if options, the URL to handle, at minimum.
167 * @returns the newly created route.
168 */
169 patch(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean;
170
171 /**
172 * Minimal port of the functionality offered by Express.js Route Param
173 * Pre-conditions
174 * @link http://expressjs.com/guide.html#route-param%20pre-conditions
175 *
176 * This basically piggy-backs on the `server.use` method. It attaches a
177 * new middleware function that only fires if the specified parameter exists
178 * in req.params
179 *
180 * Exposes an API:
181 * server.param("user", function (req, res, next) {
182 * // load the user's information here, always making sure to call next()
183 * });
184 *
185 * @param name The name of the URL param to respond to
186 * @param fn The middleware function to execute
187 * @returns returns self
188 */
189 param(name: string, fn: RequestHandler): Server;
190
191 /**
192 * Removes a route from the server.
193 * You pass in the route 'blob' you got from a mount call.
194 * @throws {TypeError} on bad input.
195 * @param route the route name.
196 * @returns true if route was removed, false if not.
197 */
198 rm(route: string): boolean;
199
200 /**
201 * Installs a list of handlers to run _before_ the "normal" handlers of all
202 * routes.
203 *
204 * You can pass in any combination of functions or array of functions.
205 * @returns returns self
206 */
207 use(...handlers: RequestHandlerType[]): Server;
208
209 /**
210 * Gives you hooks to run _before_ any routes are located. This gives you
211 * a chance to intercept the request and change headers, etc., that routing
212 * depends on. Note that req.params will _not_ be set yet.
213 * @returns returns self
214 */
215 pre(...pre: RequestHandlerType[]): Server;
216
217 /**
218 * toString() the server for easy reading/output.
219 */
220 toString(): string;
221
222 /**
223 * Return debug information about the server.
224 */
225 getDebugInfo(): any;
226
227 /** Name of the server. */
228 name: string;
229
230 /** Default version(s) to use in all routes. */
231 versions: string[];
232
233 /** bunyan instance. */
234 log: Logger;
235
236 /** List of content-types this server can respond with. */
237 acceptable: string[];
238
239 /** Once listen() is called, this will be filled in with where the server is running. */
240 url: string;
241
242 /** Node server instance */
243 server: http.Server | https.Server | spdy.Server;
244
245 /** Router instance */
246 router: Router;
247
248 /** Handle uncaught exceptions */
249 handleUncaughtExceptions: boolean;
250
251 /** enable DTrace support */
252 dtrace: boolean;
253
254 /** Custom response formatters */
255 formatters: Formatters;
256
257 /** Prevents calling next multiple times */
258 onceNext: boolean;
259
260 /** Throws error when next() is called more than once, enabled onceNext option */
261 strictNext: boolean;
262
263 /** Pre handlers */
264 preChain: Chain;
265
266 useChain: Chain;
267
268 spdy?: boolean | undefined;
269
270 http2?: boolean | undefined;
271
272 ca: ServerOptions["ca"];
273
274 certificate: ServerOptions["certificate"];
275
276 key: ServerOptions["key"];
277
278 passphrase: ServerOptions["passphrase"] | null;
279
280 secure?: boolean | undefined;
281}
282
283export interface ChainOptions {
284 onceNext?: boolean | undefined;
285
286 strictNext?: boolean | undefined;
287}
288
289export interface Chain {
290 /** Get handlers of a chain instance */
291 getHandlers(): RequestHandler[];
292
293 /** Utilize the given middleware `handler` */
294 add(handler: RequestHandler): void;
295
296 /** Returns the number of handlers */
297 count(): number;
298
299 /** Handle server requests, punting them down the middleware stack. */
300 run(req: Request, res: Response, done: () => any): void;
301
302 /** Prevents calling next multiple times */
303 onceNext: boolean;
304
305 /** Throws error when next() is called more than once, enables onceNext option */
306 strictNext: boolean;
307}
308
309export interface RouterRegistryRadix {
310 /**
311 * Adds a route.
312 */
313 add(route: Route): boolean;
314
315 /**
316 * Removes a route.
317 */
318 remove(name: string): Route | undefined;
319
320 /**
321 * Registry for route.
322 */
323 lookup(method: string, pathname: string): Chain | undefined;
324
325 /**
326 * Get registry.
327 */
328 get(): Route[];
329
330 /**
331 * toString() serialization.
332 */
333 toString(): string;
334}
335
336export interface RouterOptions {
337 log?: Logger | undefined;
338
339 onceNext?: boolean | undefined;
340
341 strictNext?: boolean | undefined;
342
343 ignoreTrailingSlash?: boolean | undefined;
344
345 registry?: RouterRegistryRadix | undefined;
346}
347
348export class Router {
349 constructor(options: RouterOptions);
350
351 /**
352 * Lookup for route
353 */
354 lookup(req: Request, res: Response): Chain | undefined;
355
356 /**
357 * Lookup by name
358 */
359 lookupByName(name: string, req: Request, res: Response): Chain | undefined;
360
361 /**
362 * adds a route.
363 * @param options an options object
364 * @returns returns the route name if creation is successful.
365 */
366 mount(options: MountOptions, ...handlers: RequestHandlerType[]): string;
367
368 /**
369 * unmounts a route.
370 * @param name the route name
371 * @returns the name of the deleted route.
372 */
373 unmount(name: string): string;
374
375 /**
376 * Return mounted routes.
377 */
378 getRoutes(): Route[];
379
380 /**
381 * Default route, when no route found
382 */
383 defaultRoute(req: Request, res: Response, next: Next): void;
384
385 /**
386 * takes an object of route params and query params, and 'renders' a URL.
387 * @param routeName the route name
388 * @param params an object of route params
389 * @param query an object of query params
390 */
391 render(routeName: string, params: object, query?: object): string;
392
393 /**
394 * toString() serialization.
395 */
396 toString(): string;
397
398 /**
399 * Return information about the routes registered in the router.
400 * @returns The routes in the router.
401 */
402 getDebugInfo(): any;
403
404 name: string;
405
406 log?: Logger | undefined;
407
408 onceNext: boolean;
409
410 strictNext: boolean;
411}
412
413export interface RequestAuthorization {
414 scheme: string;
415 credentials: string;
416 basic?: {
417 username: string;
418 password: string;
419 } | undefined;
420}
421
422export interface Request extends http.IncomingMessage {
423 /**
424 * Builds an absolute URI for the request.
425 */
426 absoluteUri(path: string): string;
427
428 /**
429 * checks if the accept header is present and has the value requested.
430 * e.g., req.accepts('html');
431 * @param types an array of accept type headers
432 */
433 accepts(types: string | string[]): boolean;
434
435 /**
436 * checks if the request accepts the encoding types.
437 * @param types an array of accept type headers
438 */
439 acceptsEncoding(types: string | string[]): boolean;
440
441 /**
442 * gets the content-length header off the request.
443 */
444 getContentLength(): number;
445
446 /**
447 * pass through to getContentLength.
448 */
449 contentLength(): number;
450
451 /**
452 * gets the content-type header.
453 */
454 getContentType(): string;
455
456 /**
457 * pass through to getContentType.
458 */
459 contentType(): string;
460
461 /**
462 * retrieves the complete URI requested by the client.
463 */
464 getHref(): string;
465
466 /**
467 * pass through to getHref.
468 */
469 href(): string;
470
471 /**
472 * retrieves the request uuid. was created when the request was setup.
473 */
474 getId(): string;
475
476 /**
477 * pass through to getId.
478 */
479 id(): string;
480
481 /**
482 * retrieves the cleaned up url path.
483 * e.g., /foo?a=1 => /foo
484 */
485 getPath(): string;
486
487 /**
488 * pass through to getPath.
489 */
490 path(): string;
491
492 /**
493 * returns the raw query string
494 */
495 getQuery(): string;
496
497 // /**
498 // * pass through to getQuery.
499 // * @public
500 // * @function query
501 // * @returns {String}
502 // */
503 // query(): string;
504
505 /**
506 * returns ms since epoch when request was setup.
507 */
508 time(): number;
509
510 /**
511 * returns a parsed URL object.
512 */
513 getUrl(): url.Url;
514
515 /**
516 * returns the accept-version header.
517 */
518 getVersion(): string;
519
520 /**
521 * pass through to getVersion.
522 */
523 version(): string;
524
525 /**
526 * returns the version of the route that matched.
527 */
528 matchedVersion(): string;
529
530 /**
531 * Get the case-insensitive request header key,
532 * and optionally provide a default value (express-compliant).
533 * Returns any header off the request. also, 'correct' any
534 * correctly spelled 'referrer' header to the actual spelling used.
535 * @param key - the key of the header
536 * @param defaultValue - default value if header isn't found on the req
537 */
538 header(key: string, defaultValue?: string): string;
539
540 /**
541 * returns any trailer header off the request. also, 'correct' any
542 * correctly spelled 'referrer' header to the actual spelling used.
543 * @param name the name of the header
544 * @param defaultValue default value if header isn't found on the req
545 */
546 trailer(name: string, defaultValue?: string): string;
547
548 /**
549 * Check if the incoming request contains the Content-Type header field, and
550 * if it contains the given mime type.
551 * @param type a content-type header value
552 */
553 is(type: string): boolean;
554
555 /**
556 * Check if the incoming request is chunked.
557 */
558 isChunked(): boolean;
559
560 /**
561 * Check if the incoming request is kept alive.
562 */
563 isKeepAlive(): boolean;
564
565 /**
566 * Check if the incoming request is encrypted.
567 */
568 isSecure(): boolean;
569
570 /**
571 * Check if the incoming request has been upgraded.
572 */
573 isUpgradeRequest(): boolean;
574
575 /**
576 * Check if the incoming request is an upload verb.
577 */
578 isUpload(): boolean;
579
580 /**
581 * toString serialization
582 */
583 toString(): string;
584
585 /**
586 * retrieves the user-agent header.
587 */
588 userAgent(): string;
589
590 /**
591 * Start the timer for a request handler function. You must explicitly invoke
592 * endHandlerTimer() after invoking this function. Otherwise timing information
593 * will be inaccurate.
594 * @param handlerName The name of the handler.
595 */
596 startHandlerTimer(handlerName: string): void;
597
598 /**
599 * Stop the timer for a request handler function.
600 * @param handlerName The name of the handler.
601 */
602 endHandlerTimer(handlerName: string): void;
603
604 /**
605 * returns the connection state of the request. current valid values are
606 * 'close' and 'aborted'.
607 */
608 connectionState(): string;
609
610 /**
611 * returns the route object to which the current request was matched to.
612 * Route info object structure:
613 * {
614 * path: '/ping/:name',
615 * method: 'GET',
616 * versions: [],
617 * name: 'getpingname'
618 * }
619 */
620 getRoute(): Route;
621
622 /** bunyan logger you can piggyback on. */
623 log: Logger;
624
625 /** available when queryParser plugin is used. */
626 query?: any;
627
628 /** available when bodyParser plugin is used. */
629 body?: any;
630
631 /** available when bodyParser plugin is used. */
632 rawBody?: any;
633
634 /** available when queryParser or bodyParser plugin is used with mapParams enabled. */
635 params?: any;
636
637 /** available when multipartBodyParser plugin is used. */
638 files?: { [name: string]: File | undefined } | undefined;
639
640 /** available when authorizationParser plugin is used */
641 username?: string | undefined;
642
643 /** available when authorizationParser plugin is used */
644 authorization?: RequestAuthorization | undefined;
645}
646
647export interface CacheOptions {
648 maxAge: number;
649}
650
651export interface Response extends http.ServerResponse {
652 /**
653 * sets the cache-control header. `type` defaults to _public_,
654 * and options currently only takes maxAge.
655 * @param type value of the header
656 * @param [options] an options object
657 * @returns the value set to the header
658 */
659 cache(type: string, options?: CacheOptions): string;
660
661 /**
662 * sets the cache-control header. `type` defaults to _public_,
663 * and options currently only takes maxAge.
664 * @param [options] an options object
665 * @returns the value set to the header
666 */
667 cache(options?: CacheOptions): string;
668
669 /**
670 * turns off all cache related headers.
671 * @returns self, the response object
672 */
673 noCache(): Response;
674
675 /**
676 * Appends the provided character set to the response's Content-Type.
677 * e.g., res.charSet('utf-8');
678 * @param type char-set value
679 * @returns self, the response object
680 */
681 charSet(type: string): Response;
682
683 /**
684 * retrieves a header off the response.
685 * @param name the header name
686 */
687 get(name: string): string;
688
689 /**
690 * retrieves all headers off the response.
691 */
692 getHeaders(): any;
693
694 /**
695 * pass through to getHeaders.
696 */
697 headers(): any;
698
699 /**
700 * sets headers on the response.
701 * @param key the name of the header
702 * @param value the value of the header
703 */
704 header(key: string, value?: any): any;
705
706 /**
707 * short hand method for:
708 * res.contentType = 'json';
709 * res.send({hello: 'world'});
710 * @param code http status code
711 * @param body value to json.stringify
712 * @param [headers] headers to set on the response
713 */
714 json(code: number, body: any, headers?: { [header: string]: string }): any;
715
716 /**
717 * short hand method for:
718 * res.contentType = 'json';
719 * res.send({hello: 'world'});
720 * @param body value to json.stringify
721 * @param [headers] headers to set on the response
722 */
723 json(body: any, headers?: { [header: string]: string }): any;
724
725 /**
726 * sets the link heaader.
727 * @param key the link key
728 * @param value the link value
729 * @returns the header value set to res
730 */
731 link(key: string, value: string): string;
732
733 /**
734 * sends the response object. pass through to internal __send that uses a
735 * formatter based on the content-type header.
736 * @param [code] http status code
737 * @param [body] the content to send
738 * @param [headers] any add'l headers to set
739 * @returns the response object
740 */
741 send(code?: number, body?: any, headers?: { [header: string]: string }): any;
742
743 /**
744 * sends the response object. pass through to internal __send that uses a
745 * formatter based on the content-type header.
746 * @param [body] the content to send
747 * @param [headers] any add'l headers to set
748 * @returns the response object
749 */
750 send(body?: any, headers?: { [header: string]: string }): any;
751
752 /**
753 * sends the response object. pass through to internal __send that skips
754 * formatters entirely and sends the content as is.
755 * @param [code] http status code
756 * @param [body] the content to send
757 * @param [headers] any add'l headers to set
758 * @returns the response object
759 */
760 sendRaw(code?: number, body?: any, headers?: { [header: string]: string }): any;
761
762 /**
763 * sends the response object. pass through to internal __send that skips
764 * formatters entirely and sends the content as is.
765 * @param [body] the content to send
766 * @param [headers] any add'l headers to set
767 * @returns the response object
768 */
769 sendRaw(body?: any, headers?: { [header: string]: string }): any;
770
771 /**
772 * sets a header on the response.
773 * @param name name of the header
774 * @param val value of the header
775 * @returns self, the response object
776 */
777 set(name: string, val: string): Response;
778
779 /**
780 * sets a header on the response.
781 * @param val object of headers
782 * @returns self, the response object
783 */
784 set(headers?: { [header: string]: string }): Response;
785
786 /**
787 * sets the http status code on the response.
788 * @param code http status code
789 * @returns the status code passed in
790 */
791 status(code: number): number;
792
793 /**
794 * toString() serialization.
795 */
796 toString(): string;
797
798 /**
799 * redirect is sugar method for redirecting.
800 * res.redirect(301, 'www.foo.com', next);
801 * `next` is mandatory, to complete the response and trigger audit logger.
802 * @param code the status code
803 * @param url to redirect to
804 * @param next - mandatory, to complete the response and trigger audit logger
805 * @fires redirect
806 */
807 redirect(code: number, url: string, next: Next): void;
808
809 /**
810 * redirect is sugar method for redirecting.
811 * res.redirect({...}, next);
812 * `next` is mandatory, to complete the response and trigger audit logger.
813 * @param url to redirect to or options object to configure a redirect or
814 * @param next - mandatory, to complete the response and trigger audit logger
815 * @fires redirect
816 */
817 redirect(opts: string | RedirectOptions, next: Next): void;
818
819 /** HTTP status code. */
820 code: number;
821
822 /** short hand for the header content-length. */
823 contentLength: number;
824
825 /** short hand for the header content-type. */
826 contentType: string;
827
828 /** A unique request id (x-request-id). */
829 id: string;
830}
831
832export interface RedirectOptions {
833 /**
834 * whether to redirect to http or https
835 */
836 secure?: boolean | undefined;
837
838 /**
839 * redirect location's hostname
840 */
841 hostname?: string | undefined;
842
843 /**
844 * redirect location's pathname
845 */
846 pathname?: string | undefined;
847
848 /**
849 * redirect location's port number
850 */
851 port?: string | undefined;
852
853 /**
854 * redirect location's query string parameters
855 */
856 query?: string | object | undefined;
857
858 /**
859 * if true, `options.query`
860 * stomps over any existing query
861 * parameters on current URL.
862 * by default, will merge the two.
863 */
864 overrideQuery?: boolean | undefined;
865
866 /**
867 * if true, sets 301. defaults to 302.
868 */
869 permanent?: boolean | undefined;
870}
871
872export interface Next {
873 (err?: any): void;
874}
875
876export interface RouteSpec {
877 method: string;
878 name?: string | undefined;
879 path: string | RegExp;
880 versions?: string[] | undefined;
881}
882
883export interface Route {
884 name: string;
885 method: string;
886 path: string | RegExp;
887 spec: RouteSpec;
888 chain: Chain;
889}
890
891export interface RouteOptions {
892 name?: string | undefined;
893
894 path?: string | RegExp | undefined;
895
896 url?: string | RegExp | undefined;
897
898 urlParamPattern?: RegExp | undefined;
899
900 contentType?: string | string[] | undefined;
901
902 version?: string | undefined;
903
904 versions?: string[] | undefined;
905}
906
907export interface MountOptions {
908 name: string;
909
910 method: string;
911
912 path?: string | RegExp | undefined;
913
914 url?: string | RegExp | undefined;
915
916 urlParamPattern?: RegExp | undefined;
917
918 contentType?: string | string[] | undefined;
919
920 version?: string | undefined;
921
922 versions?: string[] | undefined;
923}
924
925export type FindRouteCallback = (err: Error, route?: Route, params?: any) => void;
926
927export type RequestHandler = (req: Request, res: Response, next: Next) => any;
928export type RequestHandlerType = RequestHandler | RequestHandler[];
929
930export interface ServerUpgradeResponse {
931 /**
932 * Set the status code of the response.
933 * @param code - the http status code
934 */
935 status(code: number): number;
936
937 /**
938 * Sends the response.
939 * @param code - the http status code
940 * @param body - the response to send out
941 */
942 send(code: number, body: any): any;
943
944 /**
945 * Sends the response.
946 * @param body - the response to send out
947 */
948 send(body: any): boolean;
949
950 /**
951 * Ends the response
952 */
953 end(): boolean;
954
955 /**
956 * Write to the response.
957 */
958 write(): boolean;
959
960 /**
961 * Write to the head of the response.
962 * @param statusCode - the http status code
963 * @param reason - a message
964 */
965 writeHead(statusCode: number, reason?: string): void;
966
967 /**
968 * Attempt to upgrade.
969 */
970 claimUpgrade(): any;
971}
972
973export namespace bunyan {
974 interface RequestCaptureOptions {
975 /** The stream to which to write when dumping captured records. */
976 stream?: Logger.Stream | undefined;
977
978 /** The streams to which to write when dumping captured records. */
979 streams?: readonly Logger.Stream[] | undefined;
980
981 /**
982 * The level at which to trigger dumping captured records. Defaults to
983 * bunyan.WARN.
984 */
985 level?: Logger.LogLevel | undefined;
986
987 /** Number of records to capture. Default 100. */
988 maxRecords?: number | undefined;
989
990 /**
991 * Number of simultaneous request id capturing buckets to maintain.
992 * Default 1000.
993 */
994 maxRequestIds?: number | undefined;
995
996 /**
997 * If true, then dump captured records on the *default* request id when
998 * dumping. I.e. dump records logged without "req_id" field. Default
999 * false.
1000 */
1001 dumpDefault?: boolean | undefined;
1002 }
1003
1004 /**
1005 * A Bunyan stream to capture records in a ring buffer and only pass through
1006 * on a higher-level record. E.g. buffer up all records but only dump when
1007 * getting a WARN or above.
1008 */
1009 class RequestCaptureStream extends stream.Stream {
1010 constructor(opts: RequestCaptureOptions);
1011
1012 /** write to the stream */
1013 write(record: any): void;
1014 }
1015
1016 const serializers: Logger.Serializers & {
1017 err: Logger.Serializer;
1018 req: Logger.Serializer;
1019 res: Logger.Serializer;
1020 client_req: Logger.Serializer;
1021 client_res: Logger.Serializer;
1022 };
1023
1024 /** create a bunyan logger */
1025 function createLogger(name: string): Logger;
1026}
1027
1028export function createServer(options?: ServerOptions): Server;
1029
1030export type Formatter = (req: Request, res: Response, body: any) => string | Buffer | null;
1031
1032export interface Formatters {
1033 [contentType: string]: Formatter;
1034}
1035
1036export const formatters: Formatters;
1037
1038export namespace plugins {
1039 namespace pre {
1040 /**
1041 * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request.
1042 */
1043 function context(): RequestHandler;
1044
1045 function dedupeSlashes(): RequestHandler;
1046
1047 /**
1048 * This pre handler fixes issues with node hanging when an asyncHandler is used prior to bodyParser.
1049 */
1050 function pause(): RequestHandler;
1051
1052 /**
1053 * Cleans up duplicate or trailing / on the URL
1054 */
1055 function sanitizePath(): RequestHandler;
1056
1057 /**
1058 * Automatically reuse incoming request header as the request id.
1059 */
1060 function reqIdHeaders(options: { headers: string[] }): RequestHandler;
1061
1062 /**
1063 * Checks req.urls query params with strict key/val format and rejects non-strict requests with status code 400.
1064 */
1065 function strictQueryParams(options?: { message: string }): RequestHandler;
1066
1067 /**
1068 * Regexp to capture curl user-agents
1069 */
1070 function userAgentConnection(options?: {
1071 userAgentRegExp: any;
1072 }): RequestHandler;
1073 }
1074
1075 // *************** This module includes the following header parser plugins:
1076
1077 /**
1078 * Check the client's Accept header can be handled by this server.
1079 */
1080 function acceptParser(accepts: string[]): RequestHandler;
1081
1082 type AuditLoggerContext = (
1083 req: Request,
1084 res: Response,
1085 route: any,
1086 error: any,
1087 ) => any;
1088
1089 interface AuditLoggerOptions {
1090 /**
1091 * Bunyan logger
1092 */
1093 log: Logger;
1094
1095 /**
1096 * The event from the server which initiates the
1097 * log, one of 'pre', 'routed', or 'after'
1098 */
1099 event: "pre" | "routed" | "after";
1100
1101 /**
1102 * Restify server. If passed in, causes server to emit 'auditlog' event after audit logs are flushed
1103 */
1104 server?: Server | undefined;
1105
1106 /**
1107 * The optional context function of signature
1108 * f(req, res, route, err). Invoked each time an audit log is generated. This
1109 * function can return an object that customizes the format of anything off the
1110 * req, res, route, and err objects. The output of this function will be
1111 * available on the `context` key in the audit object.
1112 */
1113 context?: AuditLoggerContext | undefined;
1114
1115 /**
1116 * Ringbuffer which is written to if passed in
1117 */
1118 logBuffer?: any;
1119
1120 /**
1121 * When true, prints audit logs. default true.
1122 */
1123 printLog?: boolean | undefined;
1124
1125 body?: boolean | undefined;
1126 }
1127
1128 /**
1129 * An audit logger for recording all handled requests
1130 */
1131 function auditLogger(options: AuditLoggerOptions): (...args: any[]) => void;
1132
1133 /**
1134 * Authorization header
1135 */
1136 function authorizationParser(options?: any): RequestHandler;
1137
1138 interface HandlerCandidate {
1139 handler: RequestHandler | RequestHandler[];
1140 version?: string | string[] | undefined;
1141 contentType?: string | string[] | undefined;
1142 }
1143
1144 /**
1145 * Runs first handler that matches to the condition
1146 */
1147 function conditionalHandler(
1148 candidates: HandlerCandidate | HandlerCandidate[],
1149 ): RequestHandler;
1150
1151 /**
1152 * Conditional headers (If-*)
1153 */
1154 function conditionalRequest(): RequestHandler[];
1155
1156 interface CpuUsageThrottleOptions {
1157 limit?: number | undefined;
1158 max?: number | undefined;
1159 interval?: number | undefined;
1160 halfLife?: number | undefined;
1161 }
1162
1163 /**
1164 * Cpu Throttle middleware
1165 */
1166 function cpuUsageThrottle(opts?: CpuUsageThrottleOptions): RequestHandler;
1167
1168 /**
1169 * Handles disappeared CORS headers
1170 */
1171 function fullResponse(): RequestHandler;
1172
1173 // ************ This module includes the following data parsing plugins:
1174
1175 interface BodyParserOptions {
1176 /**
1177 * The maximum size in bytes allowed in the HTTP body. Useful for limiting clients from hogging server memory.
1178 */
1179 maxBodySize?: number | undefined;
1180
1181 /**
1182 * If req.params should be filled with parsed parameters from HTTP body.
1183 */
1184 mapParams?: boolean | undefined;
1185
1186 /**
1187 * If req.params should be filled with the contents of files sent through a multipart request.
1188 * Formidable is used internally for parsing, and a file is denoted as a multipart part with the filename option set in its Content-Disposition.
1189 * This will only be performed if mapParams is true.
1190 */
1191 mapFiles?: boolean | undefined;
1192
1193 /**
1194 * If an entry in req.params should be overwritten by the value in the body if the names are the same.
1195 * For instance, if you have the route /:someval, and someone posts an x-www-form-urlencoded Content-Type with the body someval=happy to /sad,
1196 * the value will be happy if overrideParams is true, sad otherwise.
1197 */
1198 overrideParams?: boolean | undefined;
1199
1200 /**
1201 * A callback to handle any multipart part which is not a file.
1202 * If this is omitted, the default handler is invoked which may or may not map the parts into req.params, depending on the mapParams-option.
1203 */
1204 multipartHandler?(): void;
1205
1206 /**
1207 * A callback to handle any multipart file.
1208 * It will be a file if the part have a Content-Disposition with the filename parameter set.
1209 * This typically happens when a browser sends a form and there is a parameter similar to <input type="file" />.
1210 * If this is not provided, the default behaviour is to map the contents into req.params.
1211 */
1212 multipartFileHandler?(): void;
1213
1214 /**
1215 * If you want the uploaded files to include the extensions of the original files (multipart uploads only). Does nothing if multipartFileHandler is defined.
1216 */
1217 keepExtensions?: boolean | undefined;
1218
1219 /**
1220 * Where uploaded files are intermediately stored during transfer before the contents is mapped into req.params. Does nothing if multipartFileHandler is defined.
1221 */
1222 uploadDir?: string | undefined;
1223
1224 /**
1225 * If you want to support html5 multiple attribute in upload fields.
1226 */
1227 multiples?: boolean | undefined;
1228
1229 /**
1230 * If you want checksums calculated for incoming files, set this to either sha1 or md5.
1231 */
1232 hash?: string | undefined;
1233
1234 /**
1235 * Set to true if you want to end the request with a UnsupportedMediaTypeError when none of the supported content types was given.
1236 */
1237 rejectUnknown?: boolean | undefined;
1238
1239 requestBodyOnGet?: boolean | undefined;
1240
1241 reviver?: any;
1242
1243 maxFieldsSize?: number | undefined;
1244
1245 maxFileSize?: number | undefined;
1246 }
1247
1248 /**
1249 * Parses POST bodies to req.body. automatically uses one of the following parsers based on content type.
1250 */
1251 function bodyParser(options?: BodyParserOptions): RequestHandler[];
1252
1253 /**
1254 * Reads the body of the request.
1255 */
1256 function bodyReader(options?: { maxBodySize?: number | undefined }): RequestHandler;
1257
1258 interface UrlEncodedBodyParserOptions {
1259 mapParams?: boolean | undefined;
1260 overrideParams?: boolean | undefined;
1261 bodyReader?: boolean | undefined;
1262 }
1263
1264 /**
1265 * Parse the HTTP request body IFF the contentType is application/x-www-form-urlencoded.
1266 *
1267 * If req.params already contains a given key, that key is skipped and an
1268 * error is logged.
1269 */
1270 function urlEncodedBodyParser(
1271 options?: UrlEncodedBodyParserOptions,
1272 ): RequestHandler[];
1273
1274 interface JsonBodyParserOptions {
1275 mapParams?: boolean | undefined;
1276 overrideParams?: boolean | undefined;
1277 reviver?(key: any, value: any): any;
1278 bodyReader?: boolean | undefined;
1279 }
1280
1281 /**
1282 * Parses JSON POST bodies
1283 */
1284 function jsonBodyParser(options?: JsonBodyParserOptions): RequestHandler[];
1285
1286 /**
1287 * Parses JSONP callback
1288 */
1289 function jsonp(): RequestHandler;
1290
1291 interface MultipartBodyParser {
1292 overrideParams?: boolean | undefined;
1293 multiples?: boolean | undefined;
1294 keepExtensions?: boolean | undefined;
1295 uploadDir?: string | undefined;
1296 maxFieldsSize?: number | undefined;
1297 hash?: string | undefined;
1298 multipartFileHandler?: any;
1299 multipartHandler?: any;
1300 mapParams?: boolean | undefined;
1301 mapFiles?: boolean | undefined;
1302 maxFileSize?: number | undefined;
1303 }
1304
1305 /**
1306 * Parses JSONP callback
1307 */
1308 function multipartBodyParser(options?: MultipartBodyParser): RequestHandler;
1309
1310 interface QueryParserOptions {
1311 /**
1312 * Default `false`. Copies parsed query parameters into `req.params`.
1313 */
1314 mapParams?: boolean | undefined;
1315
1316 /**
1317 * Default `false`. Only applies when if mapParams true. When true, will stomp on req.params field when existing value is found.
1318 */
1319 overrideParams?: boolean | undefined;
1320
1321 /**
1322 * Default false. Transform `?foo.bar=baz` to a nested object: `{foo: {bar: 'baz'}}`.
1323 */
1324 allowDots?: boolean | undefined;
1325
1326 /**
1327 * Default 20. Only transform `?a[$index]=b` to an array if `$index` is less than `arrayLimit`.
1328 */
1329 arrayLimit?: number | undefined;
1330
1331 /**
1332 * Default 5. The depth limit for parsing nested objects, e.g. `?a[b][c][d][e][f][g][h][i]=j`.
1333 */
1334 depth?: number | undefined;
1335
1336 /**
1337 * Default 1000. Maximum number of query params parsed. Additional params are silently dropped.
1338 */
1339 parameterLimit?: number | undefined;
1340
1341 /**
1342 * Default true. Whether to parse `?a[]=b&a[1]=c` to an array, e.g. `{a: ['b', 'c']}`.
1343 */
1344 parseArrays?: boolean | undefined;
1345
1346 /**
1347 * Default false. Whether `req.query` is a "plain" object -- does not inherit from `Object`.
1348 * This can be used to allow query params whose names collide with Object methods, e.g. `?hasOwnProperty=blah`.
1349 */
1350 plainObjects?: boolean | undefined;
1351
1352 /**
1353 * Default false. If true, `?a&b=` results in `{a: null, b: ''}`. Otherwise, `{a: '', b: ''}`.
1354 */
1355 strictNullHandling?: boolean | undefined;
1356 }
1357
1358 /**
1359 * Parses URL query parameters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs)
1360 */
1361 function queryParser(options?: QueryParserOptions): RequestHandler;
1362
1363 interface RequestLogger {
1364 properties?: any;
1365 serializers?: any;
1366 headers?: any;
1367 log?: any;
1368 }
1369
1370 /**
1371 * Adds timers for each handler in your request chain
1372 *
1373 * `options.properties` properties to pass to bunyan's `log.child()` method
1374 */
1375 function requestLogger(options?: RequestLogger): RequestHandler;
1376
1377 // ******************** The module includes the following response plugins:
1378
1379 /**
1380 * expires requests based on current time + delta
1381 * @param delta - age in seconds
1382 */
1383 function dateParser(delta?: number): RequestHandler;
1384
1385 /**
1386 * gzips the response if client send `accept-encoding: gzip`
1387 * @param options options to pass to gzlib
1388 */
1389 function gzipResponse(options?: zlib.ZlibOptions): RequestHandler;
1390
1391 interface InflightRequestThrottleOptions {
1392 limit: number;
1393 server: Server;
1394 err: any;
1395 }
1396
1397 function inflightRequestThrottle(
1398 opts: InflightRequestThrottleOptions,
1399 ): RequestHandler;
1400
1401 interface ServeStatic {
1402 appendRequestPath?: boolean | undefined;
1403 directory?: string | undefined;
1404 maxAge?: number | undefined;
1405 match?: any;
1406 charSet?: string | undefined;
1407 file?: string | undefined;
1408 etag?: string | undefined;
1409 default?: any;
1410 gzip?: boolean | undefined;
1411 }
1412
1413 /**
1414 * Used to serve static files
1415 */
1416 function serveStatic(options?: ServeStatic): RequestHandler;
1417
1418 interface ServeStaticFiles {
1419 maxAge?: number | undefined;
1420 etag?: string | undefined;
1421 setHeaders?: ((res: Response, path: string, stat: any) => any) | undefined;
1422 }
1423
1424 /**
1425 * Used to serve static files from a given directory
1426 */
1427 function serveStaticFiles(
1428 dir: string,
1429 options?: ServeStaticFiles,
1430 ): RequestHandler;
1431
1432 interface ThrottleOptions {
1433 burst?: number | undefined;
1434 rate?: number | undefined;
1435 setHeaders?: boolean | undefined;
1436 ip?: boolean | undefined;
1437 username?: boolean | undefined;
1438 xff?: boolean | undefined;
1439 tokensTable?: any;
1440 maxKeys?: number | undefined;
1441 overrides?: any; // any
1442 }
1443
1444 /**
1445 * throttles responses
1446 */
1447 function throttle(options?: ThrottleOptions): RequestHandler;
1448
1449 type MetricsCallback = (
1450 /**
1451 * An error if the request had an error
1452 */
1453 err: Error,
1454 /**
1455 * Object that contains the various metrics that are returned
1456 */
1457 metrics: MetricsCallbackOptions,
1458 /**
1459 * The request obj
1460 */
1461 req: Request,
1462 /**
1463 * The response obj
1464 */
1465 res: Response,
1466 /**
1467 * The route obj that serviced the request
1468 */
1469 route: Route,
1470 ) => void;
1471
1472 type TMetricsCallback = "close" | "aborted" | undefined;
1473
1474 interface MetricsCallbackOptions {
1475 /**
1476 * Status code of the response. Can be undefined in the case of an `uncaughtException`.
1477 * Otherwise, in most normal scenarios, even calling `res.send()` or `res.end()` should result in a 200 by default.
1478 */
1479 statusCode: number;
1480
1481 /**
1482 * HTTP request verb
1483 */
1484 method: string;
1485
1486 /**
1487 * latency includes both request is flushed and all handlers finished
1488 */
1489 totalLatency: number;
1490
1491 /**
1492 * Request latency
1493 */
1494 latency: number;
1495
1496 /**
1497 * pre handlers latency
1498 */
1499 preLatency: number | null;
1500
1501 /**
1502 * use handlers latency
1503 */
1504 useLatency: number | null;
1505
1506 /**
1507 * req.path() value
1508 */
1509 path: string;
1510
1511 /**
1512 * Number of inflight requests pending in restify
1513 */
1514 inflightRequests: number;
1515
1516 /**
1517 * Same as `inflightRequests`
1518 */
1519 unfinishedRequests: number;
1520
1521 /**
1522 * If this value is set, err will be a corresponding `RequestCloseError` or `RequestAbortedError`.
1523 *
1524 * If connectionState is either 'close' or 'aborted', then the statusCode is not applicable since the connection was severed before a response was written.
1525 */
1526 connectionState: TMetricsCallback;
1527 }
1528
1529 /**
1530 * Listens to the server's after event and emits information about that request (5.x compatible only).
1531 *
1532 * ```
1533 * server.on('after', plugins.metrics({ server }, (err, metrics, req, res, route) =>
1534 * {
1535 * // metrics is an object containing information about the request
1536 * }));
1537 * ```
1538 */
1539 function metrics(
1540 opts: { server: Server },
1541 callback: MetricsCallback,
1542 ): (...args: any[]) => void;
1543
1544 /**
1545 * Parse the client's request for an OAUTH2 access tokensTable
1546 *
1547 * Subsequent handlers will see `req.oauth2`, which looks like:
1548 * ```
1549 * {
1550 * oauth2: {accessToken: 'mF_9.B5f-4.1JqM&p=q'}
1551 * }
1552 * ```
1553 */
1554 function oauth2TokenParser(): RequestHandler;
1555
1556 interface RequestExpiryOptions {
1557 /**
1558 * Header name of the absolute time for request expiration
1559 */
1560 absoluteHeader?: string | undefined;
1561
1562 /**
1563 * Header name for the start time of the request
1564 */
1565 startHeader?: string | undefined;
1566
1567 /**
1568 * The header name for the time in milliseconds that should ellapse before the request is considered expired.
1569 */
1570 timeoutHeader?: string | undefined;
1571 }
1572
1573 /**
1574 * A request expiry will use headers to tell if the incoming request has expired or not.
1575 *
1576 * There are two options for this plugin:
1577 * 1. Absolute Time
1578 * * Time in Milliseconds since the Epoch when this request should be considered expired
1579 * 2. Timeout
1580 * * The request start time is supplied
1581 * * A timeout, in milliseconds, is given
1582 * * The timeout is added to the request start time to arrive at the absolute time
1583 * in which the request is considered expires
1584 */
1585 function requestExpiry(options?: RequestExpiryOptions): RequestHandler;
1586}
1587
1588export namespace pre {
1589 /**
1590 * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request.
1591 */
1592 function context(): RequestHandler;
1593
1594 function dedupeSlashes(): RequestHandler;
1595
1596 /**
1597 * This pre handler fixes issues with node hanging when an asyncHandler is used prior to bodyParser.
1598 */
1599 function pause(): RequestHandler;
1600
1601 /**
1602 * Cleans up duplicate or trailing / on the URL
1603 */
1604 function sanitizePath(): RequestHandler;
1605
1606 /**
1607 * Automatically reuse incoming request header as the request id.
1608 */
1609 function reqIdHeaders(options: { headers: string[] }): RequestHandler;
1610
1611 /**
1612 * Checks req.urls query params with strict key/val format and rejects non-strict requests with status code 400.
1613 */
1614 function strictQueryParams(options?: { message: string }): RequestHandler;
1615
1616 /**
1617 * Regexp to capture curl user-agents
1618 */
1619 function userAgentConnection(options?: { userAgentRegExp: any }): RequestHandler;
1620}