UNPKG

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