UNPKG

44.5 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 queryParser or bodyParser plugin is used with mapParams enabled. */
642 params?: any;
643
644 /** available when multipartBodyParser plugin is used. */
645 files?: { [name: string]: File | undefined; } | undefined;
646
647 /** available when authorizationParser plugin is used */
648 username?: string | undefined;
649
650 /** available when authorizationParser plugin is used */
651 authorization?: RequestAuthorization | undefined;
652}
653
654export interface CacheOptions {
655 maxAge: number;
656}
657
658export interface Response extends http.ServerResponse {
659 /**
660 * sets the cache-control header. `type` defaults to _public_,
661 * and options currently only takes maxAge.
662 * @param type value of the header
663 * @param [options] an options object
664 * @returns the value set to the header
665 */
666 cache(type: string, options?: CacheOptions): string;
667
668 /**
669 * sets the cache-control header. `type` defaults to _public_,
670 * and options currently only takes maxAge.
671 * @param [options] an options object
672 * @returns the value set to the header
673 */
674 cache(options?: CacheOptions): string;
675
676 /**
677 * turns off all cache related headers.
678 * @returns self, the response object
679 */
680 noCache(): Response;
681
682 /**
683 * Appends the provided character set to the response's Content-Type.
684 * e.g., res.charSet('utf-8');
685 * @param type char-set value
686 * @returns self, the response object
687 */
688 charSet(type: string): Response;
689
690 /**
691 * retrieves a header off the response.
692 * @param name the header name
693 */
694 get(name: string): string;
695
696 /**
697 * retrieves all headers off the response.
698 */
699 getHeaders(): any;
700
701 /**
702 * pass through to getHeaders.
703 */
704 headers(): any;
705
706 /**
707 * sets headers on the response.
708 * @param key the name of the header
709 * @param value the value of the header
710 */
711 header(key: string, value?: any): any;
712
713 /**
714 * short hand method for:
715 * res.contentType = 'json';
716 * res.send({hello: 'world'});
717 * @param code http status code
718 * @param body value to json.stringify
719 * @param [headers] headers to set on the response
720 */
721 json(code: number, body: any, headers?: { [header: string]: string }): any;
722
723 /**
724 * short hand method for:
725 * res.contentType = 'json';
726 * res.send({hello: 'world'});
727 * @param body value to json.stringify
728 * @param [headers] headers to set on the response
729 */
730 json(body: any, headers?: { [header: string]: string }): any;
731
732 /**
733 * sets the link heaader.
734 * @param key the link key
735 * @param value the link value
736 * @returns the header value set to res
737 */
738 link(key: string, value: string): string;
739
740 /**
741 * sends the response object. pass through to internal __send that uses a
742 * formatter based on the content-type header.
743 * @param [code] http status code
744 * @param [body] the content to send
745 * @param [headers] any add'l headers to set
746 * @returns the response object
747 */
748 send(code?: number, body?: any, headers?: { [header: string]: string }): any;
749
750 /**
751 * sends the response object. pass through to internal __send that uses a
752 * formatter based on the content-type header.
753 * @param [body] the content to send
754 * @param [headers] any add'l headers to set
755 * @returns the response object
756 */
757 send(body?: any, headers?: { [header: string]: string }): any;
758
759 /**
760 * sends the response object. pass through to internal __send that skips
761 * formatters entirely and sends the content as is.
762 * @param [code] http status code
763 * @param [body] the content to send
764 * @param [headers] any add'l headers to set
765 * @returns the response object
766 */
767 sendRaw(code?: number, body?: any, headers?: { [header: string]: string }): any;
768
769 /**
770 * sends the response object. pass through to internal __send that skips
771 * formatters entirely and sends the content as is.
772 * @param [body] the content to send
773 * @param [headers] any add'l headers to set
774 * @returns the response object
775 */
776 sendRaw(body?: any, headers?: { [header: string]: string }): any;
777
778 /**
779 * sets a header on the response.
780 * @param name name of the header
781 * @param val value of the header
782 * @returns self, the response object
783 */
784 set(name: string, val: string): Response;
785
786 /**
787 * sets a header on the response.
788 * @param val object of headers
789 * @returns self, the response object
790 */
791 set(headers?: { [header: string]: string }): Response;
792
793 /**
794 * sets the http status code on the response.
795 * @param code http status code
796 * @returns the status code passed in
797 */
798 status(code: number): number;
799
800 /**
801 * toString() serialization.
802 */
803 toString(): string;
804
805 /**
806 * redirect is sugar method for redirecting.
807 * res.redirect(301, 'www.foo.com', next);
808 * `next` is mandatory, to complete the response and trigger audit logger.
809 * @param code the status code
810 * @param url to redirect to
811 * @param next - mandatory, to complete the response and trigger audit logger
812 * @emits redirect
813 */
814 redirect(code: number, url: string, next: Next): void;
815
816 /**
817 * redirect is sugar method for redirecting.
818 * res.redirect({...}, next);
819 * `next` is mandatory, to complete the response and trigger audit logger.
820 * @param url to redirect to or options object to configure a redirect or
821 * @param next - mandatory, to complete the response and trigger audit logger
822 * @emits redirect
823 */
824 redirect(opts: string | RedirectOptions, next: Next): void;
825
826 /** HTTP status code. */
827 code: number;
828
829 /** short hand for the header content-length. */
830 contentLength: number;
831
832 /** short hand for the header content-type. */
833 contentType: string;
834
835 /** A unique request id (x-request-id). */
836 id: string;
837}
838
839export interface RedirectOptions {
840 /**
841 * whether to redirect to http or https
842 */
843 secure?: boolean | undefined;
844
845 /**
846 * redirect location's hostname
847 */
848 hostname?: string | undefined;
849
850 /**
851 * redirect location's pathname
852 */
853 pathname?: string | undefined;
854
855 /**
856 * redirect location's port number
857 */
858 port?: string | undefined;
859
860 /**
861 * redirect location's query string parameters
862 */
863 query?: string|object | undefined;
864
865 /**
866 * if true, `options.query`
867 * stomps over any existing query
868 * parameters on current URL.
869 * by default, will merge the two.
870 */
871 overrideQuery?: boolean | undefined;
872
873 /**
874 * if true, sets 301. defaults to 302.
875 */
876 permanent?: boolean | undefined;
877}
878
879export interface Next {
880 (err?: any): void;
881}
882
883export interface RouteSpec {
884 method: string;
885 name?: string | undefined;
886 path: string | RegExp;
887 versions?: string[] | undefined;
888}
889
890export interface Route {
891 name: string;
892 method: string;
893 path: string | RegExp;
894 spec: RouteSpec;
895 chain: Chain;
896}
897
898export interface RouteOptions {
899 name?: string | undefined;
900
901 path?: string | RegExp | undefined;
902
903 url?: string | RegExp | undefined;
904
905 urlParamPattern?: RegExp | undefined;
906
907 contentType?: string | string[] | undefined;
908
909 version?: string | undefined;
910
911 versions?: string[] | undefined;
912}
913
914export interface MountOptions {
915 name: string;
916
917 method: string;
918
919 path?: string | RegExp | undefined;
920
921 url?: string | RegExp | undefined;
922
923 urlParamPattern?: RegExp | undefined;
924
925 contentType?: string | string[] | undefined;
926
927 version?: string | undefined;
928
929 versions?: string[] | undefined;
930}
931
932export type FindRouteCallback = (err: Error, route?: Route, params?: any) => void;
933
934export type RequestHandler = (req: Request, res: Response, next: Next) => any;
935export type RequestHandlerType = RequestHandler | RequestHandler[];
936
937export interface ServerUpgradeResponse {
938 /**
939 * Set the status code of the response.
940 * @param code - the http status code
941 */
942 status(code: number): number;
943
944 /**
945 * Sends the response.
946 * @param code - the http status code
947 * @param body - the response to send out
948 */
949 send(code: number, body: any): any;
950
951 /**
952 * Sends the response.
953 * @param body - the response to send out
954 */
955 send(body: any): boolean;
956
957 /**
958 * Ends the response
959 */
960 end(): boolean;
961
962 /**
963 * Write to the response.
964 */
965 write(): boolean;
966
967 /**
968 * Write to the head of the response.
969 * @param statusCode - the http status code
970 * @param reason - a message
971 */
972 writeHead(statusCode: number, reason?: string): void;
973
974 /**
975 * Attempt to upgrade.
976 */
977 claimUpgrade(): any;
978}
979
980export namespace bunyan {
981 interface RequestCaptureOptions {
982 /** The stream to which to write when dumping captured records. */
983 stream?: Logger.Stream | undefined;
984
985 /** The streams to which to write when dumping captured records. */
986 streams?: ReadonlyArray<Logger.Stream> | undefined;
987
988 /**
989 * The level at which to trigger dumping captured records. Defaults to
990 * bunyan.WARN.
991 */
992 level?: Logger.LogLevel | undefined;
993
994 /** Number of records to capture. Default 100. */
995 maxRecords?: number | undefined;
996
997 /**
998 * Number of simultaneous request id capturing buckets to maintain.
999 * Default 1000.
1000 */
1001 maxRequestIds?: number | undefined;
1002
1003 /**
1004 * If true, then dump captured records on the *default* request id when
1005 * dumping. I.e. dump records logged without "req_id" field. Default
1006 * false.
1007 */
1008 dumpDefault?: boolean | undefined;
1009 }
1010
1011 /**
1012 * A Bunyan stream to capture records in a ring buffer and only pass through
1013 * on a higher-level record. E.g. buffer up all records but only dump when
1014 * getting a WARN or above.
1015 */
1016 class RequestCaptureStream extends stream.Stream {
1017 constructor(opts: RequestCaptureOptions);
1018
1019 /** write to the stream */
1020 write(record: any): void;
1021 }
1022
1023 const serializers: Logger.Serializers & {
1024 err: Logger.Serializer,
1025 req: Logger.Serializer,
1026 res: Logger.Serializer,
1027 client_req: Logger.Serializer,
1028 client_res: Logger.Serializer
1029 };
1030
1031 /** create a bunyan logger */
1032 function createLogger(name: string): Logger;
1033}
1034
1035export function createServer(options?: ServerOptions): Server;
1036
1037export type Formatter = (req: Request, res: Response, body: any) => string | Buffer | null;
1038
1039export interface Formatters {
1040 [contentType: string]: Formatter;
1041}
1042
1043export const formatters: Formatters;
1044
1045export namespace plugins {
1046 namespace pre {
1047 /**
1048 * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request.
1049 */
1050 function context(): RequestHandler;
1051
1052 function dedupeSlashes(): RequestHandler;
1053
1054 /**
1055 * This pre handler fixes issues with node hanging when an asyncHandler is used prior to bodyParser.
1056 */
1057 function pause(): RequestHandler;
1058
1059 /**
1060 * Cleans up duplicate or trailing / on the URL
1061 */
1062 function sanitizePath(): RequestHandler;
1063
1064 /**
1065 * Automatically reuse incoming request header as the request id.
1066 */
1067 function reqIdHeaders(options: { headers: string[] }): RequestHandler;
1068
1069 /**
1070 * Checks req.urls query params with strict key/val format and rejects non-strict requests with status code 400.
1071 */
1072 function strictQueryParams(options?: { message: string }): RequestHandler;
1073
1074 /**
1075 * Regexp to capture curl user-agents
1076 */
1077 function userAgentConnection(options?: {
1078 userAgentRegExp: any;
1079 }): RequestHandler;
1080 }
1081
1082 // *************** This module includes the following header parser plugins:
1083
1084 /**
1085 * Check the client's Accept header can be handled by this server.
1086 */
1087 function acceptParser(accepts: string[]): RequestHandler;
1088
1089 type AuditLoggerContext = (
1090 req: Request,
1091 res: Response,
1092 route: any,
1093 error: any,
1094 ) => any;
1095
1096 interface AuditLoggerOptions {
1097 /**
1098 * Bunyan logger
1099 */
1100 log: Logger;
1101
1102 /**
1103 * The event from the server which initiates the
1104 * log, one of 'pre', 'routed', or 'after'
1105 */
1106 event: 'pre' | 'routed' | 'after';
1107
1108 /**
1109 * Restify server. If passed in, causes server to emit 'auditlog' event after audit logs are flushed
1110 */
1111 server?: Server | undefined;
1112
1113 /**
1114 * The optional context function of signature
1115 * f(req, res, route, err). Invoked each time an audit log is generated. This
1116 * function can return an object that customizes the format of anything off the
1117 * req, res, route, and err objects. The output of this function will be
1118 * available on the `context` key in the audit object.
1119 */
1120 context?: AuditLoggerContext | undefined;
1121
1122 /**
1123 * Ringbuffer which is written to if passed in
1124 */
1125 logBuffer?: any;
1126
1127 /**
1128 * When true, prints audit logs. default true.
1129 */
1130 printLog?: boolean | undefined;
1131
1132 body?: boolean | undefined;
1133 }
1134
1135 /**
1136 * An audit logger for recording all handled requests
1137 */
1138 function auditLogger(options: AuditLoggerOptions): (...args: any[]) => void;
1139
1140 /**
1141 * Authorization header
1142 */
1143 function authorizationParser(options?: any): RequestHandler;
1144
1145 interface HandlerCandidate {
1146 handler: RequestHandler | RequestHandler[];
1147 version?: string | string[] | undefined;
1148 contentType?: string | string[] | undefined;
1149 }
1150
1151 /**
1152 * Runs first handler that matches to the condition
1153 */
1154 function conditionalHandler(
1155 candidates: HandlerCandidate | HandlerCandidate[],
1156 ): RequestHandler;
1157
1158 /**
1159 * Conditional headers (If-*)
1160 */
1161 function conditionalRequest(): RequestHandler[];
1162
1163 interface CpuUsageThrottleOptions {
1164 limit?: number | undefined;
1165 max?: number | undefined;
1166 interval?: number | undefined;
1167 halfLife?: number | undefined;
1168 }
1169
1170 /**
1171 * Cpu Throttle middleware
1172 */
1173 function cpuUsageThrottle(opts?: CpuUsageThrottleOptions): RequestHandler;
1174
1175 /**
1176 * Handles disappeared CORS headers
1177 */
1178 function fullResponse(): RequestHandler;
1179
1180 // ************ This module includes the following data parsing plugins:
1181
1182 interface BodyParserOptions {
1183 /**
1184 * The maximum size in bytes allowed in the HTTP body. Useful for limiting clients from hogging server memory.
1185 */
1186 maxBodySize?: number | undefined;
1187
1188 /**
1189 * If req.params should be filled with parsed parameters from HTTP body.
1190 */
1191 mapParams?: boolean | undefined;
1192
1193 /**
1194 * If req.params should be filled with the contents of files sent through a multipart request.
1195 * Formidable is used internally for parsing, and a file is denoted as a multipart part with the filename option set in its Content-Disposition.
1196 * This will only be performed if mapParams is true.
1197 */
1198 mapFiles?: boolean | undefined;
1199
1200 /**
1201 * If an entry in req.params should be overwritten by the value in the body if the names are the same.
1202 * 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,
1203 * the value will be happy if overrideParams is true, sad otherwise.
1204 */
1205 overrideParams?: boolean | undefined;
1206
1207 /**
1208 * A callback to handle any multipart part which is not a file.
1209 * 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.
1210 */
1211 multipartHandler?(): void;
1212
1213 /**
1214 * A callback to handle any multipart file.
1215 * It will be a file if the part have a Content-Disposition with the filename parameter set.
1216 * This typically happens when a browser sends a form and there is a parameter similar to <input type="file" />.
1217 * If this is not provided, the default behaviour is to map the contents into req.params.
1218 */
1219 multipartFileHandler?(): void;
1220
1221 /**
1222 * If you want the uploaded files to include the extensions of the original files (multipart uploads only). Does nothing if multipartFileHandler is defined.
1223 */
1224 keepExtensions?: boolean | undefined;
1225
1226 /**
1227 * Where uploaded files are intermediately stored during transfer before the contents is mapped into req.params. Does nothing if multipartFileHandler is defined.
1228 */
1229 uploadDir?: string | undefined;
1230
1231 /**
1232 * If you want to support html5 multiple attribute in upload fields.
1233 */
1234 multiples?: boolean | undefined;
1235
1236 /**
1237 * If you want checksums calculated for incoming files, set this to either sha1 or md5.
1238 */
1239 hash?: string | undefined;
1240
1241 /**
1242 * Set to true if you want to end the request with a UnsupportedMediaTypeError when none of the supported content types was given.
1243 */
1244 rejectUnknown?: boolean | undefined;
1245
1246 requestBodyOnGet?: boolean | undefined;
1247
1248 reviver?: any;
1249
1250 maxFieldsSize?: number | undefined;
1251
1252 maxFileSize?: number | undefined;
1253 }
1254
1255 /**
1256 * Parses POST bodies to req.body. automatically uses one of the following parsers based on content type.
1257 */
1258 function bodyParser(options?: BodyParserOptions): RequestHandler[];
1259
1260 /**
1261 * Reads the body of the request.
1262 */
1263 function bodyReader(options?: { maxBodySize?: number | undefined }): RequestHandler;
1264
1265 interface UrlEncodedBodyParserOptions {
1266 mapParams?: boolean | undefined;
1267 overrideParams?: boolean | undefined;
1268 bodyReader?: boolean | undefined;
1269 }
1270
1271 /**
1272 * Parse the HTTP request body IFF the contentType is application/x-www-form-urlencoded.
1273 *
1274 * If req.params already contains a given key, that key is skipped and an
1275 * error is logged.
1276 */
1277 function urlEncodedBodyParser(
1278 options?: UrlEncodedBodyParserOptions,
1279 ): RequestHandler[];
1280
1281 interface JsonBodyParserOptions {
1282 mapParams?: boolean | undefined;
1283 overrideParams?: boolean | undefined;
1284 reviver?(key: any, value: any): any;
1285 bodyReader?: boolean | undefined;
1286 }
1287
1288 /**
1289 * Parses JSON POST bodies
1290 */
1291 function jsonBodyParser(options?: JsonBodyParserOptions): RequestHandler[];
1292
1293 /**
1294 * Parses JSONP callback
1295 */
1296 function jsonp(): RequestHandler;
1297
1298 interface MultipartBodyParser {
1299 overrideParams?: boolean | undefined;
1300 multiples?: boolean | undefined;
1301 keepExtensions?: boolean | undefined;
1302 uploadDir?: string | undefined;
1303 maxFieldsSize?: number | undefined;
1304 hash?: string | undefined;
1305 multipartFileHandler?: any;
1306 multipartHandler?: any;
1307 mapParams?: boolean | undefined;
1308 mapFiles?: boolean | undefined;
1309 maxFileSize?: number | undefined;
1310 }
1311
1312 /**
1313 * Parses JSONP callback
1314 */
1315 function multipartBodyParser(options?: MultipartBodyParser): RequestHandler;
1316
1317 interface QueryParserOptions {
1318 /**
1319 * Default `false`. Copies parsed query parameters into `req.params`.
1320 */
1321 mapParams?: boolean | undefined;
1322
1323 /**
1324 * Default `false`. Only applies when if mapParams true. When true, will stomp on req.params field when existing value is found.
1325 */
1326 overrideParams?: boolean | undefined;
1327
1328 /**
1329 * Default false. Transform `?foo.bar=baz` to a nested object: `{foo: {bar: 'baz'}}`.
1330 */
1331 allowDots?: boolean | undefined;
1332
1333 /**
1334 * Default 20. Only transform `?a[$index]=b` to an array if `$index` is less than `arrayLimit`.
1335 */
1336 arrayLimit?: number | undefined;
1337
1338 /**
1339 * Default 5. The depth limit for parsing nested objects, e.g. `?a[b][c][d][e][f][g][h][i]=j`.
1340 */
1341 depth?: number | undefined;
1342
1343 /**
1344 * Default 1000. Maximum number of query params parsed. Additional params are silently dropped.
1345 */
1346 parameterLimit?: number | undefined;
1347
1348 /**
1349 * Default true. Whether to parse `?a[]=b&a[1]=c` to an array, e.g. `{a: ['b', 'c']}`.
1350 */
1351 parseArrays?: boolean | undefined;
1352
1353 /**
1354 * Default false. Whether `req.query` is a "plain" object -- does not inherit from `Object`.
1355 * This can be used to allow query params whose names collide with Object methods, e.g. `?hasOwnProperty=blah`.
1356 */
1357 plainObjects?: boolean | undefined;
1358
1359 /**
1360 * Default false. If true, `?a&b=` results in `{a: null, b: ''}`. Otherwise, `{a: '', b: ''}`.
1361 */
1362 strictNullHandling?: boolean | undefined;
1363 }
1364
1365 /**
1366 * Parses URL query parameters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs)
1367 */
1368 function queryParser(options?: QueryParserOptions): RequestHandler;
1369
1370 interface RequestLogger {
1371 properties?: any;
1372 serializers?: any;
1373 headers?: any;
1374 log?: any;
1375 }
1376
1377 /**
1378 * Adds timers for each handler in your request chain
1379 *
1380 * `options.properties` properties to pass to bunyan's `log.child()` method
1381 */
1382 function requestLogger(options?: RequestLogger): RequestHandler;
1383
1384 // ******************** The module includes the following response plugins:
1385
1386 /**
1387 * expires requests based on current time + delta
1388 * @param delta - age in seconds
1389 */
1390 function dateParser(delta?: number): RequestHandler;
1391
1392 /**
1393 * gzips the response if client send `accept-encoding: gzip`
1394 * @param options options to pass to gzlib
1395 */
1396 function gzipResponse(options?: zlib.ZlibOptions): RequestHandler;
1397
1398 interface InflightRequestThrottleOptions {
1399 limit: number;
1400 server: Server;
1401 err: any;
1402 }
1403
1404 function inflightRequestThrottle(
1405 opts: InflightRequestThrottleOptions,
1406 ): RequestHandler;
1407
1408 interface ServeStatic {
1409 appendRequestPath?: boolean | undefined;
1410 directory?: string | undefined;
1411 maxAge?: number | undefined;
1412 match?: any;
1413 charSet?: string | undefined;
1414 file?: string | undefined;
1415 etag?: string | undefined;
1416 default?: any;
1417 gzip?: boolean | undefined;
1418 }
1419
1420 /**
1421 * Used to serve static files
1422 */
1423 function serveStatic(options?: ServeStatic): RequestHandler;
1424
1425 interface ServeStaticFiles {
1426 maxAge?: number | undefined;
1427 etag?: string | undefined;
1428 setHeaders?: ((res: Response, path: string, stat: any) => any) | undefined;
1429 }
1430
1431 /**
1432 * Used to serve static files from a given directory
1433 */
1434 function serveStaticFiles(
1435 dir: string,
1436 options?: ServeStaticFiles,
1437 ): RequestHandler;
1438
1439 interface ThrottleOptions {
1440 burst?: number | undefined;
1441 rate?: number | undefined;
1442 setHeaders?: boolean | undefined;
1443 ip?: boolean | undefined;
1444 username?: boolean | undefined;
1445 xff?: boolean | undefined;
1446 tokensTable?: any;
1447 maxKeys?: number | undefined;
1448 overrides?: any; // any
1449 }
1450
1451 /**
1452 * throttles responses
1453 */
1454 function throttle(options?: ThrottleOptions): RequestHandler;
1455
1456 type MetricsCallback = (
1457 /**
1458 * An error if the request had an error
1459 */
1460 err: Error,
1461
1462 /**
1463 * Object that contains the various metrics that are returned
1464 */
1465 metrics: MetricsCallbackOptions,
1466
1467 /**
1468 * The request obj
1469 */
1470 req: Request,
1471
1472 /**
1473 * The response obj
1474 */
1475 res: Response,
1476
1477 /**
1478 * The route obj that serviced the request
1479 */
1480 route: Route,
1481 ) => void;
1482
1483 type TMetricsCallback = 'close' | 'aborted' | undefined;
1484
1485 interface MetricsCallbackOptions {
1486 /**
1487 * Status code of the response. Can be undefined in the case of an `uncaughtException`.
1488 * Otherwise, in most normal scenarios, even calling `res.send()` or `res.end()` should result in a 200 by default.
1489 */
1490 statusCode: number;
1491
1492 /**
1493 * HTTP request verb
1494 */
1495 method: string;
1496
1497 /**
1498 * latency includes both request is flushed and all handlers finished
1499 */
1500 totalLatency: number;
1501
1502 /**
1503 * Request latency
1504 */
1505 latency: number;
1506
1507 /**
1508 * pre handlers latency
1509 */
1510 preLatency: number | null;
1511
1512 /**
1513 * use handlers latency
1514 */
1515 useLatency: number | null;
1516
1517 /**
1518 * req.path() value
1519 */
1520 path: string;
1521
1522 /**
1523 * Number of inflight requests pending in restify
1524 */
1525 inflightRequests: number;
1526
1527 /**
1528 * Same as `inflightRequests`
1529 */
1530 unfinishedRequests: number;
1531
1532 /**
1533 * If this value is set, err will be a corresponding `RequestCloseError` or `RequestAbortedError`.
1534 *
1535 * If connectionState is either 'close' or 'aborted', then the statusCode is not applicable since the connection was severed before a response was written.
1536 */
1537 connectionState: TMetricsCallback;
1538 }
1539
1540 /**
1541 * Listens to the server's after event and emits information about that request (5.x compatible only).
1542 *
1543 * ```
1544 * server.on('after', plugins.metrics({ server }, (err, metrics, req, res, route) =>
1545 * {
1546 * // metrics is an object containing information about the request
1547 * }));
1548 * ```
1549 */
1550 function metrics(
1551 opts: { server: Server },
1552 callback: MetricsCallback,
1553 ): (...args: any[]) => void;
1554
1555 /**
1556 * Parse the client's request for an OAUTH2 access tokensTable
1557 *
1558 * Subsequent handlers will see `req.oauth2`, which looks like:
1559 * ```
1560 * {
1561 * oauth2: {accessToken: 'mF_9.B5f-4.1JqM&p=q'}
1562 * }
1563 * ```
1564 */
1565 function oauth2TokenParser(): RequestHandler;
1566
1567 interface RequestExpiryOptions {
1568 /**
1569 * Header name of the absolute time for request expiration
1570 */
1571 absoluteHeader?: string | undefined;
1572
1573 /**
1574 * Header name for the start time of the request
1575 */
1576 startHeader?: string | undefined;
1577
1578 /**
1579 * The header name for the time in milliseconds that should ellapse before the request is considered expired.
1580 */
1581 timeoutHeader?: string | undefined;
1582 }
1583
1584 /**
1585 * A request expiry will use headers to tell if the incoming request has expired or not.
1586 *
1587 * There are two options for this plugin:
1588 * 1. Absolute Time
1589 * * Time in Milliseconds since the Epoch when this request should be considered expired
1590 * 2. Timeout
1591 * * The request start time is supplied
1592 * * A timeout, in milliseconds, is given
1593 * * The timeout is added to the request start time to arrive at the absolute time
1594 * in which the request is considered expires
1595 */
1596 function requestExpiry(options?: RequestExpiryOptions): RequestHandler;
1597}
1598
1599export namespace pre {
1600 /**
1601 * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request.
1602 */
1603 function context(): RequestHandler;
1604
1605 function dedupeSlashes(): RequestHandler;
1606
1607 /**
1608 * This pre handler fixes issues with node hanging when an asyncHandler is used prior to bodyParser.
1609 */
1610 function pause(): RequestHandler;
1611
1612 /**
1613 * Cleans up duplicate or trailing / on the URL
1614 */
1615 function sanitizePath(): RequestHandler;
1616
1617 /**
1618 * Automatically reuse incoming request header as the request id.
1619 */
1620 function reqIdHeaders(options: { headers: string[] }): RequestHandler;
1621
1622 /**
1623 * Checks req.urls query params with strict key/val format and rejects non-strict requests with status code 400.
1624 */
1625 function strictQueryParams(options?: { message: string }): RequestHandler;
1626
1627 /**
1628 * Regexp to capture curl user-agents
1629 */
1630 function userAgentConnection(options?: { userAgentRegExp: any }): RequestHandler;
1631}