UNPKG

225 kBTypeScriptView Raw
1// Type definitions for @hapi/hapi 20.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// Silas Rech <https://github.com/lenovouser>
8// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
9// TypeScript Version: 2.8
10
11/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
12 + +
13 + +
14 + +
15 + WARNING: BACKWARDS INCOMPATIBLE +
16 + +
17 + +
18 + +
19 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
20
21/// <reference types='node' />
22
23import { Boom } from '@hapi/boom';
24import * as http from 'http';
25import * as https from 'https';
26import * as Shot from '@hapi/shot';
27import * as stream from 'stream';
28import * as url from 'url';
29import * as zlib from 'zlib';
30
31import { MimosOptions } from '@hapi/mimos';
32import { SealOptions, SealOptionsSub } from '@hapi/iron';
33import { ValidationOptions, SchemaMap, Schema, Root } from 'joi';
34import Podium = require('@hapi/podium');
35import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePrototype, Policy, ClientApi, ClientOptions } from '@hapi/catbox';
36
37/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
38 + +
39 + +
40 + +
41 + Plugin +
42 + +
43 + +
44 + +
45 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
46
47/**
48 * one of
49 * a single plugin name string.
50 * an array of plugin name strings.
51 * an object where each key is a plugin name and each matching value is a
52 * {@link https://www.npmjs.com/package/semver version range string} which must match the registered
53 * plugin version.
54 */
55export type Dependencies = string | string[] | {
56 [key: string]: string;
57};
58
59/**
60 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
61 */
62
63/* tslint:disable-next-line:no-empty-interface */
64export interface PluginsListRegistered {
65}
66
67/**
68 * An object of the currently registered plugins where each key is a registered plugin name and the value is an
69 * object containing:
70 * * version - the plugin version.
71 * * name - the plugin name.
72 * * options - (optional) options passed to the plugin during registration.
73 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
74 */
75export interface PluginRegistered {
76 /**
77 * the plugin version.
78 */
79 version: string;
80
81 /**
82 * the plugin name.
83 */
84 name: string;
85
86 /**
87 * options used to register the plugin.
88 */
89 options: object;
90}
91
92/* tslint:disable-next-line:no-empty-interface */
93export interface PluginsStates {
94}
95
96/* tslint:disable-next-line:no-empty-interface */
97export interface PluginSpecificConfiguration {
98}
99
100export interface PluginNameVersion {
101 /**
102 * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm
103 * registry) should use the same name as the name field in their 'package.json' file. Names must be
104 * unique within each application.
105 */
106 name: string;
107
108 /**
109 * 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
110 * 'package.json' file.
111 */
112 version?: string;
113}
114
115export interface PluginPackage {
116 /**
117 * 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
118 */
119 pkg: any;
120}
121
122/**
123 * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each
124 * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox
125 * certain properties. For example, setting a file path in one plugin doesn't affect the file path set
126 * in another plugin.
127 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins)
128 *
129 * The type T is the type of the plugin options.
130 */
131export interface PluginBase<T> {
132 /**
133 * (required) the registration function with the signature async function(server, options) where:
134 * * server - the server object with a plugin-specific server.realm.
135 * * options - any options passed to the plugin during registration via server.register().
136 */
137 register: (server: Server, options: T) => void | Promise<void>;
138
139 /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */
140 multiple?: boolean;
141
142 /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */
143 dependencies?: Dependencies;
144
145 /**
146 * Allows defining semver requirements for node and hapi.
147 * @default Allows all.
148 */
149 requirements?: {
150 node?: string;
151 hapi?: string;
152 };
153
154 /** 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. */
155 once?: boolean;
156}
157
158export type Plugin<T> = PluginBase<T> & (PluginNameVersion | PluginPackage);
159
160/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
161 + +
162 + +
163 + +
164 + Request +
165 + +
166 + +
167 + +
168 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
169
170/**
171 * User extensible types user credentials.
172 */
173// tslint:disable-next-line:no-empty-interface
174export interface UserCredentials {
175}
176
177/**
178 * User extensible types app credentials.
179 */
180// tslint:disable-next-line:no-empty-interface
181export interface AppCredentials {
182}
183
184/**
185 * User-extensible type for request.auth credentials.
186 */
187export interface AuthCredentials {
188 /**
189 * The application scopes to be granted.
190 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope)
191 */
192 scope?: string[];
193 /**
194 * If set, will only work with routes that set `access.entity` to `user`.
195 */
196 user?: UserCredentials;
197
198 /**
199 * If set, will only work with routes that set `access.entity` to `app`.
200 */
201 app?: AppCredentials;
202
203 [key: string]: unknown;
204}
205
206export type AuthMode = 'required' | 'optional' | 'try';
207
208/**
209 * Authentication information:
210 * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions.
211 * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication.
212 * * error - the authentication error is failed and mode set to 'try'.
213 * * isAuthenticated - true if the request has been successfully authenticated, otherwise false.
214 * * 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
215 * authorization, set to false.
216 * * mode - the route authentication mode.
217 * * strategy - the name of the strategy used.
218 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth)
219 */
220export interface RequestAuth {
221 /** an artifact object received from the authentication strategy and used in authentication-related actions. */
222 artifacts: object;
223 /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */
224 credentials: AuthCredentials;
225 /** the authentication error is failed and mode set to 'try'. */
226 error: Error;
227 /** true if the request has been successfully authenticated, otherwise false. */
228 isAuthenticated: boolean;
229 /**
230 * 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,
231 * set to false.
232 */
233 isAuthorized: boolean;
234 /** the route authentication mode. */
235 mode: AuthMode;
236 /** the name of the strategy used. */
237 strategy: string;
238}
239
240/**
241 * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
242 * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
243 * 'disconnect' - emitted when a request errors or aborts unexpectedly.
244 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
245 */
246export type RequestEventType = 'peek' | 'finish' | 'disconnect';
247
248/**
249 * Access: read only and the public podium interface.
250 * The request.events supports the following events:
251 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
252 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
253 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
254 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
255 */
256export interface RequestEvents extends Podium {
257 /**
258 * Access: read only and the public podium interface.
259 * The request.events supports the following events:
260 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
261 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
262 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
263 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
264 */
265 on(criteria: 'peek', listener: PeekListener): void;
266
267 on(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void;
268
269 /**
270 * Access: read only and the public podium interface.
271 * The request.events supports the following events:
272 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
273 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
274 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
275 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
276 */
277 once(criteria: 'peek', listener: PeekListener): void;
278
279 once(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void;
280}
281
282/**
283 * Request information:
284 * * acceptEncoding - the request preferred encoding.
285 * * cors - if CORS is enabled for the route, contains the following:
286 * * 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
287 * 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.
288 * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080').
289 * * hostname - the hostname part of the 'Host' header (e.g. 'example.com').
290 * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').
291 * * received - request reception timestamp.
292 * * referrer - content of the HTTP 'Referrer' (or 'Referer') header.
293 * * remoteAddress - remote client IP address.
294 * * remotePort - remote client port.
295 * * responded - request response timestamp (0 is not responded yet).
296 * Note that the request.info object is not meant to be modified.
297 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo)
298 */
299export interface RequestInfo {
300 /** the request preferred encoding. */
301 acceptEncoding: string;
302 /** if CORS is enabled for the route, contains the following: */
303 cors: {
304 /**
305 * 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
306 * the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle.
307 */
308 isOriginMatch?: boolean;
309 };
310 /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */
311 host: string;
312 /** the hostname part of the 'Host' header (e.g. 'example.com'). */
313 hostname: string;
314 /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}') */
315 id: string;
316 /** request reception timestamp. */
317 received: number;
318 /** content of the HTTP 'Referrer' (or 'Referer') header. */
319 referrer: string;
320 /** remote client IP address. */
321 remoteAddress: string;
322 /** remote client port. */
323 remotePort: string;
324 /** request response timestamp (0 is not responded yet). */
325 responded: number;
326 /** request processing completion timestamp (0 is still processing). */
327 completed: number;
328}
329
330/**
331 * The request route information object, where:
332 * * method - the route HTTP method.
333 * * path - the route path.
334 * * vhost - the route vhost option if configured.
335 * * realm - the active realm associated with the route.
336 * * settings - the route options object with all defaults applied.
337 * * fingerprint - the route internal normalized string representing the normalized path.
338 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute)
339 */
340export interface RequestRoute {
341 /** the route HTTP method. */
342 method: Util.HTTP_METHODS_PARTIAL;
343
344 /** the route path. */
345 path: string;
346
347 /** the route vhost option if configured. */
348 vhost?: string | string[];
349
350 /** the active realm associated with the route. */
351 realm: ServerRealm;
352
353 /** the route options object with all defaults applied. */
354 settings: RouteSettings;
355
356 /** the route internal normalized string representing the normalized path. */
357 fingerprint: string;
358
359 auth: {
360 /**
361 * Validates a request against the route's authentication access configuration, where:
362 * @param request - the request object.
363 * @return Return value: true if the request would have passed the route's access requirements.
364 * 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
365 * 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
366 * 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
367 * requires any authentication.
368 * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest)
369 */
370 access(request: Request): boolean;
371 };
372}
373
374/**
375 * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.
376 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig)
377 */
378export interface RequestOrig {
379 params: object;
380 query: object;
381 payload: object;
382}
383
384export interface RequestLog {
385 request: string;
386 timestamp: number;
387 tags: string[];
388 data: string | object;
389 channel: string;
390}
391
392export interface RequestQuery {
393 [key: string]: any;
394}
395
396/**
397 * The request object is created internally for each incoming request. It is not the same object received from the node
398 * 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
399 * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle).
400 */
401export interface Request extends Podium {
402 /**
403 * 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].
404 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp)
405 */
406 app: RequestApplicationState;
407
408 /**
409 * Authentication information:
410 * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions.
411 * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication.
412 * * error - the authentication error is failed and mode set to 'try'.
413 * * isAuthenticated - true if the request has been successfully authenticated, otherwise false.
414 * * 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
415 * authorization, set to false.
416 * * mode - the route authentication mode.
417 * * strategy - the name of the strategy used.
418 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth)
419 */
420 readonly auth: RequestAuth;
421
422 /**
423 * Access: read only and the public podium interface.
424 * The request.events supports the following events:
425 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
426 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
427 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
428 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
429 */
430 events: RequestEvents;
431
432 /**
433 * The raw request headers (references request.raw.req.headers).
434 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders)
435 */
436 readonly headers: Util.Dictionary<string>;
437
438 /**
439 * Request information:
440 * * acceptEncoding - the request preferred encoding.
441 * * cors - if CORS is enabled for the route, contains the following:
442 * * 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
443 * 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.
444 * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080').
445 * * hostname - the hostname part of the 'Host' header (e.g. 'example.com').
446 * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').
447 * * received - request reception timestamp.
448 * * referrer - content of the HTTP 'Referrer' (or 'Referer') header.
449 * * remoteAddress - remote client IP address.
450 * * remotePort - remote client port.
451 * * responded - request response timestamp (0 is not responded yet).
452 * Note that the request.info object is not meant to be modified.
453 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo)
454 */
455 readonly info: RequestInfo;
456
457 /**
458 * An array containing the logged request events.
459 * Note that this array will be empty if route log.collect is set to false.
460 */
461 readonly logs: RequestLog[];
462
463 /**
464 * The request method in lower case (e.g. 'get', 'post').
465 */
466 readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE;
467
468 /**
469 * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred.
470 */
471 readonly mime: string;
472
473 /**
474 * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.
475 */
476 readonly orig: RequestOrig;
477
478 /**
479 * 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).
480 */
481 readonly params: Util.Dictionary<any>;
482
483 /**
484 * An array containing all the path params values in the order they appeared in the path.
485 */
486 readonly paramsArray: string[];
487
488 /**
489 * The request URI's pathname component.
490 */
491 readonly path: string;
492
493 /**
494 * The request payload based on the route payload.output and payload.parse settings.
495 * TODO check this typing and add references / links.
496 */
497 readonly payload: stream.Readable | Buffer | string | object;
498
499 /**
500 * 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.
501 */
502 plugins: PluginsStates;
503
504 /**
505 * 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
506 * object, use responses.
507 */
508 readonly pre: Util.Dictionary<any>;
509
510 /**
511 * Access: read / write (see limitations below).
512 * 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
513 * override with a different response.
514 * In case of an aborted request the status code will be set to `disconnectStatusCode`.
515 */
516 response: ResponseObject | Boom;
517
518 /**
519 * Same as pre but represented as the response object created by the pre method.
520 */
521 readonly preResponses: Util.Dictionary<any>;
522
523 /**
524 * By default the object outputted from node's URL parse() method.
525 */
526 readonly query: RequestQuery;
527
528 /**
529 * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.
530 * * req - the node request object.
531 * * res - the node response object.
532 */
533 readonly raw: {
534 req: http.IncomingMessage;
535 res: http.ServerResponse;
536 };
537
538 /**
539 * The request route information object and method
540 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute)
541 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest)
542 */
543 readonly route: RequestRoute;
544
545 /**
546 * Access: read only and the public server interface.
547 * The server object.
548 */
549 server: Server;
550
551 /**
552 * 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.
553 */
554 readonly state: Util.Dictionary<any>;
555
556 /**
557 * The parsed request URI.
558 */
559 readonly url: url.URL;
560
561 /**
562 * Returns `true` when the request is active and processing should continue and `false` when the
563 * request terminated early or completed its lifecycle. Useful when request processing is a
564 * resource-intensive operation and should be terminated early if the request is no longer active
565 * (e.g. client disconnected or aborted early).
566 */
567 active(): boolean;
568
569 /**
570 * Returns a response which you can pass into the reply interface where:
571 * @param source - the value to set as the source of the reply interface, optional.
572 * @param options - options for the method, optional.
573 * @return ResponseObject
574 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options)
575 */
576 /* tslint:disable-next-line:max-line-length */
577 generateResponse(source: string | object | null, options?: { variety?: string; prepare?: (response: ResponseObject) => Promise<ResponseObject>; marshal?: (response: ResponseObject) => Promise<ResponseValue>; close?: (response: ResponseObject) => void; }): ResponseObject;
578
579 /**
580 * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are:
581 * @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
582 * for describing and filtering events.
583 * @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
584 * 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
585 * set to true.
586 * @return void
587 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data)
588 */
589 log(tags: string | string[], data?: string | object | (() => string | object)): void;
590
591 /**
592 * Changes the request method before the router begins processing the request where:
593 * @param method - is the request HTTP method (e.g. 'GET').
594 * @return void
595 * Can only be called from an 'onRequest' extension method.
596 * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod)
597 */
598 setMethod(method: Util.HTTP_METHODS_PARTIAL): void;
599
600 /**
601 * Changes the request URI before the router begins processing the request where:
602 * Can only be called from an 'onRequest' extension method.
603 * @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
604 * parse() method output.
605 * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false.
606 * @return void
607 * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash)
608 */
609 setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void;
610}
611
612/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
613 + +
614 + +
615 + +
616 + Response +
617 + +
618 + +
619 + +
620 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
621
622/**
623 * Access: read only and the public podium interface.
624 * The response.events object supports the following events:
625 * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
626 * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
627 * [See docs](https://hapijs.com/api/17.0.1#-responseevents)
628 */
629export interface ResponseEvents extends Podium {
630 /**
631 * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
632 * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
633 */
634 on(criteria: 'peek', listener: PeekListener): void;
635
636 on(criteria: 'finish', listener: (data: undefined) => void): void;
637
638 /**
639 * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
640 * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
641 */
642 once(criteria: 'peek', listener: PeekListener): void;
643
644 once(criteria: 'finish', listener: (data: undefined) => void): void;
645}
646
647/**
648 * Object where:
649 * * append - if true, the value is appended to any existing header value using separator. Defaults to false.
650 * * separator - string used as separator when appending to an existing value. Defaults to ','.
651 * * override - if false, the header value is not set if an existing value present. Defaults to true.
652 * * 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.
653 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options)
654 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object)
655 */
656export interface ResponseObjectHeaderOptions {
657 append?: boolean;
658 separator?: string;
659 override?: boolean;
660 duplicate?: boolean;
661}
662
663/**
664 * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle
665 * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status
666 * code). In order to customize a response before it is returned, the h.response() method is provided.
667 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object)
668 * 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)
669 */
670export interface ResponseObject extends Podium {
671 /**
672 * @default {}.
673 * 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].
674 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp)
675 */
676 app: ResponseApplicationState;
677
678 /**
679 * Access: read only and the public podium interface.
680 * The response.events object supports the following events:
681 * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
682 * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
683 * [See docs](https://hapijs.com/api/17.0.1#-responseevents)
684 */
685 readonly events: ResponseEvents;
686
687 /**
688 * @default {}.
689 * 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.
690 * 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.
691 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders)
692 */
693 readonly headers: Util.Dictionary<string | string[]>;
694
695 /**
696 * @default {}.
697 * 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.
698 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins)
699 */
700 plugins: PluginsStates;
701
702 /**
703 * Object containing the response handling flags.
704 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings)
705 */
706 readonly settings: ResponseSettings;
707
708 /**
709 * The raw value returned by the lifecycle method.
710 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource)
711 */
712 readonly source: Lifecycle.ReturnValue;
713
714 /**
715 * @default 200.
716 * The HTTP response status code.
717 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode)
718 */
719 readonly statusCode: number;
720
721 /**
722 * A string indicating the type of source with available values:
723 * * 'plain' - a plain response such as string, number, null, or simple object.
724 * * 'buffer' - a Buffer.
725 * * 'stream' - a Stream.
726 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety)
727 */
728 readonly variety: 'plain' | 'buffer' | 'stream';
729
730 /**
731 * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where:
732 * @param length - the header value. Must match the actual payload size.
733 * @return Return value: the current response object.
734 * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength)
735 */
736 bytes(length: number): ResponseObject;
737
738 /**
739 * Sets the 'Content-Type' HTTP header 'charset' property where:
740 * @param charset - the charset property value.
741 * @return Return value: the current response object.
742 * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset)
743 */
744 charset(charset: string): ResponseObject;
745
746 /**
747 * Sets the HTTP status code where:
748 * @param statusCode - the HTTP status code (e.g. 200).
749 * @return Return value: the current response object.
750 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode)
751 */
752 code(statusCode: number): ResponseObject;
753
754 /**
755 * Sets the HTTP status message where:
756 * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200).
757 * @return Return value: the current response object.
758 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage)
759 */
760 message(httpMessage: string): ResponseObject;
761
762 /**
763 * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where:
764 * @param uri - an absolute or relative URI used as the 'Location' header value.
765 * @return Return value: the current response object.
766 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri)
767 */
768 created(uri: string): ResponseObject;
769
770 /**
771 * Sets the string encoding scheme used to serial data into the HTTP payload where:
772 * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)).
773 * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set.
774 * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
775 * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.
776 * * 'ucs2' - Alias of 'utf16le'.
777 * * '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.
778 * * '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).
779 * * 'binary' - Alias for 'latin1'.
780 * * 'hex' - Encode each byte as two hexadecimal characters.
781 * @return Return value: the current response object.
782 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding)
783 */
784 encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject;
785
786 /**
787 * Sets the representation entity tag where:
788 * @param tag - the entity tag string without the double-quote.
789 * @param options - (optional) settings where:
790 * * 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.
791 * * 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
792 * a '-' character). Ignored when weak is true. Defaults to true.
793 * @return Return value: the current response object.
794 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options)
795 */
796 etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject;
797
798 /**
799 * Sets an HTTP header where:
800 * @param name - the header name.
801 * @param value - the header value.
802 * @param options - (optional) object where:
803 * * append - if true, the value is appended to any existing header value using separator. Defaults to false.
804 * * separator - string used as separator when appending to an existing value. Defaults to ','.
805 * * override - if false, the header value is not set if an existing value present. Defaults to true.
806 * * 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.
807 * @return Return value: the current response object.
808 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options)
809 */
810 header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject;
811
812 /**
813 * Sets the HTTP 'Location' header where:
814 * @param uri - an absolute or relative URI used as the 'Location' header value.
815 * @return Return value: the current response object.
816 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri)
817 */
818 location(uri: string): ResponseObject;
819
820 /**
821 * Sets an HTTP redirection response (302) and decorates the response with additional methods, where:
822 * @param uri - an absolute or relative URI used to redirect the client to another resource.
823 * @return Return value: the current response object.
824 * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302).
825 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi)
826 */
827 redirect(uri: string): ResponseObject;
828
829 /**
830 * Sets the JSON.stringify() replacer argument where:
831 * @param method - the replacer function or array. Defaults to none.
832 * @return Return value: the current response object.
833 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod)
834 */
835 replacer(method: Json.StringifyReplacer): ResponseObject;
836
837 /**
838 * Sets the JSON.stringify() space argument where:
839 * @param count - the number of spaces to indent nested object keys. Defaults to no indentation.
840 * @return Return value: the current response object.
841 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount)
842 */
843 spaces(count: number): ResponseObject;
844
845 /**
846 * Sets an HTTP cookie where:
847 * @param name - the cookie name.
848 * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values.
849 * @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
850 * definition.
851 * @return Return value: the current response object.
852 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options)
853 */
854 state(name: string, value: object | string, options?: ServerStateCookieOptions): ResponseObject;
855
856 /**
857 * Sets a string suffix when the response is process via JSON.stringify() where:
858 * @param suffix - the string suffix.
859 * @return Return value: the current response object.
860 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix)
861 */
862 suffix(suffix: string): ResponseObject;
863
864 /**
865 * Overrides the default route cache expiration rule for this response instance where:
866 * @param msec - the time-to-live value in milliseconds.
867 * @return Return value: the current response object.
868 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec)
869 */
870 ttl(msec: number): ResponseObject;
871
872 /**
873 * Sets the HTTP 'Content-Type' header where:
874 * @param mimeType - is the mime type.
875 * @return Return value: the current response object.
876 * Should only be used to override the built-in default for each response type.
877 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype)
878 */
879 type(mimeType: string): ResponseObject;
880
881 /**
882 * Clears the HTTP cookie by setting an expired value where:
883 * @param name - the cookie name.
884 * @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
885 * definition.
886 * @return Return value: the current response object.
887 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options)
888 */
889 unstate(name: string, options?: ServerStateCookieOptions): ResponseObject;
890
891 /**
892 * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where:
893 * @param header - the HTTP request header name.
894 * @return Return value: the current response object.
895 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader)
896 */
897 vary(header: string): ResponseObject;
898
899 /**
900 * Marks the response object as a takeover response.
901 * @return Return value: the current response object.
902 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover)
903 */
904 takeover(): ResponseObject;
905
906 /**
907 * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where:
908 * @param isTemporary - if false, sets status to permanent. Defaults to true.
909 * @return Return value: the current response object.
910 * Only available after calling the response.redirect() method.
911 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary)
912 */
913 temporary(isTemporary: boolean): ResponseObject;
914
915 /**
916 * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where:
917 * @param isPermanent - if false, sets status to temporary. Defaults to true.
918 * @return Return value: the current response object.
919 * Only available after calling the response.redirect() method.
920 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent)
921 */
922 permanent(isPermanent: boolean): ResponseObject;
923
924 /**
925 * 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'
926 * to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments:
927 * @param isRewritable - if false, sets to non-rewritable. Defaults to true.
928 * @return Return value: the current response object.
929 * Only available after calling the response.redirect() method.
930 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable)
931 */
932 rewritable(isRewritable: boolean): ResponseObject;
933}
934
935/**
936 * Object containing the response handling flags.
937 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings)
938 */
939export interface ResponseSettings {
940 /**
941 * Defaults value: true.
942 * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response.
943 */
944 readonly passThrough: boolean;
945
946 /**
947 * @default null (use route defaults).
948 * Override the route json options used when source value requires stringification.
949 */
950 readonly stringify: Json.StringifyArguments;
951
952 /**
953 * @default null (use route defaults).
954 * If set, overrides the route cache with an expiration value in milliseconds.
955 */
956 readonly ttl: number;
957
958 /**
959 * @default false.
960 * 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.
961 */
962 varyEtag: boolean;
963}
964
965/**
966 * See more about Lifecycle
967 * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle
968 *
969 */
970
971export type ResponseValue = string | object;
972
973export interface AuthenticationData {
974 credentials: AuthCredentials;
975 artifacts?: object;
976}
977
978export interface Auth {
979 readonly isAuth: true;
980 readonly error?: Error | null;
981 readonly data?: AuthenticationData;
982}
983
984/**
985 * 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)
986 * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the
987 * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this
988 * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi.
989 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit)
990 */
991export interface ResponseToolkit {
992 /**
993 * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step
994 * without further interaction with the node response stream. It is the developer's responsibility to write
995 * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw).
996 */
997 readonly abandon: symbol;
998
999 /**
1000 * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after
1001 * calling request.raw.res.end()) to close the the node response stream.
1002 */
1003 readonly close: symbol;
1004
1005 /**
1006 * 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)
1007 * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()).
1008 */
1009 readonly context: any;
1010
1011 /**
1012 * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response.
1013 */
1014 readonly continue: symbol;
1015
1016 /**
1017 * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching
1018 * route. Defaults to the root server realm in the onRequest step.
1019 */
1020 readonly realm: ServerRealm;
1021
1022 /**
1023 * Access: read only and public request interface.
1024 * The [request] object. This is a duplication of the request lifecycle method argument used by
1025 * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request.
1026 */
1027 readonly request: Readonly<Request>;
1028
1029 /**
1030 * Used by the [authentication] method to pass back valid credentials where:
1031 * @param data - an object with:
1032 * * credentials - (required) object representing the authenticated entity.
1033 * * artifacts - (optional) authentication artifacts object specific to the authentication scheme.
1034 * @return Return value: an internal authentication object.
1035 */
1036 authenticated(data: AuthenticationData): Auth;
1037
1038 /**
1039 * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if
1040 * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request
1041 * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will
1042 * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined.
1043 * The method argumetns are:
1044 * @param options - a required configuration object with:
1045 * * etag - the ETag string. Required if modified is not present. Defaults to no header.
1046 * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header.
1047 * * vary - same as the response.etag() option. Defaults to true.
1048 * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed.
1049 * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned,
1050 * it should be used as the return value (but may be customize using the response methods).
1051 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions)
1052 */
1053 entity(options?: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined;
1054
1055 /**
1056 * Redirects the client to the specified uri. Same as calling h.response().redirect(uri).
1057 * @param url
1058 * @return Returns a response object.
1059 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi)
1060 */
1061 redirect(uri?: string): ResponseObject;
1062
1063 /**
1064 * Wraps the provided value and returns a response object which allows customizing the response
1065 * (e.g. setting the HTTP status code, custom headers, etc.), where:
1066 * @param value - (optional) return value. Defaults to null.
1067 * @return Returns a response object.
1068 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue)
1069 */
1070 response(value?: ResponseValue): ResponseObject;
1071
1072 /**
1073 * Sets a response cookie using the same arguments as response.state().
1074 * @param name of the cookie
1075 * @param value of the cookie
1076 * @param (optional) ServerStateCookieOptions object.
1077 * @return Return value: none.
1078 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options)
1079 */
1080 state(name: string, value: string | object, options?: ServerStateCookieOptions): void;
1081
1082 /**
1083 * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where:
1084 * @param error - (required) the authentication error.
1085 * @param data - (optional) an object with:
1086 * * credentials - (required) object representing the authenticated entity.
1087 * * artifacts - (optional) authentication artifacts object specific to the authentication scheme.
1088 * @return void.
1089 * The method is used to pass both the authentication error and the credentials. For example, if a request included
1090 * expired credentials, it allows the method to pass back the user information (combined with a 'try'
1091 * authentication mode) for error customization.
1092 * 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.
1093 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data)
1094 */
1095 unauthenticated(error: Error, data?: AuthenticationData): void;
1096
1097 /**
1098 * Clears a response cookie using the same arguments as
1099 * @param name of the cookie
1100 * @param options (optional) ServerStateCookieOptions object.
1101 * @return void.
1102 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options)
1103 */
1104 unstate(name: string, options?: ServerStateCookieOptions): void;
1105}
1106
1107/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1108 + +
1109 + +
1110 + +
1111 + Route +
1112 + +
1113 + +
1114 + +
1115 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
1116
1117export type RouteOptionsAccessScope = false | string | string[];
1118
1119export type AccessEntity = 'any' | 'user' | 'app';
1120
1121export interface RouteOptionsAccessScopeObject {
1122 scope: RouteOptionsAccessScope;
1123}
1124
1125export interface RouteOptionsAccessEntityObject {
1126 entity: AccessEntity;
1127}
1128
1129export type RouteOptionsAccessObject =
1130 RouteOptionsAccessScopeObject
1131 | RouteOptionsAccessEntityObject
1132 | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject);
1133
1134/**
1135 * Route Authentication Options
1136 */
1137export interface RouteOptionsAccess {
1138 /**
1139 * @default none.
1140 * 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
1141 * must include at least one of scope or entity.
1142 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess)
1143 */
1144 access?: RouteOptionsAccessObject | RouteOptionsAccessObject[];
1145
1146 /**
1147 * @default false (no scope requirements).
1148 * 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
1149 * 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
1150 * 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
1151 * 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}'.
1152 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope)
1153 */
1154 scope?: RouteOptionsAccessScope;
1155
1156 /**
1157 * @default 'any'.
1158 * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values:
1159 * * 'any' - the authentication can be on behalf of a user or application.
1160 * * '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.
1161 * * '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
1162 * strategy.
1163 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity)
1164 */
1165 entity?: AccessEntity;
1166
1167 /**
1168 * @default 'required'.
1169 * The authentication mode. Available values:
1170 * * 'required' - authentication is required.
1171 * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all.
1172 * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error.
1173 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode)
1174 */
1175 mode?: AuthMode;
1176
1177 /**
1178 * @default false, unless the scheme requires payload authentication.
1179 * 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'
1180 * when the scheme sets the authentication options.payload to true. Available values:
1181 * * false - no payload authentication.
1182 * * 'required' - payload authentication required.
1183 * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk).
1184 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload)
1185 */
1186 payload?: false | 'required' | 'optional';
1187
1188 /**
1189 * @default the default strategy set via server.auth.default().
1190 * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy.
1191 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies)
1192 */
1193 strategies?: string[];
1194
1195 /**
1196 * @default the default strategy set via server.auth.default().
1197 * A string strategy names. Cannot be used together with strategies.
1198 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy)
1199 */
1200 strategy?: string;
1201}
1202
1203/**
1204 * Values are:
1205 * * * 'default' - no privacy flag.
1206 * * * 'public' - mark the response as suitable for public caching.
1207 * * * 'private' - mark the response as suitable only for private caching.
1208 * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
1209 * * 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.
1210 * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive.
1211 * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled.
1212 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache)
1213 */
1214export type RouteOptionsCache = {
1215 privacy?: 'default' | 'public' | 'private';
1216 statuses?: number[];
1217 otherwise?: string;
1218} & (
1219 {
1220 expiresIn?: number;
1221 expiresAt?: undefined;
1222 } | {
1223 expiresIn?: undefined;
1224 expiresAt?: string;
1225} | {
1226 expiresIn?: undefined;
1227 expiresAt?: undefined;
1228}
1229 );
1230
1231/**
1232 * @default false (no CORS headers).
1233 * 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
1234 * than the API server. To enable, set cors to true, or to an object with the following options:
1235 * * 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
1236 * 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 '*'.
1237 * Defaults to any origin ['*'].
1238 * * 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.
1239 * Defaults to 86400 (one day).
1240 * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'].
1241 * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place.
1242 * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization'].
1243 * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place.
1244 * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false.
1245 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors)
1246 */
1247export interface RouteOptionsCors {
1248 /**
1249 * 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 '*'
1250 * 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
1251 * origin ['*'].
1252 */
1253 origin?: string[] | '*' | 'ignore';
1254 /**
1255 * 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.
1256 * Defaults to 86400 (one day).
1257 */
1258 maxAge?: number;
1259 /**
1260 * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'].
1261 */
1262 headers?: string[];
1263 /**
1264 * a strings array of additional headers to headers. Use this to keep the default headers in place.
1265 */
1266 additionalHeaders?: string[];
1267 /**
1268 * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization'].
1269 */
1270 exposedHeaders?: string[];
1271 /**
1272 * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place.
1273 */
1274 additionalExposedHeaders?: string[];
1275 /**
1276 * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false.
1277 */
1278 credentials?: boolean;
1279}
1280
1281/**
1282 * The value must be one of:
1283 * * '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
1284 * Buffer is returned.
1285 * * '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
1286 * 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
1287 * 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
1288 * multipart payload in the handler using a streaming parser (e.g. pez).
1289 * * '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
1290 * 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
1291 * which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. For context [See
1292 * docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput)
1293 */
1294export type PayloadOutput = 'data' | 'stream' | 'file';
1295
1296/**
1297 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression)
1298 */
1299export type PayloadCompressionDecoderSettings = object;
1300
1301/**
1302 * Determines how the request payload is processed.
1303 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload)
1304 */
1305export interface RouteOptionsPayload {
1306 /**
1307 * @default allows parsing of the following mime types:
1308 * * application/json
1309 * * application/*+json
1310 * * application/octet-stream
1311 * * application/x-www-form-urlencoded
1312 * * multipart/form-data
1313 * * text/*
1314 * 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
1315 * above will not enable them to be parsed, and if parse is true, the request will result in an error response.
1316 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow)
1317 */
1318 allow?: string | string[];
1319
1320 /**
1321 * @default none.
1322 * 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.
1323 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression)
1324 */
1325 compression?: Util.Dictionary<PayloadCompressionDecoderSettings>;
1326
1327 /**
1328 * @default 'application/json'.
1329 * The default content type if the 'Content-Type' request header is missing.
1330 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype)
1331 */
1332 defaultContentType?: string;
1333
1334 /**
1335 * @default 'error' (return a Bad Request (400) error response).
1336 * A failAction value which determines how to handle payload parsing errors.
1337 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction)
1338 */
1339 failAction?: Lifecycle.FailAction;
1340
1341 /**
1342 * @default 1048576 (1MB).
1343 * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory.
1344 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes)
1345 */
1346 maxBytes?: number;
1347
1348 /**
1349 * @default none.
1350 * Overrides payload processing for multipart requests. Value can be one of:
1351 * * false - disable multipart processing.
1352 * an object with the following required options:
1353 * * output - same as the output option with an additional value option:
1354 * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this?
1355 * * * * headers - the part headers.
1356 * * * * filename - the part file name.
1357 * * * * payload - the processed part payload.
1358 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart)
1359 */
1360 multipart?: false | {
1361 output: PayloadOutput | 'annotated';
1362 };
1363
1364 /**
1365 * @default 'data'.
1366 * The processed payload format. The value must be one of:
1367 * * '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
1368 * Buffer is returned.
1369 * * '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
1370 * 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
1371 * 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
1372 * multipart payload in the handler using a streaming parser (e.g. pez).
1373 * * '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
1374 * 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
1375 * of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup.
1376 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput)
1377 */
1378 output?: PayloadOutput;
1379
1380 /**
1381 * @default none.
1382 * A mime type string overriding the 'Content-Type' header value received.
1383 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride)
1384 */
1385 override?: string;
1386
1387 /**
1388 * @default true.
1389 * Determines if the incoming payload is processed or presented raw. Available values:
1390 * * 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
1391 * format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded.
1392 * * false - the raw payload is returned unmodified.
1393 * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded.
1394 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse)
1395 */
1396 parse?: boolean | 'gunzip';
1397
1398 /**
1399 * @default to 10000 (10 seconds).
1400 * 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)
1401 * error response. Set to false to disable.
1402 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout)
1403 */
1404 timeout?: false | number;
1405
1406 /**
1407 * @default os.tmpdir().
1408 * The directory used for writing file uploads.
1409 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads)
1410 */
1411 uploads?: string;
1412}
1413
1414/**
1415 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1416 */
1417export type RouteOptionsPreArray = RouteOptionsPreAllOptions[];
1418
1419/**
1420 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1421 */
1422export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method;
1423
1424/**
1425 * An object with:
1426 * * method - a lifecycle method.
1427 * * assign - key name used to assign the response of the method to in request.pre and request.preResponses.
1428 * * 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.
1429 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1430 */
1431export interface RouteOptionsPreObject {
1432 /**
1433 * a lifecycle method.
1434 */
1435 method: Lifecycle.Method;
1436 /**
1437 * key name used to assign the response of the method to in request.pre and request.preResponses.
1438 */
1439 assign?: string;
1440 /**
1441 * 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.
1442 */
1443 failAction?: Lifecycle.FailAction;
1444}
1445
1446export type ValidationObject = SchemaMap;
1447
1448/**
1449 * * true - any query parameter value allowed (no validation performed). false - no parameter value allowed.
1450 * * a joi validation object.
1451 * * a validation function using the signature async function(value, options) where:
1452 * * * value - the request.* object containing the request parameters.
1453 * * * options - options.
1454 */
1455export type RouteOptionsResponseSchema =
1456 boolean
1457 | ValidationObject
1458 | Schema
1459 | ((value: object | Buffer | string, options: ValidationOptions) => Promise<any>);
1460
1461/**
1462 * Processing rules for the outgoing response.
1463 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse)
1464 */
1465export interface RouteOptionsResponse {
1466 /**
1467 * @default 204.
1468 * 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
1469 * response status code will remain 200 throughout the request lifecycle unless manually set).
1470 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode)
1471 */
1472 emptyStatusCode?: 200 | 204;
1473
1474 /**
1475 * @default 'error' (return an Internal Server Error (500) error response).
1476 * A failAction value which defines what to do when a response fails payload validation.
1477 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction)
1478 */
1479 failAction?: Lifecycle.FailAction;
1480
1481 /**
1482 * @default false.
1483 * If true, applies the validation rule changes to the response payload.
1484 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify)
1485 */
1486 modify?: boolean;
1487
1488 /**
1489 * @default none.
1490 * [joi](http://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
1491 * 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.
1492 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions)
1493 */
1494 options?: ValidationOptions; // TODO needs validation
1495
1496 /**
1497 * @default true.
1498 * If false, payload range support is disabled.
1499 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges)
1500 */
1501 ranges?: boolean;
1502
1503 /**
1504 * @default 100 (all responses).
1505 * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation.
1506 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample)
1507 */
1508 sample?: number;
1509
1510 /**
1511 * @default true (no validation).
1512 * The default response payload validation rules (for all non-error responses) expressed as one of:
1513 * * true - any payload allowed (no validation).
1514 * * false - no payload allowed.
1515 * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function.
1516 * * a validation function using the signature async function(value, options) where:
1517 * * * value - the pending response payload.
1518 * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }).
1519 * * * 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
1520 * output.payload. If an error is thrown, the error is processed according to failAction.
1521 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema)
1522 */
1523 schema?: RouteOptionsResponseSchema;
1524
1525 /**
1526 * @default none.
1527 * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema.
1528 * 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.
1529 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus)
1530 */
1531 status?: Util.Dictionary<RouteOptionsResponseSchema>;
1532
1533 /**
1534 * The default HTTP status code used to set a response error when the request is closed or aborted before the
1535 * response is fully transmitted.
1536 * Value can be any integer greater or equal to 400.
1537 * The default value 499 is based on the non-standard nginx "CLIENT CLOSED REQUEST" error.
1538 * The value is only used for logging as the request has already ended.
1539 * @default 499
1540 */
1541 disconnectStatusCode?: number;
1542}
1543
1544/**
1545 * @see https://www.w3.org/TR/referrer-policy/
1546 */
1547export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'unsafe-url' |
1548 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin';
1549
1550/**
1551 * @default false (security headers disabled).
1552 * Sets common security headers. To enable, set security to true or to an object with the following options:
1553 * * hsts - controls the 'Strict-Transport-Security' header, where:
1554 * * * true - the header will be set to max-age=15768000. This is the default value.
1555 * * * a number - the maxAge parameter will be set to the provided value.
1556 * * * an object with the following fields:
1557 * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000.
1558 * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header.
1559 * * * * 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.
1560 * * xframe - controls the 'X-Frame-Options' header, where:
1561 * * * true - the header will be set to 'DENY'. This is the default value.
1562 * * * 'deny' - the headers will be set to 'DENY'.
1563 * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'.
1564 * * * an object for specifying the 'allow-from' rule, where:
1565 * * * * rule - one of:
1566 * * * * * 'deny'
1567 * * * * * 'sameorigin'
1568 * * * * * 'allow-from'
1569 * * * * 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
1570 * changed to 'sameorigin'.
1571 * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'.
1572 * 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
1573 * support old versions of IE, it may be wise to explicitly set this flag to false.
1574 * * 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'.
1575 * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'.
1576 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity)
1577 */
1578export interface RouteOptionsSecureObject {
1579 /**
1580 * hsts - controls the 'Strict-Transport-Security' header
1581 */
1582 hsts?: boolean | number | {
1583 /**
1584 * the max-age portion of the header, as a number. Default is 15768000.
1585 */
1586 maxAge: number;
1587 /**
1588 * a boolean specifying whether to add the includeSubDomains flag to the header.
1589 */
1590 includeSubDomains: boolean;
1591 /**
1592 * 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.
1593 */
1594 preload: boolean;
1595 };
1596 /**
1597 * controls the 'X-Frame-Options' header
1598 */
1599 xframe?: true | 'deny' | 'sameorigin' | {
1600 /**
1601 * an object for specifying the 'allow-from' rule,
1602 */
1603 rule: 'deny' | 'sameorigin' | 'allow-from';
1604 /**
1605 * 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 changed
1606 * to 'sameorigin'.
1607 */
1608 source: string;
1609 };
1610 /**
1611 * boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'.
1612 * 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
1613 * support old versions of IE, it may be wise to explicitly set this flag to false.
1614 */
1615 xss: boolean;
1616 /**
1617 * 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'.
1618 */
1619 noOpen?: boolean;
1620 /**
1621 * boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'.
1622 */
1623 noSniff?: boolean;
1624
1625 /**
1626 * Controls the `Referrer-Policy` header, which has the following possible values.
1627 * @default false Header will not be send.
1628 */
1629 referrer?: false | ReferrerPolicy;
1630}
1631
1632export type RouteOptionsSecure = boolean | RouteOptionsSecureObject;
1633
1634/**
1635 * @default { headers: true, params: true, query: true, payload: true, failAction: 'error' }.
1636 * Request input validation rules for various request components.
1637 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate)
1638 */
1639export interface RouteOptionsValidate {
1640 /**
1641 * @default none.
1642 * An optional object with error fields copied into every validation error response.
1643 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields)
1644 */
1645 errorFields?: object;
1646
1647 /**
1648 * @default 'error' (return a Bad Request (400) error response).
1649 * A failAction value which determines how to handle failed validations. When set to a function, the err argument includes the type of validation error under err.output.payload.validation.source.
1650 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction)
1651 */
1652 failAction?: Lifecycle.FailAction;
1653
1654 /**
1655 * Validation rules for incoming request headers:
1656 * * If a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error
1657 * is thrown, the error is handled according to failAction. Note that all header field names must be in lowercase to match the headers normalized by node.
1658 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders)
1659 * @default true
1660 */
1661 headers?: RouteOptionsResponseSchema;
1662
1663 /**
1664 * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here).
1665 * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter.
1666 * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as
1667 * Joi.ref('$query.key')).
1668 * Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated
1669 * will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the
1670 * individual route settings override the routes defaults (the rules are not merged).
1671 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams)
1672 * @default true
1673 */
1674 options?: ValidationOptions | object;
1675
1676 /**
1677 * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where:
1678 * * true - any path parameter value allowed (no validation performed).
1679 * * a joi validation object.
1680 * * a validation function using the signature async function(value, options) where:
1681 * * * value - the request.params object containing the request path parameters.
1682 * * * options - options.
1683 * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an
1684 * error is thrown, the error is handled according to failAction. Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail.
1685 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams)
1686 * @default true
1687 */
1688 params?: RouteOptionsResponseSchema;
1689
1690 /**
1691 * Validation rules for incoming request payload (request body), where:
1692 * * If a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is
1693 * thrown, the error is handled according to failAction. Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well
1694 * as the significant performance cost of validating large amounts of data.
1695 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload)
1696 * @default true
1697 */
1698 payload?: RouteOptionsResponseSchema;
1699
1700 /**
1701 * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in
1702 * request.query prior to validation. Where:
1703 * * If a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged.
1704 * If an error
1705 * is thrown, the error is handled according to failAction. Note that changes to the query parameters will not be reflected in request.url.
1706 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery)
1707 * @default true
1708 */
1709 query?: RouteOptionsResponseSchema;
1710
1711 /**
1712 * Validation rules for incoming cookies.
1713 * The cookie header is parsed and decoded into the request.state prior to validation.
1714 * @default true
1715 */
1716 state?: RouteOptionsResponseSchema;
1717}
1718
1719/**
1720 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression)
1721 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder)
1722 */
1723export type RouteCompressionEncoderSettings = object;
1724
1725/**
1726 * Empty interface to allow for user-defined augmentations.
1727 */
1728/* tslint:disable-next-line:no-empty-interface */
1729export interface RouteOptionsApp {
1730}
1731
1732export interface CommonRouteProperties {
1733 /**
1734 * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead.
1735 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp)
1736 */
1737 app?: RouteOptionsApp;
1738
1739 /**
1740 * @default null.
1741 * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function.
1742 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind)
1743 */
1744 bind?: object | null;
1745
1746 /**
1747 * @default { privacy: 'default', statuses: [200], otherwise: 'no-cache' }.
1748 * If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options:
1749 * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are:
1750 * * * 'default' - no privacy flag.
1751 * * * 'public' - mark the response as suitable for public caching.
1752 * * * 'private' - mark the response as suitable only for private caching.
1753 * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
1754 * * 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.
1755 * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive.
1756 * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled.
1757 * The default Cache-Control: no-cache header can be disabled by setting cache to false.
1758 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache)
1759 */
1760 cache?: false | RouteOptionsCache;
1761
1762 /**
1763 * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression.
1764 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression)
1765 */
1766 compression?: Util.Dictionary<RouteCompressionEncoderSettings>;
1767
1768 /**
1769 * @default false (no CORS headers).
1770 * 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
1771 * domain than the API server. To enable, set cors to true, or to an object with the following options:
1772 * * 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
1773 * 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 '*'.
1774 * Defaults to any origin ['*'].
1775 * * 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
1776 * policy. Defaults to 86400 (one day).
1777 * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'].
1778 * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place.
1779 * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization'].
1780 * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place.
1781 * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false.
1782 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors)
1783 */
1784 cors?: boolean | RouteOptionsCors;
1785
1786 /**
1787 * @default none.
1788 * Route description used for generating documentation (string).
1789 * This setting is not available when setting server route defaults using server.options.routes.
1790 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription)
1791 */
1792 description?: string;
1793
1794 /**
1795 * @default none.
1796 * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the
1797 * server.ext(events) event argument.
1798 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext)
1799 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle)
1800 */
1801 ext?: {
1802 [key in RouteRequestExtType]?: RouteExtObject | RouteExtObject[];
1803 };
1804
1805 /**
1806 * @default { relativeTo: '.' }.
1807 * Defines the behavior for accessing files:
1808 * * relativeTo - determines the folder relative paths are resolved against.
1809 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles)
1810 */
1811 files?: {
1812 relativeTo: string;
1813 };
1814
1815 /**
1816 * @default none.
1817 * The route handler function performs the main business logic of the route and sets the response. handler can be assigned:
1818 * * a lifecycle method.
1819 * * an object with a single property using the name of a handler type registred with the server.handler() method. The matching property value is passed as options to the registered handler
1820 * generator. Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context.
1821 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler)
1822 */
1823 handler?: Lifecycle.Method | object;
1824
1825 /**
1826 * @default none.
1827 * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods.
1828 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid)
1829 */
1830 id?: string;
1831
1832 /**
1833 * @default false.
1834 * If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should
1835 * not be accessible to the outside world.
1836 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal)
1837 */
1838 isInternal?: boolean;
1839
1840 /**
1841 * @default none.
1842 * Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following:
1843 * * replacer - the replacer function or array. Defaults to no action.
1844 * * space - number of spaces to indent nested object keys. Defaults to no indentation.
1845 * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix.
1846 * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false.
1847 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson)
1848 */
1849 json?: Json.StringifyArguments;
1850
1851 /**
1852 * @default none.
1853 * Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.
1854 * For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Cannot be used with stream
1855 * responses. The 'Content-Type' response header is set to 'text/javascript' and the 'X-Content-Type-Options' response header is set to 'nosniff', and will override those headers even if
1856 * explicitly set by response.type().
1857 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjsonp)
1858 */
1859 jsonp?: string;
1860
1861 /**
1862 * @default { collect: false }.
1863 * Request logging options:
1864 * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs.
1865 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog)
1866 */
1867 log?: {
1868 collect: boolean;
1869 };
1870
1871 /**
1872 * @default none.
1873 * Route notes used for generating documentation (string or array of strings).
1874 * This setting is not available when setting server route defaults using server.options.routes.
1875 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes)
1876 */
1877 notes?: string | string[];
1878
1879 /**
1880 * Determines how the request payload is processed.
1881 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload)
1882 */
1883 payload?: RouteOptionsPayload;
1884
1885 /**
1886 * @default {}.
1887 * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration.
1888 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins)
1889 */
1890 plugins?: PluginSpecificConfiguration;
1891
1892 /**
1893 * @default none.
1894 * The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared
1895 * ascross routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). pre is assigned an ordered array of methods which
1896 * are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of
1897 * the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. pre can be assigned a mixed array of:
1898 * * an array containing the elements listed below, which are executed in parallel.
1899 * * an object with:
1900 * * * method - a lifecycle method.
1901 * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses.
1902 * * * 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
1903 * assigned.
1904 * * a method function - same as including an object with a single method key.
1905 * Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used
1906 * to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other
1907 * lifecycle methods.
1908 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1909 */
1910 pre?: RouteOptionsPreArray;
1911
1912 /**
1913 * Processing rules for the outgoing response.
1914 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse)
1915 */
1916 response?: RouteOptionsResponse;
1917
1918 /**
1919 * @default false (security headers disabled).
1920 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity)
1921 */
1922 security?: RouteOptionsSecure;
1923
1924 /**
1925 * @default { parse: true, failAction: 'error' }.
1926 * HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following
1927 * options: parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. failAction - A failAction value which determines how to handle cookie parsing
1928 * errors. Defaults to 'error' (return a Bad Request (400) error response).
1929 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate)
1930 */
1931 state?: {
1932 parse?: boolean;
1933 failAction?: Lifecycle.FailAction;
1934 };
1935
1936 /**
1937 * @default none.
1938 * Route tags used for generating documentation (array of strings).
1939 * This setting is not available when setting server route defaults using server.options.routes.
1940 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags)
1941 */
1942 tags?: string[];
1943
1944 /**
1945 * @default { server: false }.
1946 * Timeouts for processing durations.
1947 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout)
1948 */
1949 timeout?: {
1950 /**
1951 * Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error
1952 * response.
1953 */
1954 server?: boolean | number;
1955
1956 /**
1957 * @default none (use node default of 2 minutes).
1958 * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts.
1959 */
1960 socket?: boolean | number;
1961 };
1962
1963 /**
1964 * @default { headers: true, params: true, query: true, payload: true, failAction: 'error' }.
1965 * Request input validation rules for various request components.
1966 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate)
1967 */
1968 validate?: RouteOptionsValidate;
1969}
1970
1971export interface AccessScopes {
1972 forbidden?: string[];
1973 required?: string[];
1974 selection?: string[];
1975}
1976
1977export interface AccessSetting {
1978 entity?: AccessEntity;
1979 scope: AccessScopes | false;
1980}
1981
1982export interface AuthSettings {
1983 strategies: string[];
1984 mode: AuthMode;
1985 access?: AccessSetting[];
1986}
1987
1988export interface RouteSettings extends CommonRouteProperties {
1989 auth?: AuthSettings;
1990}
1991
1992/**
1993 * Each route can be customized to change the default behavior of the request lifecycle.
1994 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options)
1995 */
1996export interface RouteOptions extends CommonRouteProperties {
1997 /**
1998 * Route authentication configuration. Value can be:
1999 * false to disable authentication if a default strategy is set.
2000 * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode.
2001 * an authentication configuration object.
2002 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp)
2003 */
2004 auth?: false | string | RouteOptionsAccess;
2005}
2006
2007/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
2008 + +
2009 + +
2010 + +
2011 + Server +
2012 + +
2013 + +
2014 + +
2015 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
2016
2017/**
2018 * The scheme options argument passed to server.auth.strategy() when instantiation a strategy.
2019 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme)
2020 */
2021export type ServerAuthSchemeOptions = object;
2022
2023/**
2024 * the method implementing the scheme with signature function(server, options) where:
2025 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme)
2026 * @param server - a reference to the server object the scheme is added to.
2027 * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy.
2028 */
2029export type ServerAuthScheme = (server: Server, options?: ServerAuthSchemeOptions) => ServerAuthSchemeObject;
2030
2031/* tslint:disable-next-line:no-empty-interface */
2032export interface ServerAuthSchemeObjectApi {
2033}
2034
2035/**
2036 * The scheme method must return an object with the following
2037 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme)
2038 */
2039export interface ServerAuthSchemeObject {
2040 /**
2041 * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object.
2042 */
2043 api?: ServerAuthSchemeObjectApi;
2044
2045 /**
2046 * A lifecycle method function called for each incoming request configured with the authentication scheme. The
2047 * method is provided with two special toolkit methods for returning an authenticated or an unauthenticate result:
2048 * * h.authenticated() - indicate request authenticated successfully.
2049 * * h.unauthenticated() - indicate request failed to authenticate.
2050 * @param request the request object.
2051 * @param h the ResponseToolkit
2052 * @return the Lifecycle.ReturnValue
2053 */
2054 authenticate(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue;
2055
2056 /**
2057 * A lifecycle method to authenticate the request payload.
2058 * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad
2059 * payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')),
2060 * authentication may still be successful if the route auth.payload configuration is set to 'optional'.
2061 * @param request the request object.
2062 * @param h the ResponseToolkit
2063 * @return the Lifecycle.ReturnValue
2064 */
2065 payload?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue;
2066
2067 /**
2068 * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written.
2069 * @param request the request object.
2070 * @param h the ResponseToolkit
2071 * @return the Lifecycle.ReturnValue
2072 */
2073 response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue;
2074
2075 /**
2076 * a method used to verify the authentication credentials provided
2077 * are still valid (e.g. not expired or revoked after the initial authentication).
2078 * the method throws an `Error` when the credentials passed are no longer valid (e.g. expired or
2079 * revoked). Note that the method does not have access to the original request, only to the
2080 * credentials and artifacts produced by the `authenticate()` method.
2081 */
2082 verify?(auth: RequestAuth): Promise<void>;
2083
2084 /**
2085 * An object with the following keys:
2086 * * payload
2087 */
2088 options?: {
2089 /**
2090 * if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.
2091 */
2092 payload?: boolean;
2093 };
2094}
2095
2096/**
2097 * An authentication configuration object using the same format as the route auth handler options.
2098 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions)
2099 */
2100/* tslint:disable-next-line:no-empty-interface */
2101export interface ServerAuthConfig extends RouteOptionsAccess {
2102}
2103
2104export interface ServerAuth {
2105 /**
2106 * An object where each key is an authentication strategy name and the value is the exposed strategy API.
2107 * Available only when the authentication scheme exposes an API by returning an api key in the object
2108 * returned from its implementation function.
2109 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi)
2110 */
2111 api: Util.Dictionary<ServerAuthSchemeObjectApi>;
2112
2113 /**
2114 * Contains the default authentication configuration is a default strategy was set via
2115 * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()).
2116 */
2117 readonly settings: {
2118 default: ServerAuthConfig;
2119 };
2120
2121 /**
2122 * Sets a default strategy which is applied to every route where:
2123 * @param options - one of:
2124 * * a string with the default strategy name
2125 * * an authentication configuration object using the same format as the route auth handler options.
2126 * @return void.
2127 * The default does not apply when a route config specifies auth as false, or has an authentication strategy
2128 * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication
2129 * config is applied to the defaults.
2130 * Note that if the route has authentication configured, the default only applies at the time of adding the route,
2131 * not at runtime. This means that calling server.auth.default() after adding a route with some authentication
2132 * config will have no impact on the routes added prior. However, the default will apply to routes added
2133 * before server.auth.default() is called if those routes lack any authentication config.
2134 * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active
2135 * authentication configuration of a route, use server.auth.lookup(request.route).
2136 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions)
2137 */
2138 default(options: string | ServerAuthConfig): void;
2139
2140 /**
2141 * Registers an authentication scheme where:
2142 * @param name the scheme name.
2143 * @param scheme - the method implementing the scheme with signature function(server, options) where:
2144 * * server - a reference to the server object the scheme is added to.
2145 * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy.
2146 * @return void.
2147 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme)
2148 */
2149 scheme(name: string, scheme: ServerAuthScheme): void;
2150
2151 /**
2152 * Registers an authentication strategy where:
2153 * @param name - the strategy name.
2154 * @param scheme - the scheme name (must be previously registered using server.auth.scheme()).
2155 * @param options - scheme options based on the scheme requirements.
2156 * @return Return value: none.
2157 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options)
2158 */
2159 strategy(name: string, scheme: string, options?: object): void;
2160
2161 /**
2162 * Tests a request against an authentication strategy where:
2163 * @param strategy - the strategy name registered with server.auth.strategy().
2164 * @param request - the request object.
2165 * @return an object containing the authentication credentials and artifacts if authentication was successful, otherwise throws an error.
2166 * Note that the test() method does not take into account the route authentication configuration. It also does not
2167 * perform payload authentication. It is limited to the basic strategy authentication execution. It does not
2168 * include verifying scope, entity, or other route properties.
2169 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request)
2170 */
2171 test(strategy: string, request: Request): Promise<AuthenticationData>;
2172
2173 /**
2174 * Verify a request's authentication credentials against an authentication strategy.
2175 * Returns nothing if verification was successful, otherwise throws an error.
2176 *
2177 * Note that the `verify()` method does not take into account the route authentication configuration
2178 * or any other information from the request other than the `request.auth` object. It also does not
2179 * perform payload authentication. It is limited to verifying that the previously valid credentials
2180 * are still valid (e.g. have not been revoked or expired). It does not include verifying scope,
2181 * entity, or other route properties.
2182 */
2183 verify(request: Request): Promise<void>;
2184}
2185
2186export type CachePolicyOptions<T> = PolicyOptionVariants<T> & {
2187 /**
2188 * @default '_default'
2189 */
2190 cache?: string;
2191 segment?: string;
2192};
2193
2194/**
2195 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions)
2196 */
2197export interface ServerCache {
2198 /**
2199 * Provisions a cache segment within the server cache facility where:
2200 * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where:
2201 * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
2202 * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn.
2203 * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where:
2204 * - `id` - the `id` string or object provided to the `get()` method.
2205 * - `flags` - an object used to pass back additional flags to the cache where:
2206 * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy.
2207 * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn.
2208 * * staleTimeout - number of milliseconds to wait before checking if an item is stale.
2209 * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it
2210 * is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever.
2211 * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true.
2212 * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true.
2213 * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true.
2214 * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of
2215 * concurrent generateFunc calls beyond staleTimeout).
2216 * * cache - the cache name configured in server.cache. Defaults to the default cache.
2217 * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a
2218 * server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin.
2219 * * shared - if true, allows multiple cache provisions to share the same segment. Default to false.
2220 * @return Catbox Policy.
2221 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions)
2222 */
2223 <T, O extends CachePolicyOptions<T> = CachePolicyOptions<T>>(options: O): Policy<T, O>;
2224
2225 /**
2226 * Provisions a server cache as described in server.cache where:
2227 * @param options - same as the server cache configuration options.
2228 * @return Return value: none.
2229 * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache.
2230 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions)
2231 */
2232 provision(options: ServerOptionsCache): Promise<void>;
2233}
2234
2235/**
2236 * an event name string.
2237 * an event options object.
2238 * a podium emitter object.
2239 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents)
2240 */
2241export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium;
2242
2243/**
2244 * Object that it will be used in Event
2245 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents)
2246 */
2247export interface ServerEventsApplicationObject {
2248 /** the event name string (required). */
2249 name: string;
2250 /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */
2251 channels?: string | string[];
2252 /**
2253 * if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is).
2254 */
2255 clone?: boolean;
2256 /**
2257 * if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified
2258 * by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type).
2259 */
2260 spread?: boolean;
2261 /**
2262 * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to
2263 * the arguments list at the end. A configuration override can be set by each listener. Defaults to false.
2264 */
2265 tags?: boolean;
2266 /**
2267 * if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first
2268 * configuration is used. Defaults to false (a duplicate registration will throw an error).
2269 */
2270 shared?: boolean;
2271}
2272
2273/**
2274 * A criteria object with the following optional keys (unless noted otherwise):
2275 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener)
2276 *
2277 * The type parameter T is the type of the name of the event.
2278 */
2279export interface ServerEventCriteria<T> {
2280 /** (required) the event name string. */
2281 name: T;
2282 /**
2283 * a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed
2284 * channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter.
2285 */
2286 channels?: string | string[];
2287 /** if true, the data object passed to server.event.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */
2288 clone?: boolean;
2289 /**
2290 * a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.events.once().
2291 * Defaults to no limit.
2292 */
2293 count?: number;
2294 /**
2295 * filter - the event tags (if present) to subscribe to which can be one of:
2296 * * a tag string.
2297 * * an array of tag strings.
2298 * * an object with the following:
2299 * * * tags - a tag string or array of tag strings.
2300 * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag).
2301 */
2302 filter?: string | string[] | {tags: string | string[], all?: boolean};
2303 /**
2304 * if true, and the data object passed to server.event.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used
2305 * when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false).
2306 */
2307 spread?: boolean;
2308 /**
2309 * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended
2310 * to the arguments list at the end. Defaults to the event registration option (which defaults to false).
2311 */
2312 tags?: boolean;
2313}
2314
2315export interface LogEvent {
2316 /** the event timestamp. */
2317 timestamp: string;
2318 /** an array of tags identifying the event (e.g. ['error', 'http']) */
2319 tags: string[];
2320 /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */
2321 channel: 'internal' | 'app';
2322 /** the request identifier. */
2323 request: string;
2324 /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */
2325 data: object;
2326 /** the error object related to the event if applicable. Cannot appear together with data */
2327 error: object;
2328}
2329
2330export interface RequestEvent {
2331 /** the event timestamp. */
2332 timestamp: string;
2333 /** an array of tags identifying the event (e.g. ['error', 'http']) */
2334 tags: string[];
2335 /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */
2336 channel: 'internal' | 'app' | 'error';
2337 /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */
2338 data: object;
2339 /** the error object related to the event if applicable. Cannot appear together with data */
2340 error: object;
2341}
2342
2343export type LogEventHandler = (event: LogEvent, tags: { [key: string]: true }) => void;
2344export type RequestEventHandler = (request: Request, event: RequestEvent, tags: { [key: string]: true }) => void;
2345export type ResponseEventHandler = (request: Request) => void;
2346export type RouteEventHandler = (route: RequestRoute) => void;
2347export type StartEventHandler = () => void;
2348export type StopEventHandler = () => void;
2349
2350export interface PodiumEvent<K extends string, T> {
2351 emit(criteria: K, listener: (value: T) => void): void;
2352
2353 on(criteria: K, listener: (value: T) => void): void;
2354
2355 once(criteria: K, listener: (value: T) => void): void;
2356
2357 once(criteria: K): Promise<T>;
2358
2359 removeListener(criteria: K, listener: Podium.Listener): this;
2360
2361 removeAllListeners(criteria: K): this;
2362
2363 hasListeners(criteria: K): this;
2364}
2365
2366/**
2367 * Access: podium public interface.
2368 * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters.
2369 * Use the following methods to interact with server.events:
2370 * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events.
2371 * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events.
2372 * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events.
2373 * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to
2374 * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name).
2375 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
2376 */
2377export interface ServerEvents extends Podium {
2378 /**
2379 * Subscribe to an event where:
2380 * @param criteria - the subscription criteria which must be one of:
2381 * * event name string which can be any of the built-in server events
2382 * * a custom application event registered with server.event().
2383 * * a criteria object
2384 * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options.
2385 * @return Return value: none.
2386 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener)
2387 * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event)
2388 * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event)
2389 * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event)
2390 * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event)
2391 * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event)
2392 * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event)
2393 */
2394 on(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): void;
2395
2396 on(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): void;
2397
2398 on(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): void;
2399
2400 on(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): void;
2401
2402 on(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): void;
2403
2404 on(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): void;
2405
2406 /**
2407 * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1.
2408 * @param criteria - the subscription criteria which must be one of:
2409 * * event name string which can be any of the built-in server events
2410 * * a custom application event registered with server.event().
2411 * * a criteria object
2412 * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options.
2413 * @return Return value: none.
2414 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener)
2415 */
2416 once(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): void;
2417
2418 once(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): void;
2419
2420 once(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): void;
2421
2422 once(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): void;
2423
2424 once(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): void;
2425
2426 once(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): void;
2427
2428 /**
2429 * Same as calling server.events.on() with the count option set to 1.
2430 * @param criteria - the subscription criteria which must be one of:
2431 * * event name string which can be any of the built-in server events
2432 * * a custom application event registered with server.event().
2433 * * a criteria object
2434 * @return Return value: a promise that resolves when the event is emitted.
2435 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria)
2436 */
2437 once(criteria: string | ServerEventCriteria<string>): Promise<any>;
2438
2439 /**
2440 * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener)
2441 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
2442 */
2443 removeListener(name: string, listener: Podium.Listener): Podium;
2444
2445 /**
2446 * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname)
2447 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
2448 */
2449 removeAllListeners(name: string): Podium;
2450
2451 /**
2452 * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname)
2453 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
2454 */
2455 hasListeners(name: string): boolean;
2456}
2457
2458/**
2459 * The extension point event name. The available extension points include the request extension points as well as the following server extension points:
2460 * 'onPreStart' - called before the connection listeners are started.
2461 * 'onPostStart' - called after the connection listeners are started.
2462 * 'onPreStop' - called before the connection listeners are stopped.
2463 * 'onPostStop' - called after the connection listeners are stopped.
2464 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
2465 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle)
2466 */
2467export type ServerExtType = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop';
2468export type RouteRequestExtType = 'onPreAuth'
2469 | 'onCredentials'
2470 | 'onPostAuth'
2471 | 'onPreHandler'
2472 | 'onPostHandler'
2473 | 'onPreResponse';
2474
2475export type ServerRequestExtType =
2476 RouteRequestExtType
2477 | 'onRequest';
2478
2479/**
2480 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
2481 * Registers an extension function in one of the request lifecycle extension points where:
2482 * @param events - an object or array of objects with the following:
2483 * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
2484 * * * 'onPreStart' - called before the connection listeners are started.
2485 * * * 'onPostStart' - called after the connection listeners are started.
2486 * * * 'onPreStop' - called before the connection listeners are stopped.
2487 * * * 'onPostStop' - called after the connection listeners are stopped.
2488 * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is:
2489 * * * server extension points: async function(server) where:
2490 * * * * server - the server object.
2491 * * * * this - the object provided via options.bind or the current active context set with server.bind().
2492 * * * request extension points: a lifecycle method.
2493 * * options - (optional) an object with the following:
2494 * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
2495 * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
2496 * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2497 * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or
2498 * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
2499 * @return void
2500 */
2501export interface ServerExtEventsObject {
2502 /**
2503 * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
2504 * * 'onPreStart' - called before the connection listeners are started.
2505 * * 'onPostStart' - called after the connection listeners are started.
2506 * * 'onPreStop' - called before the connection listeners are stopped.
2507 */
2508 type: ServerExtType;
2509 /**
2510 * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is:
2511 * * server extension points: async function(server) where:
2512 * * * server - the server object.
2513 * * * this - the object provided via options.bind or the current active context set with server.bind().
2514 * * request extension points: a lifecycle method.
2515 */
2516 method: ServerExtPointFunction | ServerExtPointFunction[];
2517 options?: ServerExtOptions;
2518}
2519
2520export interface RouteExtObject {
2521 method: Lifecycle.Method;
2522 options?: ServerExtOptions;
2523}
2524
2525/**
2526 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
2527 * Registers an extension function in one of the request lifecycle extension points where:
2528 * @param events - an object or array of objects with the following:
2529 * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
2530 * * * 'onPreStart' - called before the connection listeners are started.
2531 * * * 'onPostStart' - called after the connection listeners are started.
2532 * * * 'onPreStop' - called before the connection listeners are stopped.
2533 * * * 'onPostStop' - called after the connection listeners are stopped.
2534 * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is:
2535 * * * server extension points: async function(server) where:
2536 * * * * server - the server object.
2537 * * * * this - the object provided via options.bind or the current active context set with server.bind().
2538 * * * request extension points: a lifecycle method.
2539 * * options - (optional) an object with the following:
2540 * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
2541 * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
2542 * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2543 * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or
2544 * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
2545 * @return void
2546 */
2547export interface ServerExtEventsRequestObject {
2548 /**
2549 * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
2550 * * 'onPreStart' - called before the connection listeners are started.
2551 * * 'onPostStart' - called after the connection listeners are started.
2552 * * 'onPreStop' - called before the connection listeners are stopped.
2553 * * 'onPostStop' - called after the connection listeners are stopped.
2554 */
2555 type: ServerRequestExtType;
2556 /**
2557 * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is:
2558 * * server extension points: async function(server) where:
2559 * * * server - the server object.
2560 * * * this - the object provided via options.bind or the current active context set with server.bind().
2561 * * request extension points: a lifecycle method.
2562 */
2563 method: Lifecycle.Method | Lifecycle.Method[];
2564 /**
2565 * (optional) an object with the following:
2566 * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
2567 * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
2568 * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2569 * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions,
2570 * or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
2571 */
2572 options?: ServerExtOptions;
2573}
2574
2575export type ServerExtPointFunction = (server: Server) => void;
2576
2577/**
2578 * An object with the following:
2579 * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
2580 * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
2581 * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2582 * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or
2583 * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. For context [See
2584 * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
2585 */
2586export interface ServerExtOptions {
2587 /**
2588 * a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
2589 */
2590 before?: string | string[];
2591 /**
2592 * a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
2593 */
2594 after?: string | string[];
2595 /**
2596 * a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2597 */
2598 bind?: object;
2599 /**
2600 * if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when
2601 * adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
2602 */
2603 sandbox?: 'server' | 'plugin';
2604}
2605
2606/**
2607 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo)
2608 * An object containing information about the server where:
2609 */
2610export interface ServerInfo {
2611 /**
2612 * a unique server identifier (using the format '{hostname}:{pid}:{now base36}').
2613 */
2614 id: string;
2615
2616 /**
2617 * server creation timestamp.
2618 */
2619 created: number;
2620
2621 /**
2622 * server start timestamp (0 when stopped).
2623 */
2624 started: number;
2625
2626 /**
2627 * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules:
2628 * * before the server has been started: the configured port value.
2629 * * after the server has been started: the actual port assigned when no port is configured or was set to 0.
2630 */
2631 port: number | string;
2632
2633 /**
2634 * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value.
2635 */
2636 host: string;
2637
2638 /**
2639 * the active IP address the connection was bound to after starting. Set to undefined until the server has been
2640 * started or when using a non TCP port (e.g. UNIX domain socket).
2641 */
2642 address: undefined | string;
2643
2644 /**
2645 * the protocol used:
2646 * * 'http' - HTTP.
2647 * * 'https' - HTTPS.
2648 * * 'socket' - UNIX domain socket or Windows named pipe.
2649 */
2650 protocol: 'http' | 'https' | 'socket';
2651
2652 /**
2653 * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains
2654 * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set
2655 * to 0, the uri will not include a port component until the server is started.
2656 */
2657 uri: string;
2658}
2659
2660/**
2661 * An object with:
2662 * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'.
2663 * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.
2664 * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers.
2665 * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload
2666 * processing defaults to 'application/json' if no 'Content-Type' header provided.
2667 * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if
2668 * they were received via an authentication scheme. Defaults to no credentials.
2669 * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as
2670 * if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.
2671 * * app - (optional) sets the initial value of request.app, defaults to {}.
2672 * * plugins - (optional) sets the initial value of request.plugins, defaults to {}.
2673 * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false.
2674 * * remoteAddress - (optional) sets the remote address for the incoming connection.
2675 * * simulate - (optional) an object with options used to simulate client request stream conditions for testing:
2676 * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false.
2677 * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false.
2678 * * end - if false, does not end the stream. Defaults to true.
2679 * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked.
2680 * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested
2681 * separately.
2682 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions)
2683 * For context [Shot module](https://github.com/hapijs/shot)
2684 */
2685export interface ServerInjectOptions extends Shot.RequestOptions {
2686 /**
2687 * Authentication bypass options.
2688 */
2689 auth?: {
2690 /**
2691 * The authentication strategy name matching the provided credentials.
2692 */
2693 strategy: string;
2694 /**
2695 * The credentials are used to bypass the default authentication strategies,
2696 * and are validated directly as if they were received via an authentication scheme.
2697 */
2698 credentials: AuthCredentials;
2699 /**
2700 * The artifacts are used to bypass the default authentication strategies,
2701 * and are validated directly as if they were received via an authentication scheme. Defaults to no artifacts.
2702 */
2703 artifacts?: object;
2704 };
2705 /**
2706 * sets the initial value of request.app, defaults to {}.
2707 */
2708 app?: RequestApplicationState;
2709 /**
2710 * sets the initial value of request.plugins, defaults to {}.
2711 */
2712 plugins?: PluginsStates;
2713 /**
2714 * allows access to routes with config.isInternal set to true. Defaults to false.
2715 */
2716 allowInternals?: boolean;
2717}
2718
2719/**
2720 * A response object with the following properties:
2721 * * statusCode - the HTTP status code.
2722 * * headers - an object containing the headers set.
2723 * * payload - the response payload string.
2724 * * rawPayload - the raw response payload buffer.
2725 * * raw - an object with the injection request and response objects:
2726 * * req - the simulated node request object.
2727 * * res - the simulated node response object.
2728 * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of
2729 * the internal objects returned (instead of parsing the response string).
2730 * * request - the request object.
2731 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions)
2732 * For context [Shot module](https://github.com/hapijs/shot)
2733 */
2734export interface ServerInjectResponse extends Shot.ResponseObject {
2735 /**
2736 * the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the
2737 * internal objects returned (instead of parsing the response string).
2738 */
2739 result: object | undefined;
2740 /**
2741 * the request object.
2742 */
2743 request: Request;
2744}
2745
2746/**
2747 * The method function with a signature async function(...args, [flags]) where:
2748 * * ...args - the method function arguments (can be any number of arguments or none).
2749 * * flags - when caching is enabled, an object used to set optional method result flags:
2750 * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy.
2751 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options)
2752 */
2753export type ServerMethod = (...args: any[]) => any;
2754
2755/**
2756 * The same cache configuration used in server.cache().
2757 * The generateTimeout option is required.
2758 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options)
2759 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions)
2760 */
2761export interface ServerMethodCache extends PolicyOptions<any> {
2762 generateTimeout: number | false;
2763}
2764
2765/**
2766 * Configuration object:
2767 * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an
2768 * arrow function.
2769 * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required.
2770 * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically
2771 * generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided
2772 * which takes the same arguments as the function and returns a unique string (or null if no key can be generated). For reference [See
2773 * docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options)
2774 */
2775export interface ServerMethodOptions {
2776 /**
2777 * a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow
2778 * function.
2779 */
2780 bind?: object;
2781 /**
2782 * the same cache configuration used in server.cache(). The generateTimeout option is required.
2783 */
2784 cache?: ServerMethodCache;
2785 /**
2786 * a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a
2787 * unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which
2788 * takes the same arguments as the function and returns a unique string (or null if no key can be generated).
2789 */
2790 generateKey?(...args: any[]): string | null;
2791}
2792
2793/**
2794 * An object or an array of objects where each one contains:
2795 * * name - the method name.
2796 * * method - the method function.
2797 * * options - (optional) settings.
2798 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods)
2799 */
2800export interface ServerMethodConfigurationObject {
2801 /**
2802 * the method name.
2803 */
2804 name: string;
2805 /**
2806 * the method function.
2807 */
2808 method: ServerMethod;
2809 /**
2810 * (optional) settings.
2811 */
2812 options?: ServerMethodOptions;
2813}
2814
2815export type CacheProvider<T extends ClientOptions = ClientOptions> = EnginePrototype<any> | {
2816 constructor: EnginePrototype<any>;
2817 options?: T;
2818};
2819
2820/**
2821 * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis,
2822 * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache.
2823 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache)
2824 */
2825export interface ServerOptionsCache extends PolicyOptions<any> {
2826 /** catbox engine object. */
2827 engine?: ClientApi<any>;
2828
2829 /**
2830 * a class or a prototype function
2831 */
2832 provider?: CacheProvider;
2833
2834 /**
2835 * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines
2836 * the default cache. If every cache includes a name, a default memory cache is provisioned as well.
2837 */
2838 name?: string;
2839
2840 /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */
2841 shared?: boolean;
2842
2843 /** (optional) string used to isolate cached data. Defaults to 'hapi-cache'. */
2844 partition?: string;
2845
2846 /** other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). */
2847 [s: string]: any;
2848}
2849
2850export interface ServerOptionsCompression {
2851 minBytes: number;
2852}
2853
2854/**
2855 * Empty interface to allow for custom augmentation.
2856 */
2857/* tslint:disable-next-line:no-empty-interface */
2858export interface ServerOptionsApp {
2859}
2860
2861export type SameSitePolicy = false | 'None' | 'Lax' | 'Strict';
2862
2863/**
2864 * The server options control the behavior of the server object. Note that the options object is deeply cloned
2865 * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on.
2866 * All options are optionals.
2867 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options)
2868 */
2869export interface ServerOptions {
2870 /**
2871 * @default '0.0.0.0' (all available network interfaces).
2872 * Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to
2873 * restrict the server to only those coming from the same host.
2874 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress)
2875 */
2876 address?: string;
2877
2878 /**
2879 * @default {}.
2880 * Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available
2881 * anywhere a server reference is provided. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time
2882 * state.
2883 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp)
2884 */
2885 app?: ServerOptionsApp;
2886
2887 /**
2888 * @default true.
2889 * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework.
2890 * Cannot be set to true along with a port value.
2891 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten)
2892 */
2893 autoListen?: boolean;
2894
2895 /**
2896 * @default { engine: require('@hapi/catbox-memory' }.
2897 * Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and
2898 * capabilities. hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized
2899 * if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. The configuration can be assigned one or more
2900 * (array):
2901 * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('@hapi/catbox-redis')). A new catbox client will be created internally using this
2902 * function.
2903 * * a configuration object with the following:
2904 * * * engine - a class, a prototype function, or a catbox engine object.
2905 * * * name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines
2906 * the default cache. If every cache includes a name, a default memory cache is provisioned as well.
2907 * * * shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false.
2908 * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'.
2909 * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object).
2910 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache)
2911 */
2912 cache?: CacheProvider | ServerOptionsCache | ServerOptionsCache[];
2913
2914 /**
2915 * @default { minBytes: 1024 }.
2916 * Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server.
2917 */
2918 compression?: boolean | ServerOptionsCompression;
2919
2920 /**
2921 * @default { request: ['implementation'] }.
2922 * Determines which logged events are sent to the console. This should only be used for development and does not affect which events are actually logged internally and recorded. Set to false to
2923 * disable all console logging, or to an object with:
2924 * * log - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. Defaults to no output.
2925 * * request - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to
2926 * display all errors, set the option to ['error']. To turn off all console debug messages set it to false. To display all request logs, set it to '*'. Defaults to uncaught errors thrown in
2927 * external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. For example, to display all errors, set the log
2928 * or request to ['error']. To turn off all output set the log or request to false. To display all server logs, set the log or request to '*'. To disable all debug information, set debug to
2929 * false.
2930 */
2931 debug?: false | {
2932 log?: string[] | false;
2933 request?: string[] | false;
2934 };
2935
2936 /**
2937 * @default the operating system hostname and if not available, to 'localhost'.
2938 * The public hostname or IP address. Used to set server.info.host and server.info.uri and as address is none provided.
2939 */
2940 host?: string;
2941
2942 /**
2943 * @default none.
2944 * An optional node HTTP (or HTTPS) http.Server object (or an object with a compatible interface).
2945 * If the listener needs to be manually started, set autoListen to false.
2946 * If the listener uses TLS, set tls to true.
2947 */
2948 listener?: http.Server;
2949
2950 /**
2951 * @default { sampleInterval: 0 }.
2952 * Server excessive load handling limits where:
2953 * * sampleInterval - the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling).
2954 * * maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).
2955 * * maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).
2956 * * maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).
2957 */
2958 load?: {
2959 /** the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). */
2960 sampleInterval?: number;
2961
2962 /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
2963 maxHeapUsedBytes?: number;
2964 /**
2965 * maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).
2966 */
2967 maxRssBytes?: number;
2968 /**
2969 * maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response.
2970 * Defaults to 0 (no limit).
2971 */
2972 maxEventLoopDelay?: number;
2973 };
2974
2975 /**
2976 * @default none.
2977 * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime):
2978 * * override - an object hash that is merged into the built in mime information specified here. Each key value pair represents a single mime object. Each override value must contain:
2979 * * key - the lower-cased mime-type string (e.g. 'application/javascript').
2980 * * value - an object following the specifications outlined here. Additional values include:
2981 * * * type - specify the type value of result objects, defaults to key.
2982 * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations.
2983 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime)
2984 */
2985 mime?: MimosOptions;
2986
2987 /**
2988 * @default {}.
2989 * Plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the
2990 * difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state.
2991 */
2992 plugins?: PluginSpecificConfiguration;
2993
2994 /**
2995 * @default 0 (an ephemeral port).
2996 * The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to server.info.port).
2997 * If port is a string containing a '/' character, it is used as a UNIX domain socket path. If it starts with '\.\pipe', it is used as a Windows named pipe.
2998 */
2999 port?: number | string;
3000
3001 /**
3002 * @default { isCaseSensitive: true, stripTrailingSlash: false }.
3003 * Controls how incoming request URIs are matched against the routing table:
3004 * * isCaseSensitive - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true.
3005 * * stripTrailingSlash - removes trailing slashes on incoming paths. Defaults to false.
3006 */
3007 router?: {
3008 isCaseSensitive?: boolean;
3009 stripTrailingSlash?: boolean;
3010 };
3011
3012 /**
3013 * @default none.
3014 * A route options object used as the default configuration for every route.
3015 */
3016 routes?: RouteOptions;
3017
3018 /**
3019 * Default value:
3020 * {
3021 * strictHeader: true,
3022 * ignoreErrors: false,
3023 * isSecure: true,
3024 * isHttpOnly: true,
3025 * isSameSite: 'Strict',
3026 * encoding: 'none'
3027 * }
3028 * Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object.
3029 */
3030 // TODO I am not sure if I need to use all the server.state() definition (like the default value) OR only the options below. The v16 use "any" here.
3031 // state?: ServerStateCookieOptions;
3032 state?: {
3033 strictHeader?: boolean,
3034 ignoreErrors?: boolean,
3035 isSecure?: boolean,
3036 isHttpOnly?: boolean,
3037 isSameSite?: SameSitePolicy,
3038 encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'
3039 };
3040
3041 /**
3042 * @default none.
3043 * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation.
3044 */
3045 tls?: boolean | https.ServerOptions;
3046
3047 /**
3048 * @default constructed from runtime server information.
3049 * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings.
3050 */
3051 uri?: string;
3052
3053 /**
3054 * Query parameter configuration.
3055 */
3056 query?: {
3057 /**
3058 * the method must return an object where each key is a parameter and matching value is the parameter value.
3059 * If the method throws, the error is used as the response or returned when `request.setUrl` is called.
3060 */
3061 parser(raw: Util.Dictionary<string>): Util.Dictionary<any>;
3062 };
3063}
3064
3065/**
3066 * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a server object reference is provided
3067 * with a new server.realm container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. For example, a plugin can set a
3068 * default file path for local resources without breaking other plugins' configured paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by routes
3069 * and extensions added at the same level (server root or plugin).
3070 *
3071 * https://github.com/hapijs/hapi/blob/master/API.md#server.realm
3072 */
3073export interface ServerRealm {
3074 /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */
3075 modifiers: {
3076 /** routes preferences: */
3077 route: {
3078 /**
3079 * the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include
3080 * the trailing slash.
3081 */
3082 prefix: string;
3083 /** the route virtual host settings used by any calls to server.route() from the server. */
3084 vhost: string;
3085 }
3086 };
3087 /** the realm of the parent server object, or null for the root server. */
3088 parent: ServerRealm | null;
3089 /** the active plugin name (empty string if at the server root). */
3090 plugin: string;
3091 /** the plugin options object passed at registration. */
3092 pluginOptions: object;
3093 /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */
3094 plugins: PluginsStates;
3095 /** settings overrides */
3096 settings: {
3097 files: {
3098 relativeTo: string;
3099 };
3100 bind: object;
3101 };
3102}
3103
3104/**
3105 * Registration options (different from the options passed to the registration function):
3106 * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the
3107 * second time a plugin is registered on the server.
3108 * * routes - modifiers applied to each route added by the plugin:
3109 * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific
3110 * prefix.
3111 * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
3112 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options)
3113 */
3114export interface ServerRegisterOptions {
3115 /**
3116 * if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second
3117 * time a plugin is registered on the server.
3118 */
3119 once?: boolean;
3120 /**
3121 * modifiers applied to each route added by the plugin:
3122 */
3123 routes?: {
3124 /**
3125 * string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix.
3126 */
3127 prefix: string;
3128 /**
3129 * virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
3130 */
3131 vhost?: string | string[];
3132 };
3133}
3134
3135/**
3136 * An object with the following:
3137 * * plugin - a plugin object.
3138 * * options - (optional) options passed to the plugin during registration.
3139 * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the
3140 * second time a plugin is registered on the server.
3141 * * routes - modifiers applied to each route added by the plugin:
3142 * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific
3143 * prefix.
3144 * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
3145 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options)
3146 *
3147 * The type parameter T is the type of the plugin configuration options.
3148 */
3149export interface ServerRegisterPluginObject<T> extends ServerRegisterOptions {
3150 /**
3151 * a plugin object.
3152 */
3153 plugin: Plugin<T>;
3154 /**
3155 * options passed to the plugin during registration.
3156 */
3157 options?: T;
3158}
3159
3160export interface ServerRegisterPluginObjectArray<T, U, V, W, X, Y, Z> extends Array<ServerRegisterPluginObject<T>
3161 | ServerRegisterPluginObject<U>
3162 | ServerRegisterPluginObject<V>
3163 | ServerRegisterPluginObject<W>
3164 | ServerRegisterPluginObject<X>
3165 | ServerRegisterPluginObject<Y>
3166 | ServerRegisterPluginObject<Z>
3167 | undefined> {
3168 0: ServerRegisterPluginObject<T>;
3169 1?: ServerRegisterPluginObject<U>;
3170 2?: ServerRegisterPluginObject<V>;
3171 3?: ServerRegisterPluginObject<W>;
3172 4?: ServerRegisterPluginObject<X>;
3173 5?: ServerRegisterPluginObject<Y>;
3174 6?: ServerRegisterPluginObject<Z>;
3175}
3176
3177/* tslint:disable-next-line:no-empty-interface */
3178export interface HandlerDecorations {
3179}
3180
3181/**
3182 * A route configuration object or an array of configuration objects where each object contains:
3183 * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The
3184 * path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.
3185 * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP
3186 * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same
3187 * result as adding the same route with different methods manually.
3188 * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the
3189 * header only (excluding the port). Defaults to all hosts.
3190 * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation.
3191 * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being
3192 * added to and this is bound to the current realm's bind option.
3193 * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined.
3194 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute)
3195 */
3196export interface ServerRoute {
3197 /**
3198 * (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path
3199 * can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. For context [See
3200 * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters)
3201 */
3202 path: string;
3203
3204 /**
3205 * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method
3206 * (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same
3207 * result as adding the same route with different methods manually.
3208 */
3209 method: Util.HTTP_METHODS_PARTIAL | Util.HTTP_METHODS_PARTIAL[] | string | string[];
3210
3211 /**
3212 * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header
3213 * only (excluding the port). Defaults to all hosts.
3214 */
3215 vhost?: string | string[];
3216
3217 /**
3218 * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation.
3219 */
3220 handler?: Lifecycle.Method | HandlerDecorations;
3221
3222 /**
3223 * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to
3224 * and this is bound to the current realm's bind option.
3225 */
3226 options?: RouteOptions | ((server: Server) => RouteOptions);
3227
3228 /**
3229 * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined.
3230 */
3231 rules?: object;
3232}
3233
3234/**
3235 * Optional cookie settings
3236 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options)
3237 */
3238export interface ServerStateCookieOptions {
3239 /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */
3240 ttl?: number | null;
3241 /** sets the 'Secure' flag. Defaults to true. */
3242 isSecure?: boolean;
3243 /** sets the 'HttpOnly' flag. Defaults to true. */
3244 isHttpOnly?: boolean;
3245 /**
3246 * sets the 'SameSite' flag. The value must be one of:
3247 * * false - no flag.
3248 * * 'Strict' - sets the value to 'Strict' (this is the default value).
3249 * * 'Lax' - sets the value to 'Lax'.
3250 */
3251 isSameSite?: SameSitePolicy;
3252 /** the path scope. Defaults to null (no path). */
3253 path?: string | null;
3254 /** the domain scope. Defaults to null (no domain). */
3255 domain?: string | null;
3256
3257 /**
3258 * if present and the cookie was not received from the client or explicitly set by the route handler, the
3259 * cookie is automatically added to the response with the provided value. The value can be
3260 * a function with signature async function(request) where:
3261 */
3262 autoValue?(request: Request): void;
3263
3264 /**
3265 * encoding performs on the provided value before serialization. Options are:
3266 * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value.
3267 * * 'base64' - string value is encoded using Base64.
3268 * * 'base64json' - object value is JSON-stringified then encoded using Base64.
3269 * * 'form' - object value is encoded using the x-www-form-urlencoded method.
3270 * * 'iron' - Encrypts and sign the value using iron.
3271 */
3272 encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron';
3273 /**
3274 * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean
3275 * to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are:
3276 * * integrity - algorithm options. Defaults to require('@hapi/iron').defaults.integrity.
3277 * * password - password used for HMAC key generation (must be at least 32 characters long).
3278 */
3279 sign?: {
3280 integrity?: SealOptionsSub;
3281 password: string;
3282 };
3283 /** password used for 'iron' encoding (must be at least 32 characters long). */
3284 password?: string;
3285 /** options for 'iron' encoding. Defaults to require('@hapi/iron').defaults. */
3286 iron?: SealOptions;
3287 /** if true, errors are ignored and treated as missing cookies. */
3288 ignoreErrors?: boolean;
3289 /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */
3290 clearInvalid?: boolean;
3291 /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */
3292 strictHeader?: boolean;
3293 /** used by proxy plugins (e.g. h2o2). */
3294 passThrough?: any;
3295}
3296
3297/**
3298 * A single object or an array of object where each contains:
3299 * * name - the cookie name.
3300 * * value - the cookie value.
3301 * * options - cookie configuration to override the server settings.
3302 */
3303export interface ServerStateFormat {
3304 name: string;
3305 value: string;
3306 options: ServerStateCookieOptions;
3307}
3308
3309/**
3310 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options)
3311 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate)
3312 */
3313export interface ServerState {
3314 /**
3315 * The server cookies manager.
3316 * Access: read only and statehood public interface.
3317 */
3318 readonly states: object;
3319
3320 /**
3321 * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state).
3322 */
3323 readonly settings: ServerStateCookieOptions;
3324
3325 /**
3326 * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the
3327 * cookie name and value is the configuration object.
3328 */
3329 readonly cookies: {
3330 [key: string]: ServerStateCookieOptions;
3331 };
3332
3333 /**
3334 * An array containing the names of all configued cookies.
3335 */
3336 readonly names: string[];
3337
3338 /**
3339 * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()).
3340 */
3341 add(name: string, options?: ServerStateCookieOptions): void;
3342
3343 /**
3344 * Formats an HTTP 'Set-Cookie' header based on the server.options.state where:
3345 * @param cookies - a single object or an array of object where each contains:
3346 * * name - the cookie name.
3347 * * value - the cookie value.
3348 * * options - cookie configuration to override the server settings.
3349 * @return Return value: a header string.
3350 * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formating (e.g. when headers are set manually).
3351 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies)
3352 */
3353 format(cookies: ServerStateFormat | ServerStateFormat[]): Promise<string>;
3354
3355 /**
3356 * Parses an HTTP 'Cookies' header based on the server.options.state where:
3357 * @param header - the HTTP header.
3358 * @return Return value: an object where each key is a cookie name and value is the parsed cookie.
3359 * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled).
3360 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader)
3361 */
3362 parse(header: string): Promise<Util.Dictionary<string>>;
3363}
3364
3365/**
3366 * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler.
3367 * If the property is set to a function, the function uses the signature function(method) and returns the route default configuration.
3368 */
3369export interface HandlerDecorationMethod {
3370 (route: RequestRoute, options: any): Lifecycle.Method;
3371 defaults?: RouteOptions | ((method: any) => RouteOptions);
3372}
3373
3374/**
3375 * The general case for decorators added via server.decorate.
3376 */
3377export type DecorationMethod<T> = (this: T, ...args: any[]) => any;
3378
3379/**
3380 * An empty interface to allow typings of custom plugin properties.
3381 */
3382/* tslint:disable-next-line:no-empty-interface */
3383export interface PluginProperties {
3384}
3385
3386/**
3387 * An empty interface to allow typings of custom server.methods.
3388 */
3389/* tslint:disable-next-line:no-empty-interface */
3390export interface ServerMethods extends Util.Dictionary<ServerMethod> {
3391}
3392
3393export type DecorateName = string | symbol;
3394
3395/**
3396 * The server object is the main application container. The server manages all incoming requests along with all
3397 * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80).
3398 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server)
3399 */
3400export class Server {
3401 /**
3402 * Creates a new server object
3403 * @param options server configuration object.
3404 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions)
3405 */
3406 constructor(options?: ServerOptions);
3407
3408 /**
3409 * Provides a safe place to store server-specific run-time application data without potential conflicts with
3410 * the framework internals. The data can be accessed whenever the server is accessible.
3411 * Initialized with an empty object.
3412 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp)
3413 */
3414 app: ServerApplicationState;
3415
3416 /**
3417 * Server Auth: properties and methods
3418 */
3419 readonly auth: ServerAuth;
3420
3421 /**
3422 * Links another server to the initialize/start/stop state of the current server by calling the
3423 * controlled server `initialize()`/`start()`/`stop()` methods whenever the current server methods
3424 * are called, where:
3425 */
3426 control(server: Server): void;
3427
3428 /**
3429 * Provides access to the decorations already applied to various framework interfaces. The object must not be
3430 * modified directly, but only through server.decorate.
3431 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations)
3432 */
3433 readonly decorations: {
3434 /**
3435 * decorations on the request object.
3436 */
3437 request: string[],
3438 /**
3439 * decorations on the response toolkit.
3440 */
3441 toolkit: string[],
3442 /**
3443 * decorations on the server object.
3444 */
3445 server: string[]
3446 };
3447
3448 /**
3449 * Register custom application events where:
3450 * @param events must be one of:
3451 * * an event name string.
3452 * * an event options object with the following optional keys (unless noted otherwise):
3453 * * * name - the event name string (required).
3454 * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not).
3455 * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is
3456 * passed as-is).
3457 * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override
3458 * specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its
3459 * type).
3460 * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is
3461 * appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false.
3462 * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only
3463 * the first configuration is used. Defaults to false (a duplicate registration will throw an error).
3464 * * a podium emitter object.
3465 * * an array containing any of the above.
3466 * @return Return value: none.
3467 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
3468 */
3469 event(events: ServerEventsApplication | ServerEventsApplication[]): void;
3470
3471 /**
3472 * Access: podium public interface.
3473 * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters.
3474 * Use the following methods to interact with server.events:
3475 * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events.
3476 * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events.
3477 * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to
3478 * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name).
3479 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
3480 */
3481 events: ServerEvents;
3482
3483 /**
3484 * An object containing information about the server where:
3485 * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}').
3486 * * created - server creation timestamp.
3487 * * started - server start timestamp (0 when stopped).
3488 * * port - the connection port based on the following rules:
3489 * * host - The host configuration value.
3490 * * address - the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).
3491 * * protocol - the protocol used:
3492 * * 'http' - HTTP.
3493 * * 'https' - HTTPS.
3494 * * 'socket' - UNIX domain socket or Windows named pipe.
3495 * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available
3496 * settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started.
3497 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo)
3498 */
3499 readonly info: ServerInfo;
3500
3501 /**
3502 * Access: read only and listener public interface.
3503 * The node HTTP server object.
3504 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener)
3505 */
3506 listener: http.Server;
3507
3508 /**
3509 * An object containing the process load metrics (when load.sampleInterval is enabled):
3510 * * eventLoopDelay - event loop delay milliseconds.
3511 * * heapUsed - V8 heap usage.
3512 * * rss - RSS memory usage.
3513 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload)
3514 */
3515 readonly load: {
3516 /**
3517 * event loop delay milliseconds.
3518 */
3519 eventLoopDelay: number;
3520
3521 /**
3522 * V8 heap usage.
3523 */
3524 heapUsed: number;
3525 /**
3526 * RSS memory usage.
3527 */
3528 rss: number;
3529 };
3530
3531 /**
3532 * Server methods are functions registered with the server and used throughout the application as a common utility.
3533 * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request
3534 * handlers without having to create a common module.
3535 * sever.methods is an object which provides access to the methods registered via server.method() where each
3536 * server method name is an object property.
3537 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods
3538 */
3539 readonly methods: ServerMethods;
3540
3541 /**
3542 * Provides access to the server MIME database used for setting content-type information. The object must not be
3543 * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting.
3544 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime)
3545 */
3546 mime: any;
3547
3548 /**
3549 * An object containing the values exposed by each registered plugin where each key is a plugin name and the values
3550 * are the exposed properties by each plugin using server.expose(). Plugins may set the value of
3551 * the server.plugins[name] object directly or via the server.expose() method.
3552 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins)
3553 */
3554 plugins: PluginProperties;
3555
3556 /**
3557 * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When
3558 * registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm
3559 * container specific to that registration. It allows each plugin to maintain its own settings without leaking
3560 * and affecting other plugins.
3561 * For example, a plugin can set a default file path for local resources without breaking other plugins' configured
3562 * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by
3563 * routes and extensions added at the same level (server root or plugin).
3564 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm)
3565 */
3566 readonly realm: ServerRealm;
3567
3568 /**
3569 * An object of the currently registered plugins where each key is a registered plugin name and the value is
3570 * an object containing:
3571 * * version - the plugin version.
3572 * * name - the plugin name.
3573 * * options - (optional) options passed to the plugin during registration.
3574 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
3575 */
3576 readonly registrations: PluginsListRegistered;
3577
3578 /**
3579 * The server configuration object after defaults applied.
3580 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings)
3581 */
3582 readonly settings: ServerOptions;
3583
3584 /**
3585 * The server cookies manager.
3586 * Access: read only and statehood public interface.
3587 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates)
3588 */
3589 readonly states: ServerState;
3590
3591 /**
3592 * A string indicating the listener type where:
3593 * * 'socket' - UNIX domain socket or Windows named pipe.
3594 * * 'tcp' - an HTTP listener.
3595 */
3596 readonly type: 'socket' | 'tcp';
3597
3598 /**
3599 * The hapi module version number.
3600 */
3601 readonly version: string;
3602
3603 /**
3604 * Sets a global context used as the default bind object when adding a route or an extension where:
3605 * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context.
3606 * @return Return value: none.
3607 * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set.
3608 * Ignored if the method being bound is an arrow function.
3609 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext)
3610 */
3611 bind(context: object): void;
3612
3613 /**
3614 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions)
3615 */
3616 cache: ServerCache;
3617
3618 /**
3619 * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
3620 * @param encoding - the decoder name string.
3621 * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the
3622 * return value is an object compatible with the output of node's zlib.createGunzip().
3623 * @return Return value: none.
3624 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder)
3625 */
3626 decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void;
3627
3628 /**
3629 * Extends various framework interfaces with custom methods where:
3630 * @param type - the interface being decorated. Supported types:
3631 * 'handler' - adds a new handler type to be used in routes handlers.
3632 * 'request' - adds methods to the Request object.
3633 * 'server' - adds methods to the Server object.
3634 * 'toolkit' - adds methods to the response toolkit.
3635 * @param property - the object decoration key name.
3636 * @param method - the extension function or other value.
3637 * @param options - (optional) supports the following optional settings:
3638 * apply - when the type is 'request', if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned
3639 * as the decoration. extend - if true, overrides an existing decoration. The method must be a function with the signature function(existing) where: existing - is the previously set
3640 * decoration method value. must return the new decoration function or value. cannot be used to extend handler decorations.
3641 * @return void;
3642 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options)
3643 */
3644 decorate(type: 'handler', property: DecorateName, method: HandlerDecorationMethod, options?: {apply?: boolean, extend?: boolean}): void;
3645 decorate(type: 'request', property: DecorateName, method: (existing: ((...args: any[]) => any)) => (request: Request) => DecorationMethod<Request>, options: {apply: true, extend: true}): void;
3646 decorate(type: 'request', property: DecorateName, method: (request: Request) => DecorationMethod<Request>, options: {apply: true, extend?: boolean}): void;
3647 decorate(type: 'request', property: DecorateName, method: DecorationMethod<Request>, options?: {apply?: boolean, extend?: boolean}): void;
3648 decorate(type: 'toolkit', property: DecorateName, method: (existing: ((...args: any[]) => any)) => DecorationMethod<ResponseToolkit>, options: {apply?: boolean, extend: true}): void;
3649 decorate(type: 'toolkit', property: DecorateName, method: DecorationMethod<ResponseToolkit>, options?: {apply?: boolean, extend?: boolean}): void;
3650 decorate(type: 'server', property: DecorateName, method: (existing: ((...args: any[]) => any)) => DecorationMethod<Server>, options: {apply?: boolean, extend: true}): void;
3651 decorate(type: 'server', property: DecorateName, method: DecorationMethod<Server>, options?: {apply?: boolean, extend?: boolean}): void;
3652
3653 /**
3654 * Used within a plugin to declare a required dependency on other plugins where:
3655 * @param dependencies - plugins which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is
3656 * initialized or started.
3657 * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is
3658 * initialized or started. The function signature is async function(server) where: server - the server the dependency() method was called on.
3659 * @return Return value: none.
3660 * The after method is identical to setting a server extension point on 'onPreStart'.
3661 * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other).
3662 * The method does not provide version dependency which should be implemented using npm peer dependencies.
3663 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after)
3664 */
3665 dependency(dependencies: Dependencies, after?: ((server: Server) => Promise<void>)): void;
3666
3667 /**
3668 * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
3669 * @param encoding - the encoder name string.
3670 * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object
3671 * compatible with the output of node's zlib.createGzip().
3672 * @return Return value: none.
3673 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder)
3674 */
3675 encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void;
3676
3677 /**
3678 * Used within a plugin to expose a property via server.plugins[name] where:
3679 * @param key - the key assigned (server.plugins[name][key]).
3680 * @param value - the value assigned.
3681 * @return Return value: none.
3682 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value)
3683 */
3684 expose(key: string, value: any): void;
3685
3686 /**
3687 * Merges an object into to the existing content of server.plugins[name] where:
3688 * @param obj - the object merged into the exposed properties container.
3689 * @return Return value: none.
3690 * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method
3691 * for exposing large objects that may be expensive to clone or singleton objects such as database client
3692 * objects. Instead favor server.expose(key, value), which only copies a reference to value.
3693 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj)
3694 */
3695 expose(obj: object): void;
3696
3697 /**
3698 * Registers an extension function in one of the request lifecycle extension points where:
3699 * @param events - an object or array of objects with the following:
3700 * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
3701 * * * 'onPreStart' - called before the connection listeners are started.
3702 * * * 'onPostStart' - called after the connection listeners are started.
3703 * * * 'onPreStop' - called before the connection listeners are stopped.
3704 * * * 'onPostStop' - called after the connection listeners are stopped.
3705 * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is:
3706 * * * server extension points: async function(server) where:
3707 * * * * server - the server object.
3708 * * * * this - the object provided via options.bind or the current active context set with server.bind().
3709 * * * request extension points: a lifecycle method.
3710 * * options - (optional) an object with the following:
3711 * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
3712 * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
3713 * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
3714 * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level
3715 * extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
3716 * @return void
3717 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
3718 */
3719 ext(events: ServerExtEventsObject | ServerExtEventsObject[] | ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void;
3720
3721 /**
3722 * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments.
3723 * @return Return value: none.
3724 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options)
3725 */
3726 ext(event: ServerExtType, method: ServerExtPointFunction, options?: ServerExtOptions): void;
3727 ext(event: ServerRequestExtType, method: Lifecycle.Method, options?: ServerExtOptions): void;
3728
3729 /**
3730 * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port.
3731 * @return Return value: none.
3732 * Note that if the method fails and throws an error, the server is considered to be in an undefined state and
3733 * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and
3734 * other event listeners will get confused by repeated attempts to start the server or make assumptions about the
3735 * healthy state of the environment. It is recommended to abort the process when the server fails to start properly.
3736 * If you must try to resume after an error, call server.stop() first to reset the server state.
3737 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize)
3738 */
3739 initialize(): Promise<void>;
3740
3741 /**
3742 * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic
3743 * internally without the overhead and limitations of the network stack. The method utilizes the shot module for performing injections, with some additional options and response properties:
3744 * @param options - can be assigned a string with the requested URI, or an object with:
3745 * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'.
3746 * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.
3747 * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers.
3748 * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload
3749 * processing defaults to 'application/json' if no 'Content-Type' header provided.
3750 * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as
3751 * if they were received via an authentication scheme. Defaults to no credentials.
3752 * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly
3753 * as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.
3754 * * app - (optional) sets the initial value of request.app, defaults to {}.
3755 * * plugins - (optional) sets the initial value of request.plugins, defaults to {}.
3756 * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false.
3757 * * remoteAddress - (optional) sets the remote address for the incoming connection.
3758 * * simulate - (optional) an object with options used to simulate client request stream conditions for testing:
3759 * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false.
3760 * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false.
3761 * * end - if false, does not end the stream. Defaults to true.
3762 * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked.
3763 * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested
3764 * separately.
3765 * @return Return value: a response object with the following properties:
3766 * * statusCode - the HTTP status code.
3767 * * headers - an object containing the headers set.
3768 * * payload - the response payload string.
3769 * * rawPayload - the raw response payload buffer.
3770 * * raw - an object with the injection request and response objects:
3771 * * req - the simulated node request object.
3772 * * res - the simulated node response object.
3773 * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse
3774 * of the internal objects returned (instead of parsing the response string).
3775 * * request - the request object.
3776 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions)
3777 */
3778 inject(options: string | ServerInjectOptions): Promise<ServerInjectResponse>;
3779
3780 /**
3781 * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or
3782 * output to the console. The arguments are:
3783 * @param tags - (required) 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
3784 * mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information.
3785 * @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
3786 * value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked.
3787 * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now).
3788 * @return Return value: none.
3789 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp)
3790 */
3791 log(tags: string | string[], data?: string | object | (() => any), timestamp?: number): void;
3792
3793 /**
3794 * Looks up a route configuration where:
3795 * @param id - the route identifier.
3796 * @return Return value: the route information if found, otherwise null.
3797 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid)
3798 */
3799 lookup(id: string): RequestRoute | null;
3800
3801 /**
3802 * Looks up a route configuration where:
3803 * @param method - the HTTP method (e.g. 'GET', 'POST').
3804 * @param path - the requested path (must begin with '/').
3805 * @param host - (optional) hostname (to match against routes with vhost).
3806 * @return Return value: the route information if found, otherwise null.
3807 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host)
3808 */
3809 match(method: Util.HTTP_METHODS, path: string, host?: string): RequestRoute | null;
3810
3811 /**
3812 * Registers a server method where:
3813 * @param name - a unique method name used to invoke the method via server.methods[name].
3814 * @param method - the method function with a signature async function(...args, [flags]) where:
3815 * * ...args - the method function arguments (can be any number of arguments or none).
3816 * * flags - when caching is enabled, an object used to set optional method result flags:
3817 * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy.
3818 * @param options - (optional) configuration object:
3819 * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is
3820 * an arrow function.
3821 * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required.
3822 * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will
3823 * automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation
3824 * function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).
3825 * @return Return value: none.
3826 * Method names can be nested (e.g. utils.users.get) which will automatically create the full path under server.methods (e.g. accessed via server.methods.utils.users.get).
3827 * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear
3828 * the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation.
3829 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options)
3830 */
3831 method(name: string, method: ServerMethod, options?: ServerMethodOptions): void;
3832
3833 /**
3834 * Registers a server method function as described in server.method() using a configuration object where:
3835 * @param methods - an object or an array of objects where each one contains:
3836 * * name - the method name.
3837 * * method - the method function.
3838 * * options - (optional) settings.
3839 * @return Return value: none.
3840 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods)
3841 */
3842 method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void;
3843
3844 /**
3845 * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where:
3846 * @param relativeTo - the path prefix added to any relative file path starting with '.'.
3847 * @return Return value: none.
3848 * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files.relativeTo settings is used. The
3849 * path only applies to routes added after it has been set.
3850 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto)
3851 */
3852 path(relativeTo: string): void;
3853
3854 /**
3855 * Registers a plugin where:
3856 * @param plugins - one or an array of:
3857 * * a plugin object.
3858 * * an object with the following:
3859 * * * plugin - a plugin object.
3860 * * * options - (optional) options passed to the plugin during registration.
3861 * * * once, routes - (optional) plugin-specific registration options as defined below.
3862 * @param options - (optional) registration options (different from the options passed to the registration function):
3863 * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the
3864 * second time a plugin is registered on the server.
3865 * * routes - modifiers applied to each route added by the plugin:
3866 * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the
3867 * child-specific prefix.
3868 * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
3869 * @return Return value: none.
3870 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options)
3871 */
3872 /* tslint:disable-next-line:no-unnecessary-generics */
3873 register<T>(plugin: ServerRegisterPluginObject<T>, options?: ServerRegisterOptions): Promise<void>;
3874 /* tslint:disable-next-line:no-unnecessary-generics */
3875 register<T, U, V, W, X, Y, Z>(plugins: ServerRegisterPluginObjectArray<T, U, V, W, X, Y, Z>, options?: ServerRegisterOptions): Promise<void>;
3876 register(plugins: Array<ServerRegisterPluginObject<any>>, options?: ServerRegisterOptions): Promise<void>;
3877 /* tslint:disable-next-line:unified-signatures */
3878 register(plugins: Plugin<any> | Array<Plugin<any>>, options?: ServerRegisterOptions): Promise<void>;
3879
3880 /**
3881 * Adds a route where:
3882 * @param route - a route configuration object or an array of configuration objects where each object contains:
3883 * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration.
3884 * The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.
3885 * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP
3886 * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has
3887 * the same result as adding the same route with different methods manually.
3888 * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the
3889 * header only (excluding the port). Defaults to all hosts.
3890 * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation.
3891 * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being
3892 * added to and this is bound to the current realm's bind option.
3893 * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined.
3894 * @return Return value: none.
3895 * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on.
3896 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute)
3897 */
3898 route(route: ServerRoute | ServerRoute[]): void;
3899
3900 /**
3901 * Defines a route rules processor for converting route rules object into route configuration where:
3902 * @param processor - a function using the signature function(rules, info) where:
3903 * * rules -
3904 * * info - an object with the following properties:
3905 * * * method - the route method.
3906 * * * path - the route path.
3907 * * * vhost - the route virtual host (if any defined).
3908 * * returns a route config object.
3909 * @param options - optional settings:
3910 * * validate - rules object validation:
3911 * * * schema - joi schema.
3912 * * * options - optional joi validation options. Defaults to { allowUnknown: true }.
3913 * Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config.
3914 * Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin override the config generated
3915 * by the root processor if they overlap. The route config overrides the rules config if the overlap.
3916 * @return void
3917 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options)
3918 */
3919 rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options?: {validate: object}): void; // TODO needs implementation
3920
3921 /**
3922 * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false).
3923 * @return Return value: none.
3924 * Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the
3925 * various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is
3926 * recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. If a started server
3927 * is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked.
3928 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart)
3929 */
3930 start(): Promise<void>;
3931
3932 /**
3933 * HTTP state management uses client cookies to persist a state across multiple requests.
3934 * @param name - the cookie name string.
3935 * @param options - are the optional cookie settings
3936 * @return Return value: none.
3937 * State defaults can be modified via the server default state configuration option.
3938 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options)
3939 */
3940 state(name: string, options?: ServerStateCookieOptions): void;
3941
3942 /**
3943 * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where:
3944 * @param options - (optional) object with:
3945 * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds).
3946 * @return Return value: none.
3947 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions)
3948 */
3949 stop(options?: {timeout: number}): Promise<void>;
3950
3951 /**
3952 * Returns a copy of the routing table where:
3953 * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts.
3954 * @return Return value: an array of routes where each route contains:
3955 * * settings - the route config with defaults applied.
3956 * * method - the HTTP method in lower case.
3957 * * path - the route path.
3958 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost)
3959 */
3960 table(host?: string): RequestRoute[];
3961
3962 /**
3963 * Registers a server validation module used to compile raw validation rules into validation schemas for all routes.
3964 * The validator is only used when validation rules are not pre-compiled schemas. When a validation rules is a function or schema object, the rule is used as-is and the validator is not used.
3965 */
3966 validator(joi: Root): void;
3967}
3968
3969/**
3970 * Factory function to create a new server object (introduced in v17).
3971 */
3972export function server(opts?: ServerOptions): Server;
3973
3974/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
3975 + +
3976 + +
3977 + +
3978 + Utils +
3979 + +
3980 + +
3981 + +
3982 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
3983
3984/**
3985 * User-extensible type for application specific state (`server.app`).
3986 */
3987 /* tslint:disable-next-line:no-empty-interface */
3988export interface ServerApplicationState {
3989}
3990
3991/**
3992 * User-extensible type for application specific state on requests (`request.app`).
3993 */
3994 /* tslint:disable-next-line:no-empty-interface */
3995 export interface RequestApplicationState {
3996}
3997
3998/**
3999 * User-extensible type for application specific state on responses (`response.app`).
4000 */
4001 /* tslint:disable-next-line:no-empty-interface */
4002 export interface ResponseApplicationState {
4003}
4004
4005export type PeekListener = (chunk: string, encoding: string) => void;
4006
4007export namespace Json {
4008 /**
4009 * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter}
4010 */
4011 type StringifyReplacer = ((key: string, value: any) => any) | Array<(string | number)> | undefined;
4012
4013 /**
4014 * Any value greater than 10 is truncated.
4015 */
4016 type StringifySpace = number | string;
4017
4018 /**
4019 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson)
4020 */
4021 interface StringifyArguments {
4022 /** the replacer function or array. Defaults to no action. */
4023 replacer?: StringifyReplacer;
4024 /** number of spaces to indent nested object keys. Defaults to no indentation. */
4025 space?: StringifySpace;
4026 /* string suffix added after conversion to JSON string. Defaults to no suffix. */
4027 suffix?: string;
4028 /* calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. */
4029 escape?: boolean;
4030 }
4031}
4032
4033export namespace Lifecycle {
4034 /**
4035 * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps:
4036 * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods
4037 * provided by the developer and executed by the framework.
4038 * Each lifecycle method is a function with the signature await function(request, h, [err]) where:
4039 * * request - the request object.
4040 * * h - the response toolkit the handler must call to set a response and return control back to the framework.
4041 * * err - an error object availble only when the method is used as a failAction value.
4042 */
4043 type Method = (request: Request, h: ResponseToolkit, err?: Error) => ReturnValue;
4044
4045 /**
4046 * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns
4047 * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent.
4048 * The return value must be one of:
4049 * - Plain value: null, string, number, boolean
4050 * - Buffer object
4051 * - Error object: plain Error OR a Boom object.
4052 * - Stream object
4053 * - any object or array
4054 * - a toolkit signal:
4055 * - a toolkit method response:
4056 * - a promise object that resolve to any of the above values
4057 * For more info please [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods)
4058 */
4059 type ReturnValue = ReturnValueTypes | (Promise<ReturnValueTypes>);
4060 type ReturnValueTypes =
4061 (null | string | number | boolean) |
4062 (Buffer) |
4063 (Error | Boom) |
4064 (stream.Stream) |
4065 (object | object[]) |
4066 symbol |
4067 ResponseToolkit;
4068
4069 /**
4070 * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be
4071 * configured to perform another action. When supported the failAction option supports the following values:
4072 * * 'error' - return the error object as the response.
4073 * * 'log' - report the error but continue processing the request.
4074 * * 'ignore' - take no action and continue processing the request.
4075 * * a lifecycle method with the signature async function(request, h, err) where:
4076 * * * request - the request object.
4077 * * * h - the response toolkit.
4078 * * * err - the error object.
4079 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration)
4080 */
4081 type FailAction = 'error' | 'log' | 'ignore' | Method;
4082}
4083
4084export namespace Util {
4085 interface Dictionary<T> {
4086 [key: string]: T;
4087 }
4088
4089 type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options';
4090 type HTTP_METHODS_PARTIAL =
4091 'GET'
4092 | 'POST'
4093 | 'PUT'
4094 | 'PATCH'
4095 | 'DELETE'
4096 | 'OPTIONS'
4097 | HTTP_METHODS_PARTIAL_LOWERCASE;
4098 type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL;
4099}
4100
\No newline at end of file