UNPKG

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