UNPKG

226 kBTypeScriptView Raw
1// Type definitions for hapi 18.0
2// Project: https://github.com/hapijs/hapi, https://hapijs.com
3// Definitions by: Rafael Souza Fijalkowski <https://github.com/rafaelsouzaf>
4// Justin Simms <https://github.com/jhsimms>
5// Simon Schick <https://github.com/SimonSchick>
6// Rodrigo Saboya <https://github.com/saboya>
7// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
8// TypeScript Version: 2.8
9
10/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
11 + +
12 + +
13 + +
14 + WARNING: BACKWARDS INCOMPATIBLE +
15 + +
16 + +
17 + +
18 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
19
20/// <reference types='node' />
21
22import * as Boom from 'boom';
23import * as http from 'http';
24import * as https from 'https';
25import * as Shot from 'shot';
26import * as stream from 'stream';
27import * as url from 'url';
28import * as zlib from 'zlib';
29
30import { MimosOptions } from 'mimos';
31import { SealOptions, SealOptionsSub } from 'iron';
32import { ValidationOptions, SchemaMap, Schema } from 'joi';
33import Podium = require('podium');
34import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePrototype, Policy, ClientApi, ClientOptions } from 'catbox';
35
36/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
37 + +
38 + +
39 + +
40 + Plugin +
41 + +
42 + +
43 + +
44 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
45
46/**
47 * one of
48 * a single plugin name string.
49 * an array of plugin name strings.
50 * an object where each key is a plugin name and each matching value is a
51 * {@link https://www.npmjs.com/package/semver version range string} which must match the registered
52 * plugin version.
53 */
54export type Dependencies = string | string[] | {
55 [key: string]: string;
56};
57
58/**
59 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
60 */
61
62/* tslint:disable-next-line:no-empty-interface */
63export interface PluginsListRegistered {
64}
65
66/**
67 * An object of the currently registered plugins where each key is a registered plugin name and the value is an
68 * object containing:
69 * * version - the plugin version.
70 * * name - the plugin name.
71 * * options - (optional) options passed to the plugin during registration.
72 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
73 */
74export interface PluginRegistered {
75 /**
76 * the plugin version.
77 */
78 version: string;
79
80 /**
81 * the plugin name.
82 */
83 name: string;
84
85 /**
86 * options used to register the plugin.
87 */
88 options: object;
89}
90
91/* tslint:disable-next-line:no-empty-interface */
92export interface PluginsStates {
93}
94
95/* tslint:disable-next-line:no-empty-interface */
96export interface PluginSpecificConfiguration {
97}
98
99export interface PluginNameVersion {
100 /**
101 * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm
102 * registry) should use the same name as the name field in their 'package.json' file. Names must be
103 * unique within each application.
104 */
105 name: string;
106
107 /**
108 * optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's
109 * 'package.json' file.
110 */
111 version?: string | undefined;
112}
113
114export interface PluginPackage {
115 /**
116 * Alternatively, the name and version can be included via the pkg property containing the 'package.json' file for the module which already has the name and version included
117 */
118 pkg: any;
119}
120
121/**
122 * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each
123 * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox
124 * certain properties. For example, setting a file path in one plugin doesn't affect the file path set
125 * in another plugin.
126 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins)
127 *
128 * The type T is the type of the plugin options.
129 */
130export interface PluginBase<T> {
131 /**
132 * (required) the registration function with the signature async function(server, options) where:
133 * * server - the server object with a plugin-specific server.realm.
134 * * options - any options passed to the plugin during registration via server.register().
135 */
136 register: (server: Server, options: T) => void | Promise<void>;
137
138 /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */
139 multiple?: boolean | undefined;
140
141 /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */
142 dependencies?: Dependencies | undefined;
143
144 /**
145 * Allows defining semver requirements for node and hapi.
146 * @default Allows all.
147 */
148 requirements?: {
149 node?: string | undefined;
150 hapi?: string | undefined;
151 } | undefined;
152
153 /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */
154 once?: boolean | undefined;
155}
156
157export type Plugin<T> = PluginBase<T> & (PluginNameVersion | PluginPackage);
158
159/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
160 + +
161 + +
162 + +
163 + Request +
164 + +
165 + +
166 + +
167 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
168
169/**
170 * User extensible types user credentials.
171 */
172// tslint:disable-next-line:no-empty-interface
173export interface UserCredentials {
174}
175
176/**
177 * User extensible types app credentials.
178 */
179// tslint:disable-next-line:no-empty-interface
180export interface AppCredentials {
181}
182
183/**
184 * User-extensible type for request.auth credentials.
185 */
186export interface AuthCredentials {
187 /**
188 * The application scopes to be granted.
189 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope)
190 */
191 scope?: string[] | undefined;
192 /**
193 * If set, will only work with routes that set `access.entity` to `user`.
194 */
195 user?: UserCredentials | undefined;
196
197 /**
198 * If set, will only work with routes that set `access.entity` to `app`.
199 */
200 app?: AppCredentials | undefined;
201}
202
203/**
204 * Authentication information:
205 * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions.
206 * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication.
207 * * error - the authentication error is failed and mode set to 'try'.
208 * * isAuthenticated - true if the request has been successfully authenticated, otherwise false.
209 * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed
210 * authorization, set to false.
211 * * mode - the route authentication mode.
212 * * strategy - the name of the strategy used.
213 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth)
214 */
215export interface RequestAuth {
216 /** an artifact object received from the authentication strategy and used in authentication-related actions. */
217 artifacts: object;
218 /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */
219 credentials: AuthCredentials;
220 /** the authentication error is failed and mode set to 'try'. */
221 error: Error;
222 /** true if the request has been successfully authenticated, otherwise false. */
223 isAuthenticated: boolean;
224 /**
225 * true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization,
226 * set to false.
227 */
228 isAuthorized: boolean;
229 /** the route authentication mode. */
230 mode: string;
231 /** the name of the strategy used. */
232 strategy: string;
233}
234
235/**
236 * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
237 * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
238 * 'disconnect' - emitted when a request errors or aborts unexpectedly.
239 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
240 */
241export type RequestEventType = 'peek' | 'finish' | 'disconnect';
242
243/**
244 * Access: read only and the public podium interface.
245 * The request.events supports the following events:
246 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
247 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
248 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
249 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
250 */
251export interface RequestEvents extends Podium {
252 /**
253 * Access: read only and the public podium interface.
254 * The request.events supports the following events:
255 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
256 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
257 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
258 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
259 */
260 on(criteria: 'peek', listener: PeekListener): void;
261
262 on(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void;
263
264 /**
265 * Access: read only and the public podium interface.
266 * The request.events supports the following events:
267 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
268 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
269 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
270 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
271 */
272 once(criteria: 'peek', listener: PeekListener): void;
273
274 once(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void;
275}
276
277/**
278 * Request information:
279 * * acceptEncoding - the request preferred encoding.
280 * * cors - if CORS is enabled for the route, contains the following:
281 * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only
282 * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle.
283 * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080').
284 * * hostname - the hostname part of the 'Host' header (e.g. 'example.com').
285 * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').
286 * * received - request reception timestamp.
287 * * referrer - content of the HTTP 'Referrer' (or 'Referer') header.
288 * * remoteAddress - remote client IP address.
289 * * remotePort - remote client port.
290 * * responded - request response timestamp (0 is not responded yet).
291 * Note that the request.info object is not meant to be modified.
292 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo)
293 */
294export interface RequestInfo {
295 /** the request preferred encoding. */
296 acceptEncoding: string;
297 /** if CORS is enabled for the route, contains the following: */
298 cors: {
299 /**
300 * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after
301 * the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle.
302 */
303 isOriginMatch?: boolean | undefined;
304 };
305 /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */
306 host: string;
307 /** the hostname part of the 'Host' header (e.g. 'example.com'). */
308 hostname: string;
309 /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}') */
310 id: string;
311 /** request reception timestamp. */
312 received: number;
313 /** content of the HTTP 'Referrer' (or 'Referer') header. */
314 referrer: string;
315 /** remote client IP address. */
316 remoteAddress: string;
317 /** remote client port. */
318 remotePort: string;
319 /** request response timestamp (0 is not responded yet). */
320 responded: number;
321 /** request processing completion timestamp (0 is still processing). */
322 completed: number;
323}
324
325/**
326 * The request route information object, where:
327 * * method - the route HTTP method.
328 * * path - the route path.
329 * * vhost - the route vhost option if configured.
330 * * realm - the active realm associated with the route.
331 * * settings - the route options object with all defaults applied.
332 * * fingerprint - the route internal normalized string representing the normalized path.
333 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute)
334 */
335export interface RequestRoute {
336 /** the route HTTP method. */
337 method: Util.HTTP_METHODS_PARTIAL;
338
339 /** the route path. */
340 path: string;
341
342 /** the route vhost option if configured. */
343 vhost?: string | string[] | undefined;
344
345 /** the active realm associated with the route. */
346 realm: ServerRealm;
347
348 /** the route options object with all defaults applied. */
349 settings: RouteOptions;
350
351 /** the route internal normalized string representing the normalized path. */
352 fingerprint: string;
353
354 auth: {
355 /**
356 * Validates a request against the route's authentication access configuration, where:
357 * @param request - the request object.
358 * @return Return value: true if the request would have passed the route's access requirements.
359 * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access
360 * configuration. If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may
361 * not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route
362 * requires any authentication.
363 * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest)
364 */
365 access(request: Request): boolean;
366 };
367}
368
369/**
370 * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.
371 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig)
372 */
373export interface RequestOrig {
374 params: object;
375 query: object;
376 payload: object;
377}
378
379export interface RequestLog {
380 request: string;
381 timestamp: number;
382 tags: string[];
383 data: string | object;
384 channel: string;
385}
386
387export interface RequestQuery {
388 [key: string]: string | string[];
389}
390
391/**
392 * The request object is created internally for each incoming request. It is not the same object received from the node
393 * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout
394 * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle).
395 */
396export interface Request extends Podium {
397 /**
398 * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].
399 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp)
400 */
401 app: ApplicationState;
402
403 /**
404 * Authentication information:
405 * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions.
406 * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication.
407 * * error - the authentication error is failed and mode set to 'try'.
408 * * isAuthenticated - true if the request has been successfully authenticated, otherwise false.
409 * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed
410 * authorization, set to false.
411 * * mode - the route authentication mode.
412 * * strategy - the name of the strategy used.
413 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth)
414 */
415 readonly auth: RequestAuth;
416
417 /**
418 * Access: read only and the public podium interface.
419 * The request.events supports the following events:
420 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
421 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
422 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
423 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
424 */
425 events: RequestEvents;
426
427 /**
428 * The raw request headers (references request.raw.req.headers).
429 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders)
430 */
431 readonly headers: Util.Dictionary<string>;
432
433 /**
434 * Request information:
435 * * acceptEncoding - the request preferred encoding.
436 * * cors - if CORS is enabled for the route, contains the following:
437 * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only
438 * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle.
439 * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080').
440 * * hostname - the hostname part of the 'Host' header (e.g. 'example.com').
441 * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').
442 * * received - request reception timestamp.
443 * * referrer - content of the HTTP 'Referrer' (or 'Referer') header.
444 * * remoteAddress - remote client IP address.
445 * * remotePort - remote client port.
446 * * responded - request response timestamp (0 is not responded yet).
447 * Note that the request.info object is not meant to be modified.
448 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo)
449 */
450 readonly info: RequestInfo;
451
452 /**
453 * An array containing the logged request events.
454 * Note that this array will be empty if route log.collect is set to false.
455 */
456 readonly logs: RequestLog[];
457
458 /**
459 * The request method in lower case (e.g. 'get', 'post').
460 */
461 readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE;
462
463 /**
464 * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred.
465 */
466 readonly mime: string;
467
468 /**
469 * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.
470 */
471 readonly orig: RequestOrig;
472
473 /**
474 * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters).
475 */
476 readonly params: Util.Dictionary<string>;
477
478 /**
479 * An array containing all the path params values in the order they appeared in the path.
480 */
481 readonly paramsArray: string[];
482
483 /**
484 * The request URI's pathname component.
485 */
486 readonly path: string;
487
488 /**
489 * The request payload based on the route payload.output and payload.parse settings.
490 * TODO check this typing and add references / links.
491 */
492 readonly payload: stream.Readable | Buffer | string | object;
493
494 /**
495 * Plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.
496 */
497 plugins: PluginsStates;
498
499 /**
500 * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response
501 * object, use responses.
502 */
503 readonly pre: Util.Dictionary<any>;
504
505 /**
506 * Access: read / write (see limitations below).
507 * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to
508 * override with a different response.
509 * In case of an aborted request the status code will be set to `disconnectStatusCode`.
510 */
511 response: ResponseObject | Boom;
512
513 /**
514 * Same as pre but represented as the response object created by the pre method.
515 */
516 readonly preResponses: Util.Dictionary<any>;
517
518 /**
519 * By default the object outputted from node's URL parse() method.
520 */
521 readonly query: RequestQuery;
522
523 /**
524 * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.
525 * * req - the node request object.
526 * * res - the node response object.
527 */
528 readonly raw: {
529 req: http.IncomingMessage;
530 res: http.ServerResponse;
531 };
532
533 /**
534 * The request route information object and method
535 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute)
536 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest)
537 */
538 readonly route: RequestRoute;
539
540 /**
541 * Access: read only and the public server interface.
542 * The server object.
543 */
544 server: Server;
545
546 /**
547 * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition.
548 */
549 readonly state: Util.Dictionary<any>;
550
551 /**
552 * The parsed request URI.
553 */
554 readonly url: url.URL;
555
556 /**
557 * Returns `true` when the request is active and processing should continue and `false` when the
558 * request terminated early or completed its lifecycle. Useful when request processing is a
559 * resource-intensive operation and should be terminated early if the request is no longer active
560 * (e.g. client disconnected or aborted early).
561 */
562 active(): boolean;
563
564 /**
565 * Returns a response which you can pass into the reply interface where:
566 * @param source - the value to set as the source of the reply interface, optional.
567 * @param options - options for the method, optional.
568 * @return ResponseObject
569 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options)
570 */
571 /* tslint:disable-next-line:max-line-length */
572 generateResponse(source: string | object | null, options?: { variety?: string | undefined; prepare?: ((response: ResponseObject) => Promise<ResponseObject>) | undefined; marshal?: ((response: ResponseObject) => Promise<ResponseValue>) | undefined; close?: ((response: ResponseObject) => void) | undefined; }): ResponseObject;
573
574 /**
575 * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are:
576 * @param tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism
577 * for describing and filtering events.
578 * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return
579 * value) the actual data emitted to the listeners. Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag
580 * set to true.
581 * @return void
582 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data)
583 */
584 log(tags: string | string[], data?: string | object | (() => string | object)): void;
585
586 /**
587 * Changes the request method before the router begins processing the request where:
588 * @param method - is the request HTTP method (e.g. 'GET').
589 * @return void
590 * Can only be called from an 'onRequest' extension method.
591 * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod)
592 */
593 setMethod(method: Util.HTTP_METHODS_PARTIAL): void;
594
595 /**
596 * Changes the request URI before the router begins processing the request where:
597 * Can only be called from an 'onRequest' extension method.
598 * @param url - the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL
599 * parse() method output.
600 * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false.
601 * @return void
602 * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash)
603 */
604 setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void;
605}
606
607/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
608 + +
609 + +
610 + +
611 + Response +
612 + +
613 + +
614 + +
615 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
616
617/**
618 * Access: read only and the public podium interface.
619 * The response.events object supports the following events:
620 * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
621 * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
622 * [See docs](https://hapijs.com/api/17.0.1#-responseevents)
623 */
624export interface ResponseEvents extends Podium {
625 /**
626 * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
627 * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
628 */
629 on(criteria: 'peek', listener: PeekListener): void;
630
631 on(criteria: 'finish', listener: (data: undefined) => void): void;
632
633 /**
634 * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
635 * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
636 */
637 once(criteria: 'peek', listener: PeekListener): void;
638
639 once(criteria: 'finish', listener: (data: undefined) => void): void;
640}
641
642/**
643 * Object where:
644 * * append - if true, the value is appended to any existing header value using separator. Defaults to false.
645 * * separator - string used as separator when appending to an existing value. Defaults to ','.
646 * * override - if false, the header value is not set if an existing value present. Defaults to true.
647 * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true.
648 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options)
649 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object)
650 */
651export interface ResponseObjectHeaderOptions {
652 append?: boolean | undefined;
653 separator?: string | undefined;
654 override?: boolean | undefined;
655 duplicate?: boolean | undefined;
656}
657
658/**
659 * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle
660 * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status
661 * code). In order to customize a response before it is returned, the h.response() method is provided.
662 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object)
663 * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/17.0.1#-responseevents)
664 */
665export interface ResponseObject extends Podium {
666 /**
667 * Default value: {}.
668 * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].
669 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp)
670 */
671 app: ApplicationState;
672
673 /**
674 * Access: read only and the public podium interface.
675 * The response.events object supports the following events:
676 * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
677 * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
678 * [See docs](https://hapijs.com/api/17.0.1#-responseevents)
679 */
680 readonly events: ResponseEvents;
681
682 /**
683 * Default value: {}.
684 * An object containing the response headers where each key is a header field name and the value is the string header value or array of string.
685 * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission.
686 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders)
687 */
688 readonly headers: Util.Dictionary<string | string[]>;
689
690 /**
691 * Default value: {}.
692 * Plugin-specific state. Provides a place to store and pass request-level plugin data. plugins is an object where each key is a plugin name and the value is the state.
693 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins)
694 */
695 plugins: PluginsStates;
696
697 /**
698 * Object containing the response handling flags.
699 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings)
700 */
701 readonly settings: ResponseSettings;
702
703 /**
704 * The raw value returned by the lifecycle method.
705 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource)
706 */
707 readonly source: Lifecycle.ReturnValue;
708
709 /**
710 * Default value: 200.
711 * The HTTP response status code.
712 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode)
713 */
714 readonly statusCode: number;
715
716 /**
717 * A string indicating the type of source with available values:
718 * * 'plain' - a plain response such as string, number, null, or simple object.
719 * * 'buffer' - a Buffer.
720 * * 'stream' - a Stream.
721 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety)
722 */
723 readonly variety: 'plain' | 'buffer' | 'stream';
724
725 /**
726 * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where:
727 * @param length - the header value. Must match the actual payload size.
728 * @return Return value: the current response object.
729 * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength)
730 */
731 bytes(length: number): ResponseObject;
732
733 /**
734 * Sets the 'Content-Type' HTTP header 'charset' property where:
735 * @param charset - the charset property value.
736 * @return Return value: the current response object.
737 * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset)
738 */
739 charset(charset: string): ResponseObject;
740
741 /**
742 * Sets the HTTP status code where:
743 * @param statusCode - the HTTP status code (e.g. 200).
744 * @return Return value: the current response object.
745 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode)
746 */
747 code(statusCode: number): ResponseObject;
748
749 /**
750 * Sets the HTTP status message where:
751 * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200).
752 * @return Return value: the current response object.
753 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage)
754 */
755 message(httpMessage: string): ResponseObject;
756
757 /**
758 * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where:
759 * @param uri - an absolute or relative URI used as the 'Location' header value.
760 * @return Return value: the current response object.
761 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri)
762 */
763 created(uri: string): ResponseObject;
764
765 /**
766 * Sets the string encoding scheme used to serial data into the HTTP payload where:
767 * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)).
768 * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set.
769 * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
770 * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.
771 * * 'ucs2' - Alias of 'utf16le'.
772 * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5.
773 * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes).
774 * * 'binary' - Alias for 'latin1'.
775 * * 'hex' - Encode each byte as two hexadecimal characters.
776 * @return Return value: the current response object.
777 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding)
778 */
779 encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject;
780
781 /**
782 * Sets the representation entity tag where:
783 * @param tag - the entity tag string without the double-quote.
784 * @param options - (optional) settings where:
785 * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false.
786 * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by
787 * a '-' character). Ignored when weak is true. Defaults to true.
788 * @return Return value: the current response object.
789 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options)
790 */
791 etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject;
792
793 /**
794 * Sets an HTTP header where:
795 * @param name - the header name.
796 * @param value - the header value.
797 * @param options - (optional) object where:
798 * * append - if true, the value is appended to any existing header value using separator. Defaults to false.
799 * * separator - string used as separator when appending to an existing value. Defaults to ','.
800 * * override - if false, the header value is not set if an existing value present. Defaults to true.
801 * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true.
802 * @return Return value: the current response object.
803 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options)
804 */
805 header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject;
806
807 /**
808 * Sets the HTTP 'Location' header where:
809 * @param uri - an absolute or relative URI used as the 'Location' header value.
810 * @return Return value: the current response object.
811 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri)
812 */
813 location(uri: string): ResponseObject;
814
815 /**
816 * Sets an HTTP redirection response (302) and decorates the response with additional methods, where:
817 * @param uri - an absolute or relative URI used to redirect the client to another resource.
818 * @return Return value: the current response object.
819 * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302).
820 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi)
821 */
822 redirect(uri: string): ResponseObject;
823
824 /**
825 * Sets the JSON.stringify() replacer argument where:
826 * @param method - the replacer function or array. Defaults to none.
827 * @return Return value: the current response object.
828 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod)
829 */
830 replacer(method: Json.StringifyReplacer): ResponseObject;
831
832 /**
833 * Sets the JSON.stringify() space argument where:
834 * @param count - the number of spaces to indent nested object keys. Defaults to no indentation.
835 * @return Return value: the current response object.
836 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount)
837 */
838 spaces(count: number): ResponseObject;
839
840 /**
841 * Sets an HTTP cookie where:
842 * @param name - the cookie name.
843 * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values.
844 * @param options - (optional) configuration. If the state was previously registered with the server using server.state(), the specified keys in options are merged with the default server
845 * definition.
846 * @return Return value: the current response object.
847 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options)
848 */
849 state(name: string, value: object | string, options?: ServerStateCookieOptions): ResponseObject;
850
851 /**
852 * Sets a string suffix when the response is process via JSON.stringify() where:
853 * @param suffix - the string suffix.
854 * @return Return value: the current response object.
855 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix)
856 */
857 suffix(suffix: string): ResponseObject;
858
859 /**
860 * Overrides the default route cache expiration rule for this response instance where:
861 * @param msec - the time-to-live value in milliseconds.
862 * @return Return value: the current response object.
863 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec)
864 */
865 ttl(msec: number): ResponseObject;
866
867 /**
868 * Sets the HTTP 'Content-Type' header where:
869 * @param mimeType - is the mime type.
870 * @return Return value: the current response object.
871 * Should only be used to override the built-in default for each response type.
872 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype)
873 */
874 type(mimeType: string): ResponseObject;
875
876 /**
877 * Clears the HTTP cookie by setting an expired value where:
878 * @param name - the cookie name.
879 * @param options - (optional) configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified options are merged with the server
880 * definition.
881 * @return Return value: the current response object.
882 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options)
883 */
884 unstate(name: string, options?: ServerStateCookieOptions): ResponseObject;
885
886 /**
887 * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where:
888 * @param header - the HTTP request header name.
889 * @return Return value: the current response object.
890 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader)
891 */
892 vary(header: string): ResponseObject;
893
894 /**
895 * Marks the response object as a takeover response.
896 * @return Return value: the current response object.
897 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover)
898 */
899 takeover(): ResponseObject;
900
901 /**
902 * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where:
903 * @param isTemporary - if false, sets status to permanent. Defaults to true.
904 * @return Return value: the current response object.
905 * Only available after calling the response.redirect() method.
906 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary)
907 */
908 temporary(isTemporary: boolean): ResponseObject;
909
910 /**
911 * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where:
912 * @param isPermanent - if false, sets status to temporary. Defaults to true.
913 * @return Return value: the current response object.
914 * Only available after calling the response.redirect() method.
915 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent)
916 */
917 permanent(isPermanent: boolean): ResponseObject;
918
919 /**
920 * Sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST'
921 * to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments:
922 * @param isRewritable - if false, sets to non-rewritable. Defaults to true.
923 * @return Return value: the current response object.
924 * Only available after calling the response.redirect() method.
925 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable)
926 */
927 rewritable(isRewritable: boolean): ResponseObject;
928}
929
930/**
931 * Object containing the response handling flags.
932 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings)
933 */
934export interface ResponseSettings {
935 /**
936 * Defaults value: true.
937 * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response.
938 */
939 readonly passThrough: boolean;
940
941 /**
942 * Default value: null (use route defaults).
943 * Override the route json options used when source value requires stringification.
944 */
945 readonly stringify: Json.StringifyArguments;
946
947 /**
948 * Default value: null (use route defaults).
949 * If set, overrides the route cache with an expiration value in milliseconds.
950 */
951 readonly ttl: number;
952
953 /**
954 * Default value: false.
955 * If true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.
956 */
957 varyEtag: boolean;
958}
959
960/**
961 * See more about Lifecycle
962 * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle
963 *
964 */
965
966export type ResponseValue = string | object;
967
968export interface AuthenticationData {
969 credentials: AuthCredentials;
970 artifacts?: object | undefined;
971}
972
973export interface Auth {
974 readonly isAuth: true;
975 readonly error?: Error | null | undefined;
976 readonly data?: AuthenticationData | undefined;
977}
978
979/**
980 * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods)
981 * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the
982 * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this
983 * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi.
984 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit)
985 */
986export interface ResponseToolkit {
987 /**
988 * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step
989 * without further interaction with the node response stream. It is the developer's responsibility to write
990 * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw).
991 */
992 readonly abandon: symbol;
993
994 /**
995 * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after
996 * calling request.raw.res.end()) to close the the node response stream.
997 */
998 readonly close: symbol;
999
1000 /**
1001 * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind)
1002 * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()).
1003 */
1004 readonly context: any;
1005
1006 /**
1007 * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response.
1008 */
1009 readonly continue: symbol;
1010
1011 /**
1012 * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching
1013 * route. Defaults to the root server realm in the onRequest step.
1014 */
1015 readonly realm: ServerRealm;
1016
1017 /**
1018 * Access: read only and public request interface.
1019 * The [request] object. This is a duplication of the request lifecycle method argument used by
1020 * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request.
1021 */
1022 readonly request: Readonly<Request>;
1023
1024 /**
1025 * Used by the [authentication] method to pass back valid credentials where:
1026 * @param data - an object with:
1027 * * credentials - (required) object representing the authenticated entity.
1028 * * artifacts - (optional) authentication artifacts object specific to the authentication scheme.
1029 * @return Return value: an internal authentication object.
1030 */
1031 authenticated(data: AuthenticationData): Auth;
1032
1033 /**
1034 * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if
1035 * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request
1036 * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will
1037 * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined.
1038 * The method argumetns are:
1039 * @param options - a required configuration object with:
1040 * * etag - the ETag string. Required if modified is not present. Defaults to no header.
1041 * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header.
1042 * * vary - same as the response.etag() option. Defaults to true.
1043 * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed.
1044 * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned,
1045 * it should be used as the return value (but may be customize using the response methods).
1046 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions)
1047 */
1048 entity(options?: {etag?: string | undefined, modified?: string | undefined, vary?: boolean | undefined}): ResponseObject | undefined;
1049
1050 /**
1051 * Redirects the client to the specified uri. Same as calling h.response().redirect(uri).
1052 * @param url
1053 * @return Returns a response object.
1054 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi)
1055 */
1056 redirect(uri?: string): ResponseObject;
1057
1058 /**
1059 * Wraps the provided value and returns a response object which allows customizing the response
1060 * (e.g. setting the HTTP status code, custom headers, etc.), where:
1061 * @param value - (optional) return value. Defaults to null.
1062 * @return Returns a response object.
1063 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue)
1064 */
1065 response(value?: ResponseValue): ResponseObject;
1066
1067 /**
1068 * Sets a response cookie using the same arguments as response.state().
1069 * @param name of the cookie
1070 * @param value of the cookie
1071 * @param (optional) ServerStateCookieOptions object.
1072 * @return Return value: none.
1073 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options)
1074 */
1075 state(name: string, value: string | object, options?: ServerStateCookieOptions): void;
1076
1077 /**
1078 * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where:
1079 * @param error - (required) the authentication error.
1080 * @param data - (optional) an object with:
1081 * * credentials - (required) object representing the authenticated entity.
1082 * * artifacts - (optional) authentication artifacts object specific to the authentication scheme.
1083 * @return void.
1084 * The method is used to pass both the authentication error and the credentials. For example, if a request included
1085 * expired credentials, it allows the method to pass back the user information (combined with a 'try'
1086 * authentication mode) for error customization.
1087 * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity.
1088 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data)
1089 */
1090 unauthenticated(error: Error, data?: AuthenticationData): void;
1091
1092 /**
1093 * Clears a response cookie using the same arguments as
1094 * @param name of the cookie
1095 * @param options (optional) ServerStateCookieOptions object.
1096 * @return void.
1097 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options)
1098 */
1099 unstate(name: string, options?: ServerStateCookieOptions): void;
1100}
1101
1102/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1103 + +
1104 + +
1105 + +
1106 + Route +
1107 + +
1108 + +
1109 + +
1110 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
1111
1112export type RouteOptionsAccessScope = false | string | string[];
1113
1114export type RouteOptionsAccessEntity = 'any' | 'user' | 'app';
1115
1116export interface RouteOptionsAccessScopeObject {
1117 scope: RouteOptionsAccessScope;
1118}
1119
1120export interface RouteOptionsAccessEntityObject {
1121 entity: RouteOptionsAccessEntity;
1122}
1123
1124export type RouteOptionsAccessObject =
1125 RouteOptionsAccessScopeObject
1126 | RouteOptionsAccessEntityObject
1127 | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject);
1128
1129/**
1130 * Route Authentication Options
1131 */
1132export interface RouteOptionsAccess {
1133 /**
1134 * Default value: none.
1135 * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object
1136 * must include at least one of scope or entity.
1137 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess)
1138 */
1139 access?: RouteOptionsAccessObject | RouteOptionsAccessObject[] | undefined;
1140
1141 /**
1142 * Default value: false (no scope requirements).
1143 * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least
1144 * one of the scopes defined to access the route. If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For
1145 * example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access
1146 * properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'.
1147 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope)
1148 */
1149 scope?: RouteOptionsAccessScope | undefined;
1150
1151 /**
1152 * Default value: 'any'.
1153 * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values:
1154 * * 'any' - the authentication can be on behalf of a user or application.
1155 * * 'user' - the authentication must be on behalf of a user which is identified by the presence of a 'user' attribute in the credentials object returned by the authentication strategy.
1156 * * 'app' - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication
1157 * strategy.
1158 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity)
1159 */
1160 entity?: RouteOptionsAccessEntity | undefined;
1161
1162 /**
1163 * Default value: 'required'.
1164 * The authentication mode. Available values:
1165 * * 'required' - authentication is required.
1166 * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all.
1167 * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error.
1168 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode)
1169 */
1170 mode?: 'required' | 'optional' | 'try' | undefined;
1171
1172 /**
1173 * Default value: false, unless the scheme requires payload authentication.
1174 * If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required'
1175 * when the scheme sets the authentication options.payload to true. Available values:
1176 * * false - no payload authentication.
1177 * * 'required' - payload authentication required.
1178 * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk).
1179 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload)
1180 */
1181 payload?: false | 'required' | 'optional' | undefined;
1182
1183 /**
1184 * Default value: the default strategy set via server.auth.default().
1185 * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy.
1186 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies)
1187 */
1188 strategies?: string[] | undefined;
1189
1190 /**
1191 * Default value: the default strategy set via server.auth.default().
1192 * A string strategy names. Cannot be used together with strategies.
1193 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy)
1194 */
1195 strategy?: string | undefined;
1196}
1197
1198/**
1199 * Values are:
1200 * * * 'default' - no privacy flag.
1201 * * * 'public' - mark the response as suitable for public caching.
1202 * * * 'private' - mark the response as suitable only for private caching.
1203 * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
1204 * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn.
1205 * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive.
1206 * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled.
1207 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache)
1208 */
1209export type RouteOptionsCache = {
1210 privacy?: 'default' | 'public' | 'private' | undefined;
1211 statuses?: number[] | undefined;
1212 otherwise?: string | undefined;
1213} & (
1214 {
1215 expiresIn?: number | undefined;
1216 expiresAt?: undefined;
1217 } | {
1218 expiresIn?: undefined;
1219 expiresAt?: string | undefined;
1220} | {
1221 expiresIn?: undefined;
1222 expiresAt?: undefined;
1223}
1224 );
1225
1226/**
1227 * Default value: false (no CORS headers).
1228 * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain
1229 * than the API server. To enable, set cors to true, or to an object with the following options:
1230 * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a
1231 * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'.
1232 * Defaults to any origin ['*'].
1233 * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy.
1234 * Defaults to 86400 (one day).
1235 * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'].
1236 * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place.
1237 * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization'].
1238 * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place.
1239 * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false.
1240 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors)
1241 */
1242export interface RouteOptionsCors {
1243 /**
1244 * an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*'
1245 * character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any
1246 * origin ['*'].
1247 */
1248 origin?: string[] | '*' | 'ignore' | undefined;
1249 /**
1250 * number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy.
1251 * Defaults to 86400 (one day).
1252 */
1253 maxAge?: number | undefined;
1254 /**
1255 * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'].
1256 */
1257 headers?: string[] | undefined;
1258 /**
1259 * a strings array of additional headers to headers. Use this to keep the default headers in place.
1260 */
1261 additionalHeaders?: string[] | undefined;
1262 /**
1263 * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization'].
1264 */
1265 exposedHeaders?: string[] | undefined;
1266 /**
1267 * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place.
1268 */
1269 additionalExposedHeaders?: string[] | undefined;
1270 /**
1271 * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false.
1272 */
1273 credentials?: boolean | undefined;
1274}
1275
1276/**
1277 * The value must be one of:
1278 * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw
1279 * Buffer is returned.
1280 * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are
1281 * provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart
1282 * payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the
1283 * multipart payload in the handler using a streaming parser (e.g. pez).
1284 * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are
1285 * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of
1286 * which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. For context [See
1287 * docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput)
1288 */
1289export type PayloadOutput = 'data' | 'stream' | 'file';
1290
1291/**
1292 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression)
1293 */
1294export type PayloadCompressionDecoderSettings = object;
1295
1296/**
1297 * Determines how the request payload is processed.
1298 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload)
1299 */
1300export interface RouteOptionsPayload {
1301 /**
1302 * Default value: allows parsing of the following mime types:
1303 * * application/json
1304 * * application/*+json
1305 * * application/octet-stream
1306 * * application/x-www-form-urlencoded
1307 * * multipart/form-data
1308 * * text/*
1309 * A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed
1310 * above will not enable them to be parsed, and if parse is true, the request will result in an error response.
1311 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow)
1312 */
1313 allow?: string | string[] | undefined;
1314
1315 /**
1316 * Default value: none.
1317 * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression.
1318 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression)
1319 */
1320 compression?: Util.Dictionary<PayloadCompressionDecoderSettings> | undefined;
1321
1322 /**
1323 * Default value: 'application/json'.
1324 * The default content type if the 'Content-Type' request header is missing.
1325 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype)
1326 */
1327 defaultContentType?: string | undefined;
1328
1329 /**
1330 * Default value: 'error' (return a Bad Request (400) error response).
1331 * A failAction value which determines how to handle payload parsing errors.
1332 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction)
1333 */
1334 failAction?: Lifecycle.FailAction | undefined;
1335
1336 /**
1337 * Default value: 1048576 (1MB).
1338 * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory.
1339 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes)
1340 */
1341 maxBytes?: number | undefined;
1342
1343 /**
1344 * Default value: none.
1345 * Overrides payload processing for multipart requests. Value can be one of:
1346 * * false - disable multipart processing.
1347 * an object with the following required options:
1348 * * output - same as the output option with an additional value option:
1349 * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this?
1350 * * * * headers - the part headers.
1351 * * * * filename - the part file name.
1352 * * * * payload - the processed part payload.
1353 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart)
1354 */
1355 multipart?: false | {
1356 output: PayloadOutput | 'annotated';
1357 } | undefined;
1358
1359 /**
1360 * Default value: 'data'.
1361 * The processed payload format. The value must be one of:
1362 * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw
1363 * Buffer is returned.
1364 * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files
1365 * are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart
1366 * payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the
1367 * multipart payload in the handler using a streaming parser (e.g. pez).
1368 * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are
1369 * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track
1370 * of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup.
1371 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput)
1372 */
1373 output?: PayloadOutput | undefined;
1374
1375 /**
1376 * Default value: none.
1377 * A mime type string overriding the 'Content-Type' header value received.
1378 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride)
1379 */
1380 override?: string | undefined;
1381
1382 /**
1383 * Default value: true.
1384 * Determines if the incoming payload is processed or presented raw. Available values:
1385 * * true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the
1386 * format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded.
1387 * * false - the raw payload is returned unmodified.
1388 * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded.
1389 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse)
1390 */
1391 parse?: boolean | 'gunzip' | undefined;
1392
1393 /**
1394 * Default value: to 10000 (10 seconds).
1395 * Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408)
1396 * error response. Set to false to disable.
1397 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout)
1398 */
1399 timeout?: false | number | undefined;
1400
1401 /**
1402 * Default value: os.tmpdir().
1403 * The directory used for writing file uploads.
1404 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads)
1405 */
1406 uploads?: string | undefined;
1407}
1408
1409/**
1410 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1411 */
1412export type RouteOptionsPreArray = RouteOptionsPreAllOptions[];
1413
1414/**
1415 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1416 */
1417export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method;
1418
1419/**
1420 * An object with:
1421 * * method - a lifecycle method.
1422 * * assign - key name used to assign the response of the method to in request.pre and request.preResponses.
1423 * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned.
1424 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1425 */
1426export interface RouteOptionsPreObject {
1427 /**
1428 * a lifecycle method.
1429 */
1430 method: Lifecycle.Method;
1431 /**
1432 * key name used to assign the response of the method to in request.pre and request.preResponses.
1433 */
1434 assign?: string | undefined;
1435 /**
1436 * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned.
1437 */
1438 failAction?: Lifecycle.FailAction | undefined;
1439}
1440
1441export type ValidationObject = SchemaMap;
1442
1443/**
1444 * * true - any query parameter value allowed (no validation performed). false - no parameter value allowed.
1445 * * a joi validation object.
1446 * * a validation function using the signature async function(value, options) where:
1447 * * * value - the request.* object containing the request parameters.
1448 * * * options - options.
1449 */
1450export type RouteOptionsResponseSchema =
1451 boolean
1452 | ValidationObject
1453 | Schema
1454 | ((value: object | Buffer | string, options: ValidationOptions) => Promise<any>);
1455
1456/**
1457 * Processing rules for the outgoing response.
1458 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse)
1459 */
1460export interface RouteOptionsResponse {
1461 /**
1462 * Default value: 200.
1463 * The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the
1464 * response status code will remain 200 throughout the request lifecycle unless manually set).
1465 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode)
1466 */
1467 emptyStatusCode?: 200 | 204 | undefined;
1468
1469 /**
1470 * Default value: 'error' (return an Internal Server Error (500) error response).
1471 * A failAction value which defines what to do when a response fails payload validation.
1472 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction)
1473 */
1474 failAction?: Lifecycle.FailAction | undefined;
1475
1476 /**
1477 * Default value: false.
1478 * If true, applies the validation rule changes to the response payload.
1479 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify)
1480 */
1481 modify?: boolean | undefined;
1482
1483 /**
1484 * Default value: none.
1485 * [joi](https://github.com/hapijs/joi) options object pass to the validation function. Useful to set global options such as stripUnknown or abortEarly (the complete list is available here). If a
1486 * custom validation function is defined via schema or status then options can an arbitrary object that will be passed to this function as the second argument.
1487 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions)
1488 */
1489 options?: ValidationOptions | undefined; // TODO needs validation
1490
1491 /**
1492 * Default value: true.
1493 * If false, payload range support is disabled.
1494 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges)
1495 */
1496 ranges?: boolean | undefined;
1497
1498 /**
1499 * Default value: 100 (all responses).
1500 * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation.
1501 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample)
1502 */
1503 sample?: number | undefined;
1504
1505 /**
1506 * Default value: true (no validation).
1507 * The default response payload validation rules (for all non-error responses) expressed as one of:
1508 * * true - any payload allowed (no validation).
1509 * * false - no payload allowed.
1510 * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function.
1511 * * a validation function using the signature async function(value, options) where:
1512 * * * value - the pending response payload.
1513 * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }).
1514 * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error
1515 * output.payload. If an error is thrown, the error is processed according to failAction.
1516 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema)
1517 */
1518 schema?: RouteOptionsResponseSchema | undefined;
1519
1520 /**
1521 * Default value: none.
1522 * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema.
1523 * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.
1524 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus)
1525 */
1526 status?: Util.Dictionary<RouteOptionsResponseSchema> | undefined;
1527
1528 /**
1529 * The default HTTP status code used to set a response error when the request is closed or aborted before the
1530 * response is fully transmitted.
1531 * Value can be any integer greater or equal to 400.
1532 * The default value 499 is based on the non-standard nginx "CLIENT CLOSED REQUEST" error.
1533 * The value is only used for logging as the request has already ended.
1534 * @default 499
1535 */
1536 disconnectStatusCode?: number | undefined;
1537}
1538
1539/**
1540 * @see https://www.w3.org/TR/referrer-policy/
1541 */
1542export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'unsafe-url' |
1543 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin';
1544
1545/**
1546 * Default value: false (security headers disabled).
1547 * Sets common security headers. To enable, set security to true or to an object with the following options:
1548 * * hsts - controls the 'Strict-Transport-Security' header, where:
1549 * * * true - the header will be set to max-age=15768000. This is the default value.
1550 * * * a number - the maxAge parameter will be set to the provided value.
1551 * * * an object with the following fields:
1552 * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000.
1553 * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header.
1554 * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header.
1555 * * xframe - controls the 'X-Frame-Options' header, where:
1556 * * * true - the header will be set to 'DENY'. This is the default value.
1557 * * * 'deny' - the headers will be set to 'DENY'.
1558 * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'.
1559 * * * an object for specifying the 'allow-from' rule, where:
1560 * * * * rule - one of:
1561 * * * * * 'deny'
1562 * * * * * 'sameorigin'
1563 * * * * * 'allow-from'
1564 * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically
1565 * changed to 'sameorigin'.
1566 * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'.
1567 * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively
1568 * support old versions of IE, it may be wise to explicitly set this flag to false.
1569 * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'.
1570 * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'.
1571 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeo