UNPKG

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