[@hapi/*] new namespace for hapi modules

This commit is contained in:
Silas Rech
2019-04-04 23:14:28 +02:00
parent 935a7078dd
commit f499f42f6c
107 changed files with 11384 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
import * as accept from '@hapi/accept';
accept.charsets("iso-8859-5, unicode-1-1;q=0.8"); // charset === "iso-8859-5"
accept.charset("iso-8859-5, unicode-1-1;q=0.8", ["unicode-1-1"]); // charset === "unicode-1-1"
accept.encoding("gzip, deflate, sdch"); // encoding === "gzip"
accept.encoding("gzip, deflate, sdch", ["deflate", "identity"]);
const encodings = accept.encodings("compress;q=0.5, gzip;q=1.0"); // encodings === ["gzip", "compress", "identity"]
encodings.lastIndexOf('');
accept.language("en;q=0.7, en-GB;q=0.8");
accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB"
const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"]
languages.lastIndexOf('');
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1", ["application/json", "text/html"]);
const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
// mediaTypes === ["text/plain", "text/html", "application/json", "*/*"]
mediaTypes.lastIndexOf('');
const headers = {
accept: 'text/plain, application/json;q=0.5, text/html, */*;q=0.1',
'accept-language': 'da, en;q=0.7, en-GB;q=0.8'
};
const all = accept.parseAll(headers);
all.charsets.length;
all.encodings.length;
all.languages.length;
all.mediaTypes.length;

23
types/hapi__accept/index.d.ts vendored Normal file
View File

@@ -0,0 +1,23 @@
// Type definitions for @hapi/accept 3.2
// Project: https://github.com/hapijs/accept#readme
// Definitions by: feinoujc <https://github.com/feinoujc>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export function charset(charsetHeader?: string, preferences?: string[]): string;
export function charsets(charsetHeader?: string): string[];
export function encoding(encodingHeader?: string, preferences?: string[]): string;
export function encodings(encodingHeader?: string): string[];
export function language(languageHeader?: string, preferences?: string[]): string;
export function languages(languageHeader?: string): string[];
export function mediaType(mediaTypeHeader?: string, preferences?: string[]): string;
export function mediaTypes(mediaTypeHeader?: string): string[];
export function parseAll(
headers: Record<string, string | string[] | undefined>
): {
charsets: string[];
encodings: string[];
languages: string[];
mediaTypes: string[];
};

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/accept": [
"hapi__accept"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__accept-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,209 @@
import * as Boom from '@hapi/boom';
// 4xx and data type
const badRequestError = Boom.badRequest('message', {some: 'data'});
badRequestError.data.some;
const badRequestError2: Boom = Boom.badImplementation('message');
const unauthorizedError1 = Boom.unauthorized('message', 'scheme', {some: 'attribute'});
unauthorizedError1.output.payload.attributes === { some: 'attribute', error: 'message' };
unauthorizedError1.output.headers === { 'WWW-Authenticate': 'scheme some="attribute", error="message"' };
const unauthorizedError2 = Boom.unauthorized('message', ['scheme']);
unauthorizedError2.output.payload.attributes === undefined;
unauthorizedError2.output.headers === { 'WWW-Authenticate': 'scheme' };
const unauthorizedError3 = Boom.unauthorized(null, 'scheme', 'attribute');
unauthorizedError3.output.payload.attributes === 'attribute';
unauthorizedError3.output.headers === { 'WWW-Authenticate': 'scheme attribute' };
const unauthorizedError4 = Boom.unauthorized(null, 'scheme', {some: 'attribute'});
unauthorizedError4.output.payload.attributes === { some: 'attribute' };
unauthorizedError4.output.headers === { 'WWW-Authenticate': 'scheme some="attribute"' };
const paymentRequiredError = Boom.paymentRequired('message', {some: 'data'});
paymentRequiredError.data.some;
const paymentRequiredError2: Boom = Boom.paymentRequired('message');
const forbiddenError = Boom.forbidden('message', {some: 'data'});
forbiddenError.data.some;
const forbiddenError2: Boom = Boom.forbidden('message');
const notFoundError = Boom.notFound('message', {some: 'data'});
notFoundError.data.some;
const notFoundError2: Boom = Boom.notFound('message');
const methodNotAllowedError = Boom.methodNotAllowed('message', {some: 'data'});
methodNotAllowedError.data.some;
const methodNotAllowedError2: Boom = Boom.methodNotAllowed('message');
const notAcceptableError = Boom.notAcceptable('message', {some: 'data'});
notAcceptableError.data.some;
const notAcceptableError2: Boom = Boom.notAcceptable('message');
const proxyAuthRequiredError = Boom.proxyAuthRequired('message', {some: 'data'});
proxyAuthRequiredError.data.some;
const proxyAuthRequiredError2: Boom = Boom.proxyAuthRequired('message');
const clientTimeoutError = Boom.clientTimeout('message', {some: 'data'});
clientTimeoutError.data.some;
const clientTimeoutError2: Boom = Boom.clientTimeout('message');
const conflictError = Boom.conflict('message', {some: 'data'});
conflictError.data.some;
const resourceGoneError = Boom.resourceGone('message', {some: 'data'});
resourceGoneError.data.some;
const resourceGoneError2: Boom = Boom.resourceGone('message');
const lengthRequiredError = Boom.lengthRequired('message', {some: 'data'});
lengthRequiredError.data.some;
const lengthRequiredError2: Boom = Boom.lengthRequired('message');
const preconditionFailedError = Boom.preconditionFailed('message', {some: 'data'});
preconditionFailedError.data.some;
const preconditionFailedError2: Boom = Boom.preconditionFailed('message');
const entityTooLargeError = Boom.entityTooLarge('message', {some: 'data'});
entityTooLargeError.data.some;
const entityTooLargeError2: Boom = Boom.lengthRequired('message');
const uriTooLongError = Boom.uriTooLong('message', {some: 'data'});
uriTooLongError.data.some;
const uriTooLongError2: Boom = Boom.uriTooLong('message');
const unsupportedMediaTypeError = Boom.unsupportedMediaType('message', {some: 'data'});
unsupportedMediaTypeError.data.some;
const unsupportedMediaTypeError2: Boom = Boom.unsupportedMediaType('message');
const rangeNotSatisfiableError = Boom.rangeNotSatisfiable('message', {some: 'data'});
rangeNotSatisfiableError.data.some;
const rangeNotSatisfiableError2: Boom = Boom.rangeNotSatisfiable('message');
const expectationFailedError = Boom.expectationFailed('message', {some: 'data'});
expectationFailedError.data.some;
const expectationFailedError2: Boom = Boom.expectationFailed('message');
const teapotError = Boom.teapot('message', {some: 'data'});
teapotError.data.some;
const teapotError2: Boom = Boom.teapot('message');
const badDataError = Boom.badData('message', {some: 'data'});
badDataError.data.some;
const badDataError2: Boom = Boom.badData('message');
const lockedError = Boom.locked('message', {some: 'data'});
lockedError.data.some;
const lockedError2: Boom = Boom.locked('message');
const failedDependencyError = Boom.failedDependency('message', {some: 'data'});
failedDependencyError.data.some;
const failedDependencyError2: Boom = Boom.failedDependency('message');
const preconditionRequiredError = Boom.preconditionRequired('message', {some: 'data'});
preconditionRequiredError.data.some;
const preconditionRequiredError2: Boom = Boom.preconditionRequired('message');
const tooManyRequestsError = Boom.tooManyRequests('message', {some: 'data'});
tooManyRequestsError.data.some;
const tooManyRequestsError2: Boom = Boom.tooManyRequests('message');
const illegalError = Boom.illegal('message', {some: 'data'});
illegalError.data.some;
const illegalError2: Boom = Boom.illegal('message');
// 5xx and data type
const badImplementationError = Boom.badImplementation('message', {some: 'data'});
badImplementationError.data.some;
const badImplementationError2: Boom = Boom.badImplementation('message');
const internalError = Boom.internal('message', {some: 'data'});
internalError.data.some;
const internalError2: Boom = Boom.internal('message');
const notImplementedError = Boom.notImplemented('message', {some: 'data'});
notImplementedError.data.some;
const notImplementedError2: Boom = Boom.notImplemented('message');
const badGatewayError = Boom.badGateway('message', {some: 'data'});
badGatewayError.data.some;
const badGatewayError2: Boom = Boom.badGateway('message');
const serverUnavailableError = Boom.serverUnavailable('message', {some: 'data'});
serverUnavailableError.data.some;
const serverUnavailableError2: Boom = Boom.serverUnavailable('message');
const gatewayTimeoutError = Boom.gatewayTimeout('message', {some: 'data'});
gatewayTimeoutError.data.some;
const gatewayTimeoutError2: Boom = Boom.gatewayTimeout('message');
// boomify
const boomifiedError = Boom.boomify(new Error('test'), { statusCode: 400, message: 'some message' });
// isBoom
const isBoomError = new Boom('test');
Boom.isBoom(isBoomError);
const maybeBoom = <any> new Boom('test');
if (Boom.isBoom(maybeBoom)) {
// isBoom is a type guard that allows accessing these properties:
maybeBoom.output.headers;
}
// constructor
const constructorError: Boom = new Boom('test');
constructorError.message;
// type widen asserting
const unauthorizedError = Boom.unauthorized() as Error;
// status code and reformat
const error = Boom.badRequest('Cannot feed after midnight');
error.output.statusCode = 499; // Assign a custom error code
error.reformat();
/**
* Add a custom key to the payload
*/
interface CustomPayload extends Boom.Payload {
custom: string;
}
(error.output.payload as CustomPayload).custom = 'abc_123';
/**
* Test assignment of custom error data:
*/
// tslint:disable-next-line:no-object-literal-type-assertion
const errorWithData = Boom.badImplementation('', <CustomData1> { custom1: 'test', customType: 'Custom1', isCustom: true });
const errorWithNoExplicitDataType: Boom = errorWithData; // can assign to error without explicit data type
const errorWithExplicitType: Boom<CustomData> = errorWithData; // can assign to union data type
const errorWithConcreteCustomData: Boom<CustomData1> = errorWithData; // can assign to concrete data type
// assignment to CustomData2 would not be possible
// const errorWithConcreteCustomData2: Boom<CustomData2> = errorWithData;
// Some complex error data types for testing purposes:
interface CustomDataBase {
isCustom: true;
}
interface CustomData1 extends CustomDataBase {
customType: 'Custom1';
custom1: string;
}
interface CustomData2 extends CustomDataBase {
customType: 'Custom2';
custom2: string;
}
type CustomData = CustomData1 | CustomData2;

372
types/hapi__boom/index.d.ts vendored Normal file
View File

@@ -0,0 +1,372 @@
// Type definitions for @hapi/boom 7.4
// Project: https://github.com/hapijs/boom
// Definitions by: Igor Rogatty <https://github.com/rogatty>
// AJP <https://github.com/AJamesPhillips>
// Jinesh Shah <https://github.com/jineshshah36>
// Timon van Spronsen <https://github.com/TimonVS>
// Daniel Machado <https://github.com/danielmachado>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export = Boom;
/**
* boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties:
* @see {@link https://github.com/hapijs/boom#boom}
*/
declare class Boom<Data = any> extends Error {
/** Creates a new Boom object using the provided message and then calling boomify() to decorate the error with the Boom properties. */
constructor(message?: string | Error, options?: Boom.Options<Data>);
/** isBoom - if true, indicates this is a Boom object instance. */
isBoom: boolean;
/** isServer - convenience bool indicating status code >= 500. */
isServer: boolean;
/** message - the error message. */
message: string;
/** output - the formatted response. Can be directly manipulated after object construction to return a custom error response. Allowed root keys: */
output: Boom.Output;
/** reformat() - rebuilds error.output using the other object properties. */
reformat(): string;
/**
* "If message is unset, the 'error' segment of the header will not be present and
* isMissing will be true on the error object." mentioned in
* @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes}
*/
isMissing?: boolean;
/** https://github.com/hapijs/boom#createstatuscode-message-data and https://github.com/hapijs/boom/blob/v4.3.0/lib/index.js#L99 */
data: Data;
}
declare namespace Boom {
interface Options<Data> {
/** statusCode - the HTTP status code. Defaults to 500 if no status code is already set. */
statusCode?: number;
/** data - additional error information (assigned to error.data). */
data?: Data;
/** decorate - an option with extra properties to set on the error object. */
decorate?: object;
/** ctor - constructor reference used to crop the exception call stack output. */
ctor?: any;
/** message - error message string. If the error already has a message, the provided message is added as a prefix. Defaults to no message. */
message?: string;
/**
* override - if false, the err provided is a Boom object, and a statusCode or message are
* provided, the values are ignored. Defaults to true (apply the provided statusCode and
* message options to the error regardless of its type, Error or Boom object).
*/
override?: boolean;
}
interface Output {
/** statusCode - the HTTP status code (typically 4xx or 5xx). */
statusCode: number;
/**
* headers - an object containing any HTTP headers where each key is a header name and
* value is the header content. (Limited value type to string
* https://github.com/hapijs/boom/issues/151 )
*/
headers: {[index: string]: string};
/**
* payload - the formatted object used as the response payload (stringified).
* Can be directly manipulated but any changes will be lost if reformat() is called.
* Any content allowed and by default includes the following content:
*/
payload: Payload;
}
interface Payload {
/** statusCode - the HTTP status code, derived from error.output.statusCode. */
statusCode: number;
/** error - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */
error: string;
/** message - the error message derived from error.message. */
message: string;
/**
* "Every key/value pair will be included ... in the response payload under the attributes key."
* [see docs](https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes)
*/
attributes?: any;
// Excluded this to aid typing of the other values. See tests for example casting to a custom interface to manipulate the payload
// [anyContent: string]: any;
}
/**
* Decorates an error with the boom properties
* @param error the error object to wrap. If error is already a boom object, it defaults to overriding the object with the new status code and message.
* @param options optional additional options
* @see {@link https://github.com/hapijs/boom#boomifyerror-options}
*/
function boomify(error: Error, options?: { statusCode?: number, message?: string, override?: boolean }): Boom<null>;
/**
* Identifies whether an error is a Boom object. Same as calling instanceof Boom.
* @param error the error object to identify.
*/
function isBoom(error: Error): error is Boom;
// 4xx
/**
* Returns a 400 Bad Request error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadrequestmessage-data}
*/
function badRequest<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 401 Unauthorized error
* @param message optional message.
* @param scheme can be one of the following:
* * an authentication scheme name
* * an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header.
* @param attributes an object of values to use while setting the 'WWW-Authenticate' header.
* This value is only used when scheme is a string, otherwise it is ignored.
* Every key/value pair will be included in the 'WWW-Authenticate' in the format of
* 'key="value"' as well as in the response payload under the attributes key.
* Alternatively value can be a string which is use to set the value of the scheme,
* for example setting the token value for negotiate header.
* If string is used message parameter must be null.
* null and undefined will be replaced with an empty string. If attributes is set,
* message will be used as the 'error' segment of the 'WWW-Authenticate' header.
* If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object.
* @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes}
*/
function unauthorized(message?: string, scheme?: string, attributes?: {[index: string]: string}): Boom<null>;
function unauthorized(message?: string, scheme?: string[]): Boom<null>;
function unauthorized(message?: null, scheme?: string, attributes?: {[index: string]: string} | string): Boom<null>;
/**
* Returns a 402 Payment Required error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompaymentrequiredmessage-data}
*/
function paymentRequired<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 403 Forbidden error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomforbiddenmessage-data}
*/
function forbidden<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 404 Not Found error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotfoundmessage-data}
*/
function notFound<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 405 Method Not Allowed error
* @param message optional message.
* @param data optional additional error data.
* @param allow optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header.
* @see {@link https://github.com/hapijs/boom#boommethodnotallowedmessage-data-allow}
*/
function methodNotAllowed<Data = null>(message?: string, data?: Data, allow?: string | string[]): Boom<Data>;
/**
* Returns a 406 Not Acceptable error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotacceptablemessage-data}
*/
function notAcceptable<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 407 Proxy Authentication Required error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomproxyauthrequiredmessage-data}
*/
function proxyAuthRequired<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 408 Request Time-out error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomclienttimeoutmessage-data}
*/
function clientTimeout<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 409 Conflict error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomconflictmessage-data}
*/
function conflict<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 410 Gone error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomresourcegonemessage-data}
*/
function resourceGone<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 411 Length Required error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomlengthrequiredmessage-data}
*/
function lengthRequired<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 412 Precondition Failed error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompreconditionfailedmessage-data}
*/
function preconditionFailed<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 413 Request Entity Too Large error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomentitytoolargemessage-data}
*/
function entityTooLarge<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 414 Request-URI Too Large error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomuritoolongmessage-data}
*/
function uriTooLong<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 415 Unsupported Media Type error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomunsupportedmediatypemessage-data}
*/
function unsupportedMediaType<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 416 Requested Range Not Satisfiable error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomrangenotsatisfiablemessage-data}
*/
function rangeNotSatisfiable<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 417 Expectation Failed error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomexpectationfailedmessage-data}
*/
function expectationFailed<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 418 I'm a Teapot error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomteapotmessage-data}
*/
function teapot<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 422 Unprocessable Entity error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombaddatamessage-data}
*/
function badData<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 423 Locked error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomlockedmessage-data}
*/
function locked<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 424 Failed Dependency error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomfaileddependencymessage-data}
*/
function failedDependency<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 428 Precondition Required error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boompreconditionrequiredmessage-data}
*/
function preconditionRequired<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 429 Too Many Requests error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomtoomanyrequestsmessage-data}
*/
function tooManyRequests<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 451 Unavailable For Legal Reasons error
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomillegalmessage-data}
*/
function illegal<Data = null>(message?: string, data?: Data): Boom<Data>;
// 5xx
/**
* Returns a 500 Internal Server Error error
* Only 500 errors will hide your message from the end user. Your message is recorded in the server log.
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal}
*/
function badImplementation<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 500 Internal Server Error error
* Only 500 errors will hide your message from the end user. Your message is recorded in the server log.
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal}
*/
function internal<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 501 Not Implemented error with your error message to the user
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomnotimplementedmessage-data}
*/
function notImplemented<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 502 Bad Gateway error with your error message to the user
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boombadgatewaymessage-data}
*/
function badGateway<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 503 Service Unavailable error with your error message to the user
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomserverunavailablemessage-data}
*/
function serverUnavailable<Data = null>(message?: string, data?: Data): Boom<Data>;
/**
* Returns a 504 Gateway Time-out error with your error message to the user
* @param message optional message.
* @param data optional additional error data.
* @see {@link https://github.com/hapijs/boom#boomgatewaytimeoutmessage-data}
*/
function gatewayTimeout<Data = null>(message?: string, data?: Data): Boom<Data>;
}

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/boom": [
"hapi__boom"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__boom-tests.ts"
]
}

View File

@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-angle-bracket-type-assertion": false
}
}

View File

@@ -0,0 +1,8 @@
import * as CatboxMemory from '@hapi/catbox-memory';
const client = new CatboxMemory<string>({
allowMixedContent: true,
cloneBuffersOnGet: false,
maxByteSize: 1024,
minCleanupIntervalMsec: 1000,
});

48
types/hapi__catbox-memory/index.d.ts vendored Normal file
View File

@@ -0,0 +1,48 @@
// Type definitions for @hapi/catbox-memory 4.1
// Project: https://github.com/hapijs/catbox-memory#readme
// Definitions by: Simon Schick <https://github.com/SimonSchick>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import { ClientApi } from '@hapi/catbox';
interface CatboxMemory<T> extends ClientApi<T> {}
// tslint:disable-next-line:no-unnecessary-class
declare class CatboxMemory<T> implements ClientApi<T> {
constructor(options?: CatboxMemory.Options);
}
declare namespace CatboxMemory {
interface Options {
/**
* Sets an upper limit on the number of bytes that can be stored in the cache.
* Once this limit is reached no additional items will be added to the cache until some expire.
* The utilized memory calculation is a rough approximation and must not be relied on.
* @default 104857600 (100MB).
*/
maxByteSize?: number;
/**
* The minimum number of milliseconds in between each cache cleanup.
* @default 1000 (1 second)
*/
minCleanupIntervalMsec?: number;
/**
* by default, all data is cached as JSON strings, and converted to an object using JSON.parse() on retrieval.
* By setting this option to true, Buffer data can be stored alongside the stringified data.
* Buffers are not stringified, and are copied before storage to prevent the value from changing while in the cache.
* @default false
*/
allowMixedContent?: boolean;
/**
* by default, buffers stored in the cache with allowMixedContent set to true are copied when they are set but not when they are retrieved.
* This means a change to the buffer returned by a get() will change the value in the cache. To prevent this,
* set cloneBuffersOnGet to true to always return a copy of the cached buffer.
* @default false
*/
cloneBuffersOnGet?: boolean;
}
}
export = CatboxMemory;

View File

@@ -0,0 +1,31 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/catbox": [
"hapi__catbox"
],
"@hapi/catbox-memory": [
"hapi__catbox-memory"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__catbox-memory-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -0,0 +1,44 @@
import { Client, Policy, EnginePrototypeOrObject, DecoratedResult, CachedObject } from "@hapi/catbox";
const Memory: EnginePrototypeOrObject = {
async start(): Promise<void> {},
stop(): void {},
async get(): Promise<null | CachedObject<string>> {
return {
item: 'asd',
stored: 12,
ttl: 123,
};
},
async set(): Promise<void> {},
async drop(): Promise<void> {},
isReady(): boolean { return true; },
validateSegmentName(segment: string): null { return null; },
};
const client = new Client<string>(Memory, { partition: 'cache' });
client.start().then(() => {});
client.stop().then(() => {});
const cache = new Policy({
expiresIn: 5000,
}, client, 'cache');
cache.set('foo', 'bar', 5000).then(() => {});
cache.get('foo').then(() => {});
cache.drop('foo').then(() => {});
cache.isReady();
cache.stats();
const decoratedCache = new Policy({
getDecoratedValue: true,
}, client, 'cache2');
decoratedCache.get('test').then((a: DecoratedResult<string>) => {
const res: string = a.value;
});

287
types/hapi__catbox/index.d.ts vendored Normal file
View File

@@ -0,0 +1,287 @@
// Type definitions for @hapi/catbox 10.2
// Project: https://github.com/hapijs/catbox
// Definitions by: Jason Swearingen <https://github.com/jasonswearingen>
// AJP <https://github.com/AJamesPhillips>
// Rodrigo Saboya <https://github.com/saboya>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/**
* Client
* The Client object provides a low-level cache abstraction. The object is constructed using new Client(engine, options) where:
* engine - is an object or a prototype function implementing the cache strategy:
* * function - a prototype function with the signature function(options). catbox will call new func(options).
* * object - a pre instantiated client implementation object. Does not support passing options.
* options - the strategy configuration object. Each strategy defines its own configuration options with the following common options:
* * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name,
* the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name.
* @see {@link https://github.com/hapijs/catbox#client}
*/
export class Client<T> implements ClientApi<T> {
constructor(engine: EnginePrototypeOrObject, options: ClientOptions);
/** start() - creates a connection to the cache server. Must be called before any other method is available. */
start(): Promise<void>;
/** stop() - terminates the connection to the cache server. */
stop(): Promise<void>;
/**
* get(key, callback) - retrieve an item from the cache engine if found where:
* * key - a cache key object (see [ICacheKey]).
*/
get(key: CacheKey): Promise<null | CachedObject<T>>;
/**
* set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where:
* * key - a cache key object (see [ICacheKey]).
* * value - the string or object value to be stored.
* * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
*/
set(key: CacheKey, value: T, ttl: number): Promise<void>;
/**
* drop(key, callback) - remove an item from cache where:
* * key - a cache key object (see [ICacheKey]).
*/
drop(key: CacheKey): Promise<void>;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */
isReady(): boolean;
/** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */
validateSegmentName(segment: string): null | Error;
}
export type EnginePrototypeOrObject = EnginePrototype<any> | ClientApi<any>;
/**
* A prototype CatBox engine function
*/
export interface EnginePrototype<T> {
new(settings: ClientOptions): ClientApi<T>;
}
/**
* Client API
* The Client object provides the following methods:
* @see {@link https://github.com/hapijs/catbox#api}
*/
export interface ClientApi<T> {
/** start() - creates a connection to the cache server. Must be called before any other method is available. */
start(): Promise<void>;
/** stop() - terminates the connection to the cache server. */
stop(): void;
/**
* get(key, callback) - retrieve an item from the cache engine if found where:
* * key - a cache key object (see [ICacheKey]).
*/
get(key: CacheKey): Promise<null | CachedObject<T>>;
/**
* set(key, value, ttl) - store an item in the cache for a specified length of time, where:
* * key - a cache key object (see [ICacheKey]).
* * value - the string or object value to be stored.
* * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
*/
set(key: CacheKey, value: T, ttl: number): Promise<void>;
/**
* drop(key) - remove an item from cache where:
* * key - a cache key object (see [ICacheKey]).
*/
drop(key: CacheKey): Promise<void>;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */
isReady(): boolean;
/** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */
validateSegmentName(segment: string): null | Error;
}
/**
* Any method with a key argument takes an object with the following required properties:
*/
export interface CacheKey {
/** segment - a caching segment name string. Enables using a single cache server for storing different sets of items with overlapping ids. */
segment: string;
/** id - a unique item identifier string (per segment). Can be an empty string. */
id: string;
}
/** Cached object contains the following: */
export interface CachedObject<T> {
/** item - the value stored in the cache using set(). */
item: T;
/** stored - the timestamp when the item was stored in the cache (in milliseconds). */
stored: number;
/** ttl - the remaining time-to-live (not the original value used when storing the object). */
ttl: number;
}
export interface ClientOptions {
/**
* this will store items under keys that start with this value.
*/
partition: string;
}
export type PolicyOptionVariants<T> = PolicyOptions<T> | DecoratedPolicyOptions<T>;
export type Id = string | { id: string };
/**
* The Policy object provides a convenient cache interface by setting a
* global policy which is automatically applied to every storage action.
* The object is constructed using new Policy(options, [cache, segment]) where:
* * options - an object with the IPolicyOptions structure
* * cache - a Client instance (which has already been started).
* * segment - required when cache is provided. The segment name used to
* isolate cached items within the cache partition.
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export class Policy<T, O extends PolicyOptionVariants<T>> {
constructor(options: O, cache: Client<T>, segment: string);
/**
* retrieve an item from the cache. If the item is not
* found and the generateFunc method was provided,
* a new value is generated, stored in the cache, and returned.
* Multiple concurrent requests are queued and processed once. The method arguments are:
* @param id the unique item identifier (within the policy segment).
* Can be a string or an object with the required 'id' key.
*/
get(id: Id): Promise<O extends DecoratedPolicyOptions<T> ? DecoratedResult<T> : T | null>;
/**
* store an item in the cache where:
* @param id - the unique item identifier (within the policy segment).
* @param value - the string or object value to be stored.
* @param ttl - a time-to-live override value in milliseconds after which the item is automatically
* removed from the cache (or is marked invalid).
* This should be set to 0 in order to use the caching rules configured when creating the Policy object.
*/
set(id: Id, value: T, ttl?: number): Promise<void>;
/**
* remove the item from cache where:
* @param id the unique item identifier (within the policy segment).
*/
drop(id: Id): Promise<void>;
/**
* given a created timestamp in milliseconds, returns the time-to-live left
* based on the configured rules.
*/
ttl(created: number): number;
/** changes the policy rules after construction (note that items already stored will not be affected) */
rules(options: PolicyOptions<T>): void;
/**
* returns true if cache engine determines itself as ready, false if it is not ready or if
* here is no cache engine set.
*/
isReady(): boolean;
/** an object with cache statistics */
stats(): CacheStatisticsObject;
}
export interface DecoratedResult<T> {
value: T;
cached: PolicyGetCachedOptions<T>;
report: PolicyGetReportLog;
}
export interface PolicyGetCachedOptions<T> {
/** item - the cached value. */
item: T;
/** stored - the timestamp when the item was stored in the cache. */
stored: number;
/** ttl - the cache ttl value for the record. */
ttl: number;
/** isStale - true if the item is stale. */
isStale: boolean;
}
/**
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export interface PolicyOptions<T> {
/** expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */
expiresIn?: number;
/** expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Uses local time. Cannot be used together with expiresIn. */
expiresAt?: string;
/** 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 function(id, next) where: */
generateFunc?: GenerateFunc<T>;
/**
* 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. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where:
* * stored - the timestamp when the item was stored in the cache (in milliseconds).
* * ttl - the remaining time-to-live (not the original value used when storing the object).
*/
staleIn?: number | ((stored: number, ttl: number) => number);
/** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */
staleTimeout?: number;
/**
* 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 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.
*/
generateTimeout?: number | false;
/** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */
dropOnError?: boolean;
/** generateOnReadError - if false, an upstream cache read error will stop the get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */
generateOnReadError?: boolean;
/** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */
generateIgnoreWriteError?: boolean;
/**
* pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed.
* @default 0, no blocking of concurrent generateFunc calls beyond staleTimeout.
*/
pendingGenerateTimeout?: number;
}
export interface DecoratedPolicyOptions<T> extends PolicyOptions<T> {
/**
* @default false
*/
getDecoratedValue: boolean | undefined;
}
export interface GenerateFuncFlags {
ttl: number;
}
/**
* generateFunc
* Is used in PolicyOptions
* 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 function(id)
* @param id - the id string or object provided to the get() method.
* @param next - the method called when the new item is returned with the signature function(err, value, ttl) where:
* * err - an error condition.
* * value - the new value generated.
* * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy.
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export type GenerateFunc<T> = (id: Id, flags: GenerateFuncFlags) => Promise<T>;
/**
* An object with logging information about the generation operation containing the following keys (as relevant):
*/
export interface PolicyGetReportLog {
/** msec - the cache lookup time in milliseconds. */
msec: number;
/** stored - the timestamp when the item was stored in the cache. */
stored: number;
/** isStale - true if the item is stale. */
isStale: boolean;
/** ttl - the cache ttl value for the record. */
ttl: number;
/** error - lookup error. */
error?: Error;
}
/**
* an object with cache statistics where:
*/
export interface CacheStatisticsObject {
/** sets - number of cache writes. */
sets: number;
/** gets - number of cache get() requests. */
gets: number;
/** hits - number of cache get() requests in which the requested id was found in the cache (can be stale). */
hits: number;
/** stales - number of cache reads with stale requests (only counts the first request in a queued get() operation). */
stales: number;
/** generates - number of calls to the generate function. */
generates: number;
/** errors - cache operations errors. TODO check this */
errors: number;
}

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/catbox": [
"hapi__catbox"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__catbox-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,5 @@
import * as cryptiles from "@hapi/cryptiles";
cryptiles.randomString(0); // $ExpectType string
cryptiles.randomDigits(0); // $ExpectType string
cryptiles.fixedTimeComparison("", ""); // $ExpectTpe boolean

22
types/hapi__cryptiles/index.d.ts vendored Normal file
View File

@@ -0,0 +1,22 @@
// Type definitions for @hapi/cryptiles 4.2
// Project: https://github.com/hapijs/cryptiles
// Definitions by: Alex Wendland <https://github.com/awendland>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Returns a cryptographically strong pseudo-random data string. Takes a size argument for the length of the string.
*/
export function randomString(size: number): string;
/**
* Returns a cryptographically strong pseudo-random data string consisting of only numerical digits (0-9).
* Takes a size argument for the length of the string.
*/
export function randomDigits(size: number): string;
/**
* Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match).
* Returns true if the strings match, false if they differ.
*/
export function fixedTimeComparison(a: string, b: string): boolean;

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/cryptiles": [
"hapi__cryptiles"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__cryptiles-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

4047
types/hapi__hapi/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
import { Request } from '@hapi/hapi';
declare module '@hapi/hapi' {
interface UserCredentials {
a: number;
}
interface AppCredentials {
b: number;
}
}
const req: Request = {} as any;
const scope: string[] | undefined = req.auth.credentials.scope;
const user = req.auth.credentials.user!;
console.log(user.a);
const app = req.auth.credentials.app!;
console.log(app.b);

View File

@@ -0,0 +1,14 @@
// https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route
import { Request, ResponseToolkit, Server, ServerOptions } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const server = new Server(options);
server.route({ method: '*', path: '/{p*}', handler(request, h) {
return h.response('The page was not found').code(404);
}});
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,67 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents
// https://github.com/hapijs/hapi/blob/master/API.md#-requestevents
import { Lifecycle, Request, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
import * as Crypto from 'crypto';
const options: ServerOptions = {
port: 8000,
};
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler(request) {
return 'ok: ' + request.path;
}
};
const onRequest: Lifecycle.Method = (request, h) => {
/*
* Server events
*/
request.server.events.on('request', (request: Request, event: any, tags: any) => {
console.log(request.paramsArray);
console.log(event);
console.log(tags);
});
request.server.events.on('response', (request: Request) => {
console.log('Response sent for request: ' + request.path);
});
request.server.events.on('start', () => {
console.log('Server started');
});
request.server.events.once('stop', () => {
console.log('Server stoped');
});
/*
* Request events
*/
const hash = Crypto.createHash('sha1');
request.events.on("peek", (chunk) => {
hash.update(chunk);
});
request.events.once("finish", () => {
console.log(hash.digest('hex'));
});
request.events.once("disconnect", () => {
console.error('request aborted');
});
return h.continue;
};
const server = new Server(options);
server.route(serverRoute);
server.ext('onRequest', onRequest, {
before: 'test',
});
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,29 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data
import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const handlerFn: Lifecycle.Method = (request, h) => {
request.log(['test', 'error'], 'Test event');
return 'path: ' + request.path;
};
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler: handlerFn
};
const server = new Server(options);
server.route(serverRoute);
server.start();
console.log('Server started at: ' + server.info.uri);
server.events.on('request', (request: Request, event: any, tags: any) => {
console.log(tags);
if (tags.error) {
console.log(event);
}
});

View File

@@ -0,0 +1,4 @@
import { Request } from "@hapi/hapi";
const req: Request = {} as any;
const { completed, responded } = req.info;

View File

@@ -0,0 +1,4 @@
import { Request } from '@hapi/hapi';
declare const req: Request;
const act: boolean = req.active();

View File

@@ -0,0 +1,37 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-requestparams
import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
// Example 1
// http://localhost:8000/album-name/song-optional
const getAlbum: Lifecycle.Method = (request, h) => {
console.log(request.params);
return 'ok: ' + request.path;
};
const serverRoute1: ServerRoute = {
path: '/{album}/{song?}',
method: 'GET',
handler: getAlbum
};
// Example 2
// http://localhost:8000/person/rafael/fijalkowski
const getPerson: Lifecycle.Method = (request, h) => {
const nameParts = request.params.name.split('/');
return { first: nameParts[0], last: nameParts[1] };
};
const serverRoute2: ServerRoute = {
path: '/person/{name*2}',
method: 'GET',
handler: getPerson
};
const server = new Server(options);
server.route(serverRoute1);
server.route(serverRoute2);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,26 @@
// Added test in addition to docs, for request.query
import { Lifecycle, Request, RequestQuery, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const handlerFn: Lifecycle.Method = (request, h) => {
const query1 = request.query;
console.log(query1);
const query2 = request.query;
// http://localhost:8000/?name=test
return `You asked for ${query2.name}`;
};
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler: handlerFn
};
const server = new Server(options);
server.route(serverRoute);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,25 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options
import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const serverRoute: ServerRoute = {
path: '/test',
method: 'GET',
handler(request, h) {
return 'ok: ' + request.path;
}
};
const server = new Server(options);
server.route(serverRoute);
server.ext("onRequest", (request, h) => {
request.setUrl('/test');
return h.continue;
});
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,30 @@
// https://github.com/hapijs/hapi/blob/master/API.md#errors
import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
import * as Boom from "boom";
const options: ServerOptions = {
port: 8000,
};
const serverRoutes: ServerRoute[] = [
{
path: '/badRequest',
method: 'GET',
handler(request, h) {
throw Boom.badRequest('Unsupported parameter');
}
},
{
path: '/internal',
method: 'GET',
handler(request, h) {
throw new Error('unexpect error');
}
},
];
const server = new Server(options);
server.route(serverRoutes);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,20 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi
import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler(request, h) {
return h.redirect('http://example.com');
}
};
const server = new Server(options);
server.route(serverRoute);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,28 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-responseevents
import { Lifecycle, Request, ResponseObject, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
import * as Crypto from "crypto";
const preResponse: Lifecycle.Method = (request, h) => {
// In onPreResponse, the response object will be defined.
const response = <ResponseObject> request.response;
const hash = Crypto.createHash('sha1');
response.events.on('peek', (chunk, encoding) => {
hash.update(chunk);
});
response.events.once('finish', () => {
console.log(hash.digest('hex'));
});
return h.continue;
};
const server = new Server({
port: 8000,
});
server.ext('onPreResponse', preResponse);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,36 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue
import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const serverRoutes: ServerRoute[] = [
// Detailed notation
{
path: '/test1',
method: 'GET',
handler(request, h) {
const response = h.response('success');
response.type('text/plain');
response.header('X-Custom', 'some-value');
return response;
}
},
// Chained notation
{
path: '/test2',
method: 'GET',
handler(request, h) {
return h.response('success')
.type('text/plain')
.header('X-Custom', 'some-value');
}
},
];
const server = new Server(options);
server.route(serverRoutes);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,38 @@
// from https://hapijs.com/tutorials/getting-started#adding-routes
import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler(request, h) {
return 'ok: ' + request.path;
}
};
const serverRoutes: ServerRoute[] = [
{
path: '/test1',
method: 'GET',
handler(request, h) {
return 'ok: ' + request.path;
}
},
{
path: '/test2',
method: 'GET',
handler(request, h) {
return 'ok: ' + request.path;
}
},
];
const server = new Server(options);
server.route(serverRoute);
server.route(serverRoutes);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,52 @@
import { Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
// different methods
const routeConfig: ServerRoute = {
path: '/signin',
method: 'PUT',
vhost: 'site.coms',
};
const routeConfigTest1: ServerRoute = {
path: '/signin',
method: '*'
};
const routeConfigTest2: ServerRoute = {
path: '/signin',
method: ['OPTIONS', '*']
};
// different handlers
const routeConfigTest3: ServerRoute = {
path: '/signin',
method: 'PUT',
handler(request, h) {
return 'ok';
}
};
const routeConfigTest4: ServerRoute = {
path: '/signin',
method: 'PUT',
handler(request, h) {
return 'ok';
}
};
const server = new Server(options);
server.route(routeConfig);
// Handler in config
const user: RouteOptions = {
cache: { expiresIn: 5000 },
handler(request, h) {
return { name: 'John' };
}
};
server.route({method: 'GET', path: '/user', options: user });
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,22 @@
import { Server } from "@hapi/hapi";
const server = new Server();
server.route({
method: 'get',
path: "/test",
options: {
ext: {
onPreResponse: {
method(_request, h) {
return h.continue;
},
},
onPostHandler: [{
method(_request, h) {
return h.continue;
},
}],
}
}
});

View File

@@ -0,0 +1,9 @@
import { Lifecycle, Request, ResponseToolkit } from "@hapi/hapi";
const handler: Lifecycle.Method = (request, h) => {
return 'success';
};
const strictHandler: Lifecycle.Method = (request, h) => {
return 123;
};

View File

@@ -0,0 +1,42 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre
import { Lifecycle, Request, ResponseToolkit, Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
const pre1: Lifecycle.Method = (request, h) => {
return 'Hello';
};
const pre2: Lifecycle.Method = (request, h) => {
return 'World';
};
const pre3: Lifecycle.Method = (request, h) => {
return `request.pre.m1 request.pre.m2`;
};
server.route({
method: 'GET',
path: '/',
options: {
pre: [
[
// m1 and m2 executed in parallel
{ method: pre1, assign: 'm1' },
{ method: pre2, assign: 'm2' }
],
{ method: pre3, assign: 'm3' },
],
handler(request, h) {
return request.pre.m3 + '!\n';
}
}
});
server.start();
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});

View File

@@ -0,0 +1,194 @@
// https://github.com/hapijs/hapi/blob/master/API.md#route-options
import {
Lifecycle,
Request,
ResponseToolkit,
RouteOptions,
RouteOptionsAccess,
RouteOptionsCors,
RouteOptionsPayload,
RouteOptionsResponse,
RouteOptionsValidate,
Server,
RouteOptionsSecureObject
} from "@hapi/hapi";
const routeOptionsAccess: RouteOptionsAccess = {
access: [
{
scope: false
},
{
entity: 'user'
}
],
scope: false,
entity: 'user',
mode: 'optional',
payload: 'optional',
strategies: ['', ''],
strategy: ''
};
const corsOption: RouteOptionsCors = {
origin: 'ignore',
maxAge: 5000,
headers: ['test', 'test', 'test'],
additionalHeaders: ['test', 'test', 'test'],
exposedHeaders: ['test', 'test', 'test'],
additionalExposedHeaders: ['test', 'test', 'test'],
credentials: false
};
const payloadOptions: RouteOptionsPayload = {
allow: 'string',
compression: {
test1: {
test: 2
}
},
defaultContentType: 'application/json',
failAction(request, h) {
return 'ok: ' + request.path;
},
maxBytes: 1048576,
multipart: {
output: 'annotated'
},
output: 'stream',
override: '',
parse: 'gunzip',
timeout: 5000,
uploads: 'dir/'
};
const pre1: Lifecycle.Method = (request, h) => {
return 'Hello';
};
const pre2: Lifecycle.Method = (request, h) => {
return 'World';
};
const pre3: Lifecycle.Method = (request, h) => {
return `request.pre.m1 request.pre.m2`;
};
const routeOptionsResponse: RouteOptionsResponse = {
emptyStatusCode: 200,
failAction(request, h) {
return 'ok: ' + request.path;
},
modify: false,
options: undefined,
ranges: true,
sample: 100,
schema: true,
status: {
200: true,
302: true,
404: false,
},
disconnectStatusCode: 123,
};
const routeOptionSecure: RouteOptionsSecureObject = {
referrer: 'origin',
noSniff: true,
xframe: "deny",
hsts: {
includeSubdomains: true,
maxAge: 1111,
preload: false,
},
noOpen: false,
xss: true,
};
const routeOptionsValidate: RouteOptionsValidate = {
errorFields: {},
failAction(request, h) {
return 'ok: ' + request.path;
},
headers: false,
options: {},
params: false,
payload: true,
query: true,
};
declare module '@hapi/hapi' {
interface RouteOptionsApp {
one: number;
two: string;
}
}
const routeOptions: RouteOptions = {
app: {
one: 1,
two: "2"
},
auth: routeOptionsAccess,
bind: null,
cache: {
privacy: 'default',
statuses: [200],
otherwise: 'no-cache'
},
compression: {
test1: {
test: 2
}
},
cors: corsOption,
description: 'description here',
ext: undefined,
files: { relativeTo: '.' },
handler(request, h) {
return 'ok: ' + request.path;
},
id: 'test',
isInternal: false,
json: undefined,
jsonp: 'callback',
log: { collect: false },
notes: ['test', 'test', 'test'],
payload: payloadOptions,
plugins: {
plugin1: {},
plugin2: {},
},
pre: [
[
// m1 and m2 executed in parallel
{ method: pre1, assign: 'm1' },
{ method: pre2, assign: 'm2' }
],
{ method: pre3, assign: 'm3' },
],
response: routeOptionsResponse,
security: false,
state: {
parse: true,
failAction(request, h) {
return 'ok: ' + request.path;
},
},
tags: ['test', 'test', 'test'],
timeout: {
server: 10000,
socket: false
},
validate: routeOptionsValidate
};
const server = new Server({
port: 8000,
routes: routeOptions
});
server.start();
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});

View File

@@ -0,0 +1,51 @@
// from https://hapijs.com/tutorials/validation?lang=en_US
import { Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
import * as Joi from "@hapi/joi";
const options: ServerOptions = {
port: 8000,
};
const routeOptions: RouteOptions = {
validate: {
payload: {
id: Joi.string().uuid().required(),
name: Joi.object({
firstName: Joi.string().required(),
lastName: Joi.string().allow(null)
}),
firstName: Joi.ref("name.firstName")
},
params: {
name: Joi.string().min(3).max(10),
nameRef: Joi.ref("name")
},
state: {
woop: Joi.string().allow('doop'),
},
},
response: {
schema: Joi.object({
a: Joi.string(),
b: Joi.object({
c: Joi.number()
}),
d: Joi.ref("b.c")
})
}
};
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler(request, h) {
return 'ok: ' + request.path;
},
options: routeOptions
};
const server = new Server(options);
server.route(serverRoute);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,29 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverapp
import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
declare module "@hapi/hapi" {
// Demonstrate augmenting the application state.
interface ApplicationState {
key?: string;
}
}
const server = new Server(options);
server.app.key = 'value2';
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler(request, h) {
return 'key: ' + request.server.app.key;
}
};
server.route(serverRoute);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,40 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi
import {
Server,
ServerAuthScheme,
} from "@hapi/hapi";
import * as Boom from "@hapi/boom";
declare module '@hapi/hapi' {
interface ServerAuthSchemeObjectApi {
settings: {
x: number;
};
}
}
const scheme: ServerAuthScheme = (server, options) => {
return {
api: {
settings: {
x: 5
}
},
authenticate(request, h) {
const authorization = request.headers.authorization;
if (!authorization) {
throw Boom.unauthorized(null, 'Custom');
}
return h.authenticated({ credentials: { user: { a: 1 } } });
}
};
};
const server = new Server({
port: 8000,
});
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.start();
console.log(server.auth.api.default.settings.x); // 5

View File

@@ -0,0 +1,41 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions
// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme
import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "@hapi/hapi";
import * as Boom from "@hapi/boom";
declare module '@hapi/hapi' {
interface UserCredentials {
a: number;
}
}
const server = new Server({
port: 8000,
});
const scheme: ServerAuthScheme = (server, options) => {
return {
authenticate(request, h) {
const req = request.raw.req;
const authorization = req.headers.authorization;
if (!authorization) {
throw Boom.unauthorized(null, 'Custom');
}
return h.authenticated({ credentials: { user: { a: 1 }, scope: ['test'] } });
}
};
};
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.auth.default('default');
server.route({
method: 'GET',
path: '/',
handler(request, h) {
return request.auth.credentials.user || 'not authed';
}
});
server.start();

View File

@@ -0,0 +1,45 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request
// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme
import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "@hapi/hapi";
import * as Boom from "@hapi/boom";
declare module '@hapi/hapi' {
interface AuthCredentials {
name?: string;
}
}
const server = new Server({
port: 8000,
});
const scheme: ServerAuthScheme = (server, options) => {
return {
authenticate(request, h) {
const req = request.raw.req;
const authorization = req.headers.authorization;
if (!authorization) {
throw Boom.unauthorized(null, 'Custom');
}
return h.authenticated({ credentials: { name: 'john', } });
}
};
};
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.route({
method: 'GET',
path: '/',
handler: async (request: Request, h: ResponseToolkit) => {
try {
const { credentials } = await request.server.auth.test('default', request);
return { status: true, user: credentials.name };
} catch (err) {
return { status: false };
}
}
});
server.start();

View File

@@ -0,0 +1,26 @@
import { Request, Server, RequestAuth } from "@hapi/hapi";
import * as Boom from "@hapi/boom";
const server = new Server({
port: 8000,
});
server.auth.scheme('custom', () => ({
authenticate() {
throw Boom.unauthorized(null, 'hurr');
},
async verify(_auth: RequestAuth) {
throw Boom.unauthorized(null, 'durr');
}
}));
server.auth.strategy('default', 'custom');
server.route({
method: 'GET',
path: '/',
async handler(request: Request) {
request.server.auth.verify(request);
}
});
server.start();

View File

@@ -0,0 +1,27 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext
import { Lifecycle, Plugin, Request, ResponseToolkit, Server, ServerRegisterOptions } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
const handler: Lifecycle.Method = (request, h) => {
return h.context.message; // Or h.context.message
};
const plugin: Plugin<any> = {
name: 'example',
register: async (server, options) => {
const bind = {
message: 'hello'
};
server.bind(bind);
server.route({ method: 'GET', path: '/', handler });
}
};
server.start();
server.register(plugin);
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});

View File

@@ -0,0 +1,19 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions
import { Server } from "@hapi/hapi";
import * as catbox from "@hapi/catbox";
const server = new Server({
port: 8000,
});
server.initialize();
server.cache.provision({engine: require('@hapi/catbox-memory'), name: 'countries' });
const cache = server.cache<string>({segment: 'countries', cache: 'countries', expiresIn: 60 * 60 * 1000 });
cache.set('norway', 'oslo', 10 * 1000).then(() => {});
const value = cache.get('norway').then(() => {});
server.start();
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});

View File

@@ -0,0 +1,23 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions
import { Server, ServerOptionsCache } from "@hapi/hapi";
import * as catbox from "@hapi/catbox";
const server = new Server({
port: 8000,
});
const catboxOptions: ServerOptionsCache = {
segment: 'countries',
expiresIn: 60 * 60 * 1000
};
const cache = server.cache<string>(catboxOptions);
cache.set('norway', 'oslo', 10 * 1000).then(() => {});
const value = cache.get('norway').then(() => {});
console.log("Value: " + value);
server.start();
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});

View File

@@ -0,0 +1,3 @@
import { Server } from "@hapi/hapi";
new Server().control(new Server());

View File

@@ -0,0 +1,8 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder
import { Server } from "@hapi/hapi";
import * as Zlib from "zlib";
const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } });
server.decoder('special', (options) => Zlib.createGunzip(options));
server.start();

View File

@@ -0,0 +1,111 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options
import { Request, ResponseToolkit, Server } from "@hapi/hapi";
declare module '@hapi/hapi' {
interface HandlerDecorations {
test?: {
test: number;
};
}
}
// Test basic types.
const server = new Server({
port: 8000,
});
server.start();
server.decorate('toolkit', 'success', function() {
return this.response({ status: 'ok' });
});
server.decorate('handler', 'test', (route, options) => (req, h) => 123);
server.route({
method: 'GET',
path: '/',
handler: {
test: {
test: 123,
},
asd: 1,
}
});
console.log(server.decorations.toolkit);
// Test decorators with additional arguments
declare module '@hapi/hapi' {
interface Server {
withParams(x: number, y: string): string;
}
interface ResponseToolkit {
withParams(x: number, y: string): string;
}
}
function decorateServerWithParams(this: Server, x: number, y: string) {
return `${x} ${y}`;
}
server.decorate('server', 'withParams', decorateServerWithParams);
server.withParams(1, "one");
function decorateToolkitWithParams(this: ResponseToolkit, x: number, y: string) {
return `${x} ${y}`;
}
server.decorate('toolkit', 'withParams', decorateToolkitWithParams);
server.decorate('toolkit', Symbol('hi'), decorateToolkitWithParams);
server.route({
method: 'GET',
path: '/toolkitWithParams',
handler: (r, h) => {
return h.withParams(1, "one");
}
});
// Test request + apply option types
declare module '@hapi/hapi' {
interface Request {
withApply(x: string, y: number): string;
}
}
function decorateRequestWithApply(request: Request) {
return (x: string, y: number) => {
return `${x} ${y}`;
};
}
server.decorate('request', 'withApply', decorateRequestWithApply, {apply: true});
server.route({
method: 'GET',
path: '/requestWithApply',
handler: (r, h) => {
return r.withApply("one", 1);
}
});
// Test extend option type
declare module '@hapi/hapi' {
interface Server {
withExtend(x: string, y: number): string;
}
}
const decorateServerWithExtend = (existing: () => void) => {
return (x: string, y: number) => {
existing();
return `${x} ${y}`;
};
};
server.decorate('server', 'withExtend', decorateServerWithExtend, {extend: true});
server.withExtend("one", 1);

View File

@@ -0,0 +1,8 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder
import { Server } from "@hapi/hapi";
import * as Zlib from "zlib";
const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } });
server.encoder('special', (options) => Zlib.createGzip(options));
server.start();

View File

@@ -0,0 +1,31 @@
// from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener
import { Request, ResponseToolkit, Server, ServerRoute } from "@hapi/hapi";
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler(request, h) {
return 'oks: ' + request.path;
}
};
declare module '@hapi/hapi' {
interface ServerEvents {
once(event: 'test1', listener: (update: string) => void): this;
once(event: 'test2', listener: (...updates: string[]) => void): this;
}
}
const server = new Server({
port: 8000,
});
server.route(serverRoute);
server.event('test1');
server.event('test2');
server.events.once('test1', update => { console.log(update); });
server.events.once('test2', (...args) => { console.log(args); });
server.events.emit('test1', 'hello-1');
server.events.emit('test2', 'hello-2'); // Ignored
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,24 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents
import { Server, ServerEvents } from "@hapi/hapi";
import Podium = require('@hapi/podium');
import '@hapi/hapi/definitions/server/server';
declare module '@hapi/hapi' {
interface ServerEvents {
on(event: 'test', listener: (update: string) => void): this;
}
}
const server = new Server({
port: 8000,
});
server.events.on('route', route => {
console.log(route.path, route.vhost, route.realm, route.method, route.settings, route.fingerprint);
});
server.event('test');
server.events.on('test', (update: any) => console.log(update));
server.events.emit('test', 'hello');
server.start();

View File

@@ -0,0 +1,38 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins
import { Plugin, Server, ServerRegisterOptions } from "@hapi/hapi";
declare module '@hapi/hapi' {
interface PluginProperties {
example1: {
util(): void;
};
example2: {
util(): void;
};
}
}
const plugin1: Plugin<any> = {
name: 'example1',
async register(server: Server, options: ServerRegisterOptions) {
server.expose('util', () => console.log('something'));
}
};
const plugin2: Plugin<any> = {
name: 'example2',
async register(server: Server, options: ServerRegisterOptions) {
server.expose('util', () => console.log('something'));
}
};
const server = new Server({
port: 8000,
});
server.start();
server.register(plugin1);
server.register(plugin2);
server.plugins.example1.util();
server.plugins.example2.util();

View File

@@ -0,0 +1,10 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo
import { Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
server.start();
console.log(server.info);
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,40 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions
import { Request, ResponseToolkit, Server, ServerRoute } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
const serverRoute: ServerRoute = {
path: '/',
method: 'GET',
handler(request, h) {
return 'Success!';
}
};
server.route(serverRoute);
server.start();
server.inject('/').then(res => console.log(res.result));
declare module '@hapi/hapi' {
interface ApplicationState {
injectState?: number;
}
}
server.inject({
auth: {
strategy: 'test',
credentials: {
user: {
a: 1,
},
},
},
url: "test",
app: {
injectState: 1
}
});

View File

@@ -0,0 +1,14 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener
import { Server } from "@hapi/hapi";
import * as SocketIO from "socket.io";
const server = new Server({
port: 8000,
});
const io = SocketIO.listen(server.listener);
io.sockets.on('connection', (socket) => {
socket.emit('welcome');
});
server.start();

View File

@@ -0,0 +1,17 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverload
import { Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
load: {
sampleInterval: 1000,
concurrent: 123,
}
});
server.start();
setTimeout(() => {
console.log(server.load.rss);
console.log(server.load.eventLoopDelay);
console.log(server.load.heapUsed);
}, 5 * 1000);

View File

@@ -0,0 +1,20 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid
import { RequestRoute, Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
server.route({
path: '/',
method: 'GET',
options: {
id: 'root',
handler: () => 'ok'
}
});
const route: RequestRoute | null = server.lookup('root');
console.log(route);
server.start();

View File

@@ -0,0 +1,23 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host
import { RequestRoute, Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
server.route({
path: '/',
method: 'GET',
options: {
id: 'root',
handler: () => 'ok'
}
});
const route: RequestRoute | null = server.match('get', '/');
if (route !== null) {
console.log(route.path);
}
server.start();

View File

@@ -0,0 +1,25 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods
import { Server, ServerMethodConfigurationObject } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
server.start();
const add = (a: any, b: any): number => {
return a + b;
};
const methodObject: ServerMethodConfigurationObject = {
name: 'sum',
method: add,
options: {
cache: {
expiresIn: 2000,
generateTimeout: 100
},
generateKey: (a: string | undefined) => a === undefined ? null : a
}
};
server.method(methodObject);

View File

@@ -0,0 +1,11 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-servermethods
import { Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
server.start();
server.method('add', (a, b) => (a + b));
const result = server.methods.add(1, 2); // 3
console.log(result);

View File

@@ -0,0 +1,22 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-servermime
import { Server, ServerOptions } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
mime: {
override: {
'node/module': {
source: 'steve',
compressible: false,
extensions: ['node', 'module', 'npm'],
type: 'node/module'
}
}
}
};
const server = new Server(options);
console.log(server.mime.path('code.js').type); // 'application/javascript'
console.log(server.mime.path('file.npm').type); // 'node/module'
server.start();

View File

@@ -0,0 +1,114 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-server-options
import { Plugin, RouteOptions, Server, ServerOptions, ServerRegisterOptions } from "@hapi/hapi";
import { MimosOptions, MimosOptionsValue } from "@hapi/mimos";
const mimeOptions: MimosOptions = {
override: {
'node/module': {
source: 'iana',
compressible: true,
extensions: ['node', 'modsule', 'npm'],
type: 'node/module'
},
'application/javascript': {
source: 'iana',
charset: 'UTF-8',
compressible: true,
extensions: ['js', 'javascript'],
type: 'text/javascript'
},
'text/html': {
predicate: (mime: MimosOptionsValue) => {
if (1 === 1) {
// mime.foo = 'test';
} else {
// mime.foo = 'bar';
}
return mime;
}
}
}
};
const plugin: Plugin<any> = {
name: 'example',
register: async (server: Server, options: ServerRegisterOptions) => {
server.expose('key', 'value');
server.plugins.example.other = 'other';
console.log(server.plugins.example.key); // 'value'
console.log(server.plugins.example.other); // 'other'
}
};
const routeOptions: RouteOptions = {
compression: {
test: {
some: 'option'
}
},
files: {
relativeTo: __dirname
},
cors: {
origin: ['http://test.example.com', 'http://www.example.com', 'http://*.a.com']
},
};
declare module '@hapi/hapi' {
interface ServerOptionsApp {
key1?: string;
key2?: string;
any_thing?: string;
}
}
const options: ServerOptions = {
address: '0.0.0.0',
app: {
key1: 'value1',
key2: 'value2',
any_thing: 'any_value',
},
autoListen: true,
cache: {
engine: require('@hapi/catbox-memory'),
name: 'test',
shared: true,
partition: 'hapi-cache',
any_thing_1: 'any_thing_1',
any_thing_2: 'any_thing_2'
},
compression: {
minBytes: 1024
},
debug: {
request: ['implementation']
},
host: 'localhost',
listener: undefined,
load: { sampleInterval: 0 },
mime: mimeOptions,
plugins: plugin,
port: 8000,
router: {
isCaseSensitive: true,
stripTrailingSlash: false
},
routes: routeOptions,
state: {
strictHeader: true,
ignoreErrors: false,
isSecure: true,
isHttpOnly: true,
isSameSite: 'Strict',
encoding: 'none'
},
tls: true
};
const server = new Server(options);
server.start();
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});

View File

@@ -0,0 +1,37 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto
import { Plugin, Server, ServerRegisterOptions, ServerRoute } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
// Definition for INERT
declare module '@hapi/hapi' {
interface HandlerDecorations {
file?: string;
}
}
const serverRouteOption: ServerRoute = {
path: '/file',
method: 'GET',
handler: {
file: './test.html'
}
};
const plugin: Plugin<any> = {
name: 'example',
register: async (server: Server, options: ServerRegisterOptions) => {
// Assuming the Inert plugin was registered previously
server.path(__dirname + '../static');
server.route(serverRouteOption);
}
};
server.start();
server.register(plugin);
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});

View File

@@ -0,0 +1,116 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins
import { Plugin, Server, ServerRegisterOptions } from "@hapi/hapi";
interface Plugin1 {
one: 1;
}
interface Plugin2 {
two: 2;
}
interface Plugin3 {
three: 3;
}
interface Plugin4 {
four: 4;
}
declare module '@hapi/hapi' {
interface PluginProperties {
example: {
other: string;
key: string;
};
}
}
const plugin1: Plugin<Plugin1> = {
name: 'plugin1',
register: async (server: Server, options: Plugin1) => {
server.expose('key', 'value');
server.plugins.example.other = 'other';
console.log(server.plugins.example.key); // 'value'
console.log(server.plugins.example.other); // 'other'
},
};
const plugin2: Plugin<Plugin2> = {
name: 'plugin2',
register: async (server: Server, options: Plugin2) => {},
dependencies: {
plugin1: '*',
},
requirements: {
node: '>=8',
hapi: '>=1337',
},
};
const plugin3: Plugin<Plugin3> = {
name: 'plugin3',
register: async (server: Server, options: Plugin3) => {},
dependencies: ['plugin2'],
};
const plugin4: Plugin<Plugin4> = {
name: 'plugin4',
register: (server: Server, options: Plugin4) => {},
dependencies: 'plugin3',
};
const server = new Server({
port: 8000,
});
server.start();
server.register(plugin1);
server.register({
plugin: plugin1,
options: {one: 1}
});
server.register([
{
plugin: plugin2,
options: {two: 2}
},
{
plugin: plugin3,
options: {three: 3}
},
{
plugin: plugin1,
options: {one: 1}
},
{
plugin: plugin2,
options: {two: 2}
},
{
plugin: plugin3,
options: {three: 3}
},
{
plugin: plugin1,
options: {one: 1}
},
{
plugin: plugin2,
options: {two: 2}
},
{
plugin: plugin3,
options: {three: 3}
},
{
plugin: plugin1,
options: {one: 1}
},
{
plugin: plugin4,
options: {four: 4}
}
]);

View File

@@ -0,0 +1,18 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serversettings
import { Server } from "@hapi/hapi";
declare module '@hapi/hapi' {
interface ServerOptionsApp {
key?: string;
}
}
const server = new Server({
port: 8000,
app: {
key: 'value'
}
});
server.start();
console.log(server.settings.app); // { key: 'value' }

View File

@@ -0,0 +1,11 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart
import { Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
server.start();
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});

View File

@@ -0,0 +1,28 @@
// from https://hapijs.com/tutorials/cookies?lang=en_US
import { Server, ServerOptions, ServerRoute, ServerStateCookieOptions } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const serverRoute: ServerRoute = {
path: '/say-hello',
method: 'GET',
handler(_request, h) {
h.state('test', { test: true });
return h.response('Hello').state('data', { firstVisit: false });
}
};
const server = new Server(options);
server.route(serverRoute);
const stateOption: ServerStateCookieOptions = {
ttl: 24 * 60 * 60 * 1000, // One day
isSecure: false,
isHttpOnly: false,
encoding: 'base64json',
};
server.state('data', stateOption);
server.start();
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,17 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions
import { Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
server.start();
server.events.on('start', () => {
console.log('Server started at: ' + server.info.uri);
});
server.events.on('stop', () => {
console.log('Server stoped.');
});
setTimeout(() => {
server.stop({ timeout: 10 * 1000 });
}, 5 * 1000);

View File

@@ -0,0 +1,29 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost
import { Request, ResponseToolkit, Server, ServerOptions } from "@hapi/hapi";
const options: ServerOptions = {
port: 8000,
};
const server = new Server(options);
server.app.key = 'value2';
server.route({
path: '/',
method: 'GET',
handler(request, h) {
return h.response("Hello World");
}
});
server.start();
const table = server.table();
console.log(table);
console.log(table[0].method);
console.log(table[0].path);
console.log(table[0].vhost);
console.log(table[0].realm);
console.log(table[0].settings);
console.log(table[0].fingerprint);
console.log(table[0].auth);
console.log('Server started at: ' + server.info.uri);

View File

@@ -0,0 +1,9 @@
// https://github.com/hapijs/hapi/blob/master/API.md#-serverversion
import { Server } from "@hapi/hapi";
const server = new Server({
port: 8000,
});
server.start();
console.log(server.version); // 17.x.x

View File

@@ -0,0 +1,101 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/hapi": [
"hapi__hapi"
],
"@hapi/boom": [
"hapi__boom"
],
"@hapi/shot": [
"hapi__shot"
],
"@hapi/mimos": [
"hapi__mimos"
],
"@hapi/iron": [
"hapi__iron"
],
"@hapi/joi": [
"hapi__joi"
],
"@hapi/podium": [
"hapi__podium"
],
"@hapi/catbox": [
"hapi__catbox"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"test/request/auth.ts",
"test/request/catch-all.ts",
"test/request/event-types.ts",
"test/request/get-log.ts",
"test/request/info.ts",
"test/request/methods.ts",
"test/request/parameters.ts",
"test/request/query.ts",
"test/response/continue.ts",
"test/response/error.ts",
"test/response/redirect.ts",
"test/response/response-events.ts",
"test/response/response.ts",
"test/route/adding-routes.ts",
"test/route/config.ts",
"test/route/ext.ts",
"test/route/handler.ts",
"test/route/route-options-pre.ts",
"test/route/route-options.ts",
"test/route/validation.ts",
"test/server/server-app.ts",
"test/server/server-auth-api.ts",
"test/server/server-auth-default.ts",
"test/server/server-auth-test.ts",
"test/server/server-auth-verify.ts",
"test/server/server-bind.ts",
"test/server/server-cache-provision.ts",
"test/server/server-cache.ts",
"test/server/server-control.ts",
"test/server/server-decoder.ts",
"test/server/server-decorations.ts",
"test/server/server-encoder.ts",
"test/server/server-events-once.ts",
"test/server/server-events.ts",
"test/server/server-expose.ts",
"test/server/server-info.ts",
"test/server/server-inject.ts",
"test/server/server-listener.ts",
"test/server/server-load.ts",
"test/server/server-lookup.ts",
"test/server/server-match.ts",
"test/server/server-method.ts",
"test/server/server-methods.ts",
"test/server/server-mime.ts",
"test/server/server-options.ts",
"test/server/server-path.ts",
"test/server/server-plugins.ts",
"test/server/server-settings.ts",
"test/server/server-start.ts",
"test/server/server-state.ts",
"test/server/server-stop.ts",
"test/server/server-table.ts",
"test/server/server-version.ts"
]
}

View File

@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-angle-bracket-type-assertion": false
}
}

View File

@@ -0,0 +1,291 @@
import * as Hoek from "@hapi/hoek";
/**
* Import the entire module as above or use named imports:
* import { clone, merge, assert } from "@hapi/hoek";
* "Tests" taken straight from hoek API reference and adapted to TypeScript.
*/
// clone(obj)
let nestedObj = {
w: /^something$/ig,
x: {
a: [1, 2, 3],
b: 123456,
c: new Date()
},
y: 'y',
z: new Date()
};
let copy = Hoek.clone(nestedObj);
copy.x.b = 100;
console.log(copy.y); // results in 'y'
console.log(nestedObj.x.b); // results in 123456
console.log(copy.x.b); // results in 100
// cloneWithShallow(obj, keys)
nestedObj = {
w: /^something$/ig,
x: {
a: [1, 2, 3],
b: 123456,
c: new Date()
},
y: 'y',
z: new Date()
};
copy = Hoek.cloneWithShallow(nestedObj, ['x']);
copy.x.b = 100;
console.log(copy.y); // results in 'y'
console.log(nestedObj.x.b); // results in 100
console.log(copy.x.b); // results in 100
// merge(target, source, isNullOverride, isMergeArrays)
const target = { a: 1, b: 2 };
const source = { a: 0, c: 5 };
const source2 = { a: null, c: 5 };
Hoek.merge(target, source); // results in {a: 0, b: 2, c: 5}
Hoek.merge(target, source2); // results in {a: null, b: 2, c: 5}
Hoek.merge(target, source2, false); // results in {a: 1, b: 2, c: 5}
const targetArray = [1, 2, 3];
const sourceArray = [4, 5];
Hoek.merge(targetArray, sourceArray); // results in [1, 2, 3, 4, 5]
Hoek.merge(targetArray, sourceArray, true, false); // results in [4, 5]
// applyToDefaults(defaults, options, isNullOverride)
let defaults = { host: "localhost", port: 8000 };
const options = { port: 8080 };
let config = Hoek.applyToDefaults(defaults, options); // results in { host: "localhost", port: 8080 }
defaults = { host: "localhost", port: 8000 };
const options1 = { host: null, port: 8080 };
config = Hoek.applyToDefaults(defaults, options1, true); // results in { host: null, port: 8080 }
// applyToDefaultsWithShallow(defaults, options, keys)
const defaults1 = {
server: {
host: "localhost",
port: 8000
},
name: 'example'
};
const options2 = { server: { port: 8080 } };
const config1 = Hoek.applyToDefaultsWithShallow(defaults1, options2, ['server']); // results in { server: { port: 8080 }, name: 'example' }
// deepEqual(b, a, [options])
Hoek.deepEqual({ a: [1, 2], b: 'string', c: { d: true } }, { a: [1, 2], b: 'string', c: { d: true } }); // results in true
Hoek.deepEqual(Object.create(null), {}, { prototype: false }); // results in true
Hoek.deepEqual(Object.create(null), {}); // results in false
// unique(array, key)
let array = [1, 2, 2, 3, 3, 4, 5, 6];
const newArray = Hoek.unique(array); // results in [1,2,3,4,5,6]
let array1 = [{ id: 1 }, { id: 1 }, { id: 2 }];
const newArray1 = Hoek.unique(array1, "id"); // results in [{id: 1}, {id: 2}]
// mapToObject(array, key)
array = [1, 2, 3];
let newObject = Hoek.mapToObject(array); // results in {"1": true, "2": true, "3": true}
array1 = [{ id: 1 }, { id: 2 }];
newObject = Hoek.mapToObject(array1, "id"); // results in {"1": true, "2": true}
// intersect(array1, array2)
array = [1, 2, 3];
const array2 = [1, 4, 5];
const newArray2 = Hoek.intersect(array, array2); // results in [1]
// contain(ref, values, [options])
Hoek.contain('aaa', 'a', { only: true }); // true
Hoek.contain([{ a: 1 }], [{ a: 1 }], { deep: true }); // true
Hoek.contain([1, 2, 2], [1, 2], { once: true }); // false
Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1, d: 4 }, { part: true }); // true
// flatten(array, [target])
let array3 = [1, [2, 3]];
let flattenedArray = Hoek.flatten(array); // results in [1, 2, 3]
array3 = [1, [2, 3]];
const target1 = [4, [5]];
flattenedArray = Hoek.flatten(array3, target1); // results in [4, [5], 1, 2, 3]
// reach(obj, chain, [options])
let chain = 'a.b.c';
let obj = { a: { b: { c: 1 } } };
Hoek.reach(obj, chain); // returns 1
chain = 'a.b.-1';
const obj1 = { a: { b: [2, 3, 6] } };
Hoek.reach(obj1, chain); // returns 6
// reachTemplate(obj, template, [options])
chain = 'a.b.c';
obj = { a: { b: { c: 1 } } };
Hoek.reachTemplate(obj, '1+{a.b.c}=2'); // returns '1+1=2'
// transform(obj, transform, [options])
const source1 = {
address: {
one: '123 main street',
two: 'PO Box 1234'
},
title: 'Warehouse',
state: 'CA'
};
let result = Hoek.transform(source1, {
'person.address.lineOne': 'address.one',
'person.address.lineTwo': 'address.two',
title: 'title',
'person.address.region': 'state'
});
// Results in
// {
// person: {
// address: {
// lineOne: '123 main street',
// lineTwo: 'PO Box 1234',
// region: 'CA'
// }
// },
// title: 'Warehouse'
// }
// shallow(obj)
const shallow = Hoek.shallow({ a: { b: 1 } });
// stringify(obj)
let a: any = {};
a.b = a;
Hoek.stringify(a); // Returns '[Cannot display object: Converting circular structure to JSON]'
// Timer
const timerObj = new Hoek.Timer();
console.log("Time is now: " + timerObj.ts);
console.log(`Elapsed time from initialization: ${timerObj.elapsed()}milliseconds`);
// Bench
const benchObj = new Hoek.Bench();
console.log(`Elapsed time from initialization: ${benchObj.elapsed()}milliseconds`);
// base64urlEncode(value)
Hoek.base64urlEncode("hoek");
// base64urlDecode(value)
Hoek.base64urlDecode("aG9law==");
// escapeHtml(string)
const string = '<html> hey </html>';
const escapedString = Hoek.escapeHtml(string); // returns &lt;html&gt; hey &lt;/html&gt;
// escapeHeaderAttribute(attribute)
a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); // returns I said \"go w\\o me\"
// escapeRegex(string)
a = Hoek.escapeRegex('4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,'); // returns 4\^f\$s\.4\*5\+\-_\?%\=#\!\:@\|~\\\/`"\(>\)\[<\]d\{\}s\,
// assert(condition, message)
const x = 1;
const y = 2 as number;
Hoek.assert(x === y, 'x should equal y'); // Throws 'x should equal y'
Hoek.assert(x === y, new Error('x should equal y')); // Throws the given error object
// abort(message)
Hoek.abort("Error message");
// displayStack(slice)
const stack = Hoek.displayStack();
console.log(stack);
// callStack(slice)
const stack2 = Hoek.callStack();
console.log(stack2);
// nextTick(fn)
let myFn = () => {
console.log('Do this later');
};
const nextFn = Hoek.nextTick(myFn);
nextFn();
console.log('Do this first');
// Results in:
//
// Do this first
// Do this later
// once(fn)
myFn = () => {
console.log('Ran myFn');
};
const onceFn = Hoek.once(myFn);
onceFn(); // results in "Ran myFn"
onceFn(); // results in undefined
// ignore
Hoek.ignore();
// uniqueFilename(path, extension)
const result1 = Hoek.uniqueFilename('./test/modules', 'txt'); // results in "full/path/test/modules/{random}.txt"
// isInteger(value)
result = Hoek.isInteger('23');

213
types/hapi__hoek/index.d.ts vendored Normal file
View File

@@ -0,0 +1,213 @@
// Type definitions for @hapi/hoek 6.2
// Project: https://github.com/hapijs/hoek
// Definitions by: Prashant Tiwari <https://github.com/prashaantt>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface ContainOptions {
/** Perform a deep comparison of the values? */
deep?: boolean;
/** Allow only one occurrence of each value? */
once?: boolean;
/** Don't allow values not explicitly listed? */
only?: boolean;
/** Allow partial match of the values? */
part?: boolean;
}
export interface ReachOptions {
/** String to split chain path on. Defaults to ".". */
separator?: string;
/** Value to return if the path or value is not present. Default is undefined. */
default?: any;
/** Throw an error on missing member? Default is false. */
strict?: boolean;
/** Allow traversing functions for properties? */
functions?: boolean;
}
// Object
/**
* Clone an object or an array.
*/
export function clone<T>(obj: T): T;
/**
* Clone an object or array.
*/
export function cloneWithShallow(obj: any, keys: string[]): any;
/**
* Merge all the properties of source into target.
*/
export function merge<T1, T2>(target: T1, source: T2, isNullOverride?: boolean, isMergeArrays?: boolean): T1 & T2;
/**
* Apply options to a copy of the defaults.
*/
export function applyToDefaults<T1, T2>(defaults: T1, options: T2, isNullOverride?: boolean): T1 & T2;
/**
* Apply options to a copy of the defaults.
*/
export function applyToDefaultsWithShallow<T1, T2>(defaults: T1, options: T2, keys?: string[]): T1 & T2;
/**
* Perform a deep comparison of the two values.
*/
export function deepEqual<T>(b: T, a: T, options?: any): T;
/**
* Remove duplicate items from Array.
*/
export function unique<T>(array: T[], key?: string): T[];
/**
* Convert an Array into an Object.
*/
export function mapToObject(array: any[], key?: string): any;
/**
* Find the common unique items in two arrays.
*/
export function intersect(array1: any[], array2: any[]): any;
/**
* Test if the reference value contains the provided values.
*/
export function contain(ref: any, values: any, options?: ContainOptions): boolean;
/**
* Flatten an array.
*/
export function flatten(array: any[], target?: any[]): any[];
/**
* Convert an object key chain string to reference.
*/
export function reach(obj: any, chain: any, options?: ReachOptions): any;
/**
* Replace string parameters ({name}) with their corresponding object key values.
*/
export function reachTemplate(obj: any, template: string, options?: ReachOptions): any;
/**
* Transform an existing object into a new one based on the supplied obj and transform map.
*/
export function transform(obj: any, transform: any, options?: ReachOptions): any;
/**
* Perform a shallow copy by copying the references of all the top level children.
*/
export function shallow(obj: any): any;
/**
* Convert an object to string. Any errors are caught and reported back in the form of the returned string.
*/
export function stringify(obj: any): string;
// Timer
/**
* A Timer object.
*/
export class Timer {
/** The number of milliseconds elapsed since the epoch. */
ts: number;
/** The time (ms) elapsed since the timer was created. */
elapsed(): number;
}
// Bench
/**
* Same as Timer, except ts stores the internal node clock.
*/
export class Bench {
/** The number of milliseconds on the node clock elapsed since the epoch. */
ts: number;
/** The time (ms) elapsed since the timer was created. */
elapsed(): number;
}
// Binary Encoding/Decoding
/**
* Encode value of string or buffer type in Base64 or URL encoding.
*/
export function base64urlEncode(value: string): string;
/**
* Decode string into Base64 or URL encoding.
*/
export function base64urlDecode(value: string): string;
// Escaping Characters
/**
* Escape html characters.
*/
export function escapeHtml(htmlString: string): string;
/**
* Escape attribute value for use in HTTP header.
*/
export function escapeHeaderAttribute(attribute: string): string;
/**
* Escape string for Regex construction.
*/
export function escapeRegex(regexString: string): string;
// Errors
/**
* Print message or throw error if condition fails.
*/
export function assert(condition: boolean, message: string | Error): void | Error;
/**
* Throw if process.env.NODE_ENV === 'test'. Else display most recent stack and exit process.
*/
export function abort(message: string | Error): void;
/**
* Display the trace stack.
*/
export function displayStack(slice?: any): string[];
/**
* Return a trace stack array.
*/
export function callStack(slice?: any): any[];
// Function
/**
* Wrap fn in process.nextTick.
*/
export function nextTick(fn: () => void): () => void;
/**
* Make sure fn is only run once.
*/
export function once(fn: () => void): () => void;
/**
* A simple no-op function.
*/
export function ignore(): void;
// Miscellaneous
/**
* path to prepend to a randomly generated file name.
*/
export function uniqueFilename(path: string, extension?: string): string;
/**
* Check value to see if it is an integer.
*/
export function isInteger(value: any): boolean;

View File

@@ -0,0 +1,29 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/hoek": [
"hapi__hoek"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__hoek-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,78 @@
import * as Iron from "@hapi/iron";
const options: Iron.SealOptions = {
encryption: {
saltBits: 256,
algorithm: 'aes-256-cbc',
iterations: 1,
minPasswordlength: 32
},
integrity: {
saltBits: 256,
algorithm: 'sha256',
iterations: 1,
minPasswordlength: 32
},
ttl: 0,
timestampSkewSec: 60,
localtimeOffsetMsec: 0
};
const algorithms: Iron.Algorithms = {
'aes-128-ctr': { keyBits: 128, ivBits: 128 },
'aes-256-cbc': { keyBits: 256, ivBits: 128 },
sha256: { keyBits: 256 }
};
const optionsGenerateKey: Iron.GenerateKeyOptions = {
saltBits: 256,
salt: '4d8nr9q384nr9q384nr93q8nruq9348run',
algorithm: 'aes-128-ctr',
iterations: 10000,
iv: 'sdfsdfsdfsdfscdrgercgesrcgsercg',
minPasswordlength: 32
};
const obj: object = {
a: 1,
b: 2,
c: [3, 4, 5],
d: {
e: 'f'
}
};
Iron.seal(obj, 'password', options)
.then((sealed: string) => {
console.log(sealed);
});
Iron.unseal('data', 'password', Iron.defaults)
.then((unsealed: object) => {
console.log(unsealed);
});
Iron.generateKey('password', options.encryption)
.then((value: Iron.Key) => {
console.log(value);
});
Iron.generateKey('password', optionsGenerateKey)
.then((value: Iron.Key) => {
console.log(value);
});
Iron.encrypt('password', Iron.defaults.encryption, 'data')
.then((obj: { data: Buffer, key: Iron.Key }) => {
console.log(obj);
});
Iron.decrypt('password', Iron.defaults.encryption, 'data')
.then((buffer: Buffer) => {
console.log(buffer);
});
Iron.hmacWithPassword('password', Iron.defaults.integrity, 'data')
.then((value: Iron.HMacResult) => {
console.log(value);
});

100
types/hapi__iron/index.d.ts vendored Normal file
View File

@@ -0,0 +1,100 @@
// Type definitions for @hapi/iron 5.1
// Project: https://github.com/hueniverse/iron
// Definitions by: Simon Schick <https://github.com/simonschick>
// Rafael Souza Fijalkowski <https://github.com/rafaelsouzaf>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="node" />
export interface SealOptionsSub {
/**
* the size of the salt (random buffer used to ensure that two identical objects will generate a different encrypted result.
*/
saltBits: number;
/**
* the algorithm used ('aes-256-cbc' for encryption and 'sha256' for integrity are the only two supported at this time).
*/
algorithm: keyof Algorithms;
/**
* the number of iterations used to derive a key from the password. Set to 1 by default. The number of ideal iterations
* to use is dependent on your application's performance requirements. More iterations means it takes longer to generate the key.
*/
iterations: number;
/**
* minimum password size
*/
minPasswordlength: number;
}
/**
* iron provides a few options for customizing the key derivation algorithm used to generate encryption and
* integrity verification keys as well as the algorithms and salt sizes used.
* For context [See docs](https://github.com/hueniverse/iron#options)
*/
export interface SealOptions {
/**
* defines the options used by the encryption process.
*/
encryption: SealOptionsSub;
/**
* defines the options used by the HMAC integrity verification process.
*/
integrity: SealOptionsSub;
/**
* sealed object lifetime in milliseconds where 0 means forever. Defaults to 0.
*/
ttl: number;
/**
* number of seconds of permitted clock skew for incoming expirations. Defaults to 60 seconds.
*/
timestampSkewSec: number;
/**
* local clock time offset, expressed in number of milliseconds (positive or negative). Defaults to 0.
*/
localtimeOffsetMsec: number;
}
export interface Algorithms {
'aes-128-ctr': {
keyBits: number;
ivBits: number;
};
'aes-256-cbc': {
keyBits: number;
ivBits: number;
};
'sha256': {
keyBits: number;
};
}
export interface GenerateKeyOptions extends Pick<SealOptionsSub, 'algorithm' | 'iterations' | 'minPasswordlength'> {
saltBits?: number;
salt?: string;
iv?: string;
}
export interface Key {
key: Buffer;
salt: string;
iv: string;
}
export interface HMacResult {
digest: string;
salt: string;
}
export const defaults: SealOptions;
export const algorithms: Algorithms;
export const macFormatVersion: string;
export const macPrefix: string;
export function generateKey(password: string, options: GenerateKeyOptions): Promise<Key>;
export function encrypt(password: string, options: GenerateKeyOptions, data: string): Promise<{ data: Buffer, key: Key }>;
export function decrypt(password: string, options: GenerateKeyOptions, data: string): Promise<Buffer>;
export function hmacWithPassword(password: string, options: GenerateKeyOptions, data: string): Promise<HMacResult>;
export function seal(obj: object, password: string, options: SealOptions): Promise<string>;
export function unseal(data: string, password: string, options: SealOptions): Promise<object>;

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/iron": [
"hapi__iron"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__iron-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

File diff suppressed because it is too large Load Diff

1340
types/hapi__joi/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/joi": [
"hapi__joi"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__joi-tests.ts"
]
}

View File

@@ -0,0 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
// All are TODOs
"no-empty-interface": false,
"no-self-import": false
}
}

28
types/hapi__mimos/index.d.ts vendored Normal file
View File

@@ -0,0 +1,28 @@
// Type definitions for @hapi/mimos 4.1
// Project: https://github.com/hapijs/mimos
// Definitions by: AJP <https://github.com/AJamesPhillips>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import { DataStructure as MimeDbDataStructure } from 'mime-db';
/**
*
* @see {@link https://github.com/hapijs/mimos#new-mimosoptions}
*/
export interface MimosOptions {
/**
* an object hash that is merged into the built in mime information specified here {@link https://github.com/jshttp/mime-db}. Each key value pair represents a single mime object. Each override value should follow this schema:
* * the key is the lower-cased correct mime-type. (Ex. "application/javascript").
* * the value should an object @see MimosOptionsValue
*/
override: {[index: string]: MimosOptionsValue};
}
export interface MimosOptionsValue extends MimeDbDataStructure {
/** specify the type value of result objects, defaults to key. See the example below for more clarification. */
type?: string;
/** method with signature function(mime) when this mime type is found in the database, this function will run. This allows you make customizations to mime based on developer criteria. */
predicate?: (mime: MimosOptionsValue) => MimosOptionsValue;
}

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/mimos": [
"hapi__mimos"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts"
]
}

View File

@@ -0,0 +1,80 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}

View File

@@ -0,0 +1,33 @@
declare var console: { log(...args: any[]): void };
import Podium = require('@hapi/podium');
const podiumObject = new Podium(); // new emitter
const podiumObject2 = new Podium('event1');// creates new event and calls registerEvent()
podiumObject.registerEvent('event1');
//with optional parameters
podiumObject.registerEvent({
name: 'event1',
shared: true
});
podiumObject.registerEvent('event1');
podiumObject.on('event1',function(update){ // Way 1
console.log('inside autonomous listener without name! data:', update);
});
const listener1 = function() { // normal function object
console.log('listener1 called');
}
podiumObject.on('event1',listener1); // Way 2
// podium.addListener(criteria, listener) Same as podium.on().
podiumObject.addListener('event1',listener1);
// podium.once(criteria, listener) Same as calling podium.on() with the count option set to 1. Whenever we call emit(), listener1 will get fired but also get removed, so that it won't get fired on call to emit().
podiumObject.once('event1',listener1);

187
types/hapi__podium/index.d.ts vendored Normal file
View File

@@ -0,0 +1,187 @@
// Type definitions for @hapi/podium 3.4
// Project: https://github.com/hapijs/podium
// Definitions by: AJP <https://github.com/AJamesPhillips>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/**
* Podium
* Node (semi) compatible event emitter with extra features.
* podium is an event emitter with support for tags, filters, channels, event update cloning, arguments spreading, and other features useful when building large scale applications. While node's native EventEmitter is strictly focused on maximum performance, it lacks many features that do not belong in the core implementation. podium is not restricted by node's performance requirement as it is designed for application layer needs where it's overhead is largely insignificant as implementing these features will have similar cost on top of the native emitter.
* @see {@link https://github.com/hapijs/podium}
*/
interface Podium {
/**
* Creates a new podium emitter
* @param events if present, the value is passed to podium.registerEvent().
*/
new(events?: Podium.Events[]): Podium;
new(events?: Podium.Events): Podium;
/**
* podium.registerEvent(events)
* Register the specified events and their optional configuration. Events must be registered before they can be emitted or subscribed to. This is done to detect event name mispelling and invalid event activities.
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumregistereventevents}
*/
registerEvent(events: Podium.Events[]): void;
registerEvent(events: Podium.Events): void;
/**
* podium.registerPodium(podiums)
* Registers another emitter as an event source for the current emitter (any event update emitted by the source emitter is passed to any subscriber of the current emitter)
* Note that any events registered with a source emitter are automatically added to the current emitter. If the events are already registered, they are left as-is.
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumregisterpodiumpodiums}
*/
registerPodium(podiums: Podium[]): void;
registerPodium(podiums: Podium): void;
/**
* podium.emit(criteria, data, [callback])
* Emits an event update to all the subscribed listeners
* @param criteria the event update criteria
* @param data the value emitted to the subscribers.
* @param callback an optional callback method invoked when all subscribers have been notified using the signature function()
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumemitcriteria-data-callback}
*/
emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any, callback?: (() => void)): void;
/**
* podium.on(criteria, listener)
* Subscribe a handler to an event
* @param criteria the subscription criteria
* @param listener the handler method set to receive event updates. The function signature depends on the block, spread, and tags options.
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener}
*/
on(criteria: string | Podium.Criteria, listener: Podium.Listener): void;
/**
* podium.addListener(criteria, listener)
* Same as podium.on()
* @param criteria the subscription criteria
* @param listener the handler method set to receive event updates. The function signature depends on the block, spread, and tags options.
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener}
*/
addListener(criteria: string | Podium.Criteria, listener: Podium.Listener): void;
/**
* podium.once(criteria, listener)
* Same as podium.on() with the count option set to 1.
* @param criteria the subscription criteria
* @param listener the handler method set to receive event updates. The function signature depends on the block, spread, and tags options.
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener}
*/
once(criteria: string | Podium.Criteria, listener: Podium.Listener): void;
/**
* podium.removeListener(name, listener)
* Removes all listeners subscribed to a given event name matching the provided listener method where:
* @param name the event name string.
* @param listener the function reference provided when subscribed.
* Returns a reference to the current emitter.
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener}
*/
removeListener(name: string, listener: Podium.Listener): Podium;
/**
* podium.removeAllListeners(name)
* Removes all listeners subscribed to a given event name
* @param name the event name string.
* Returns a reference to the current emitter.
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname}
*/
removeAllListeners(name: string): Podium;
/**
* podium.hasListeners(name)
* Returns whether an event has any listeners subscribed
* @param name the event name string.
* Returns true if the event name has any listeners, otherwise false.
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname}
*/
hasListeners(name: string): boolean;
}
declare namespace Podium {
/**
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumregistereventevents}
*/
export type Events = string | EventOptionsObject | Podium;
/**
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumregistereventevents}
*/
export interface EventOptionsObject {
/** the event name string (required). */
name: string;
/** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */
channels?: string | string[];
/** if true, the data object passed to podium.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). */
clone?: boolean;
/** if true, the data object passed to podium.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override 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 type). */
spread?: boolean;
/** if true and the criteria object passed to podium.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 the arguments list at the end (but before the callback argument if block is set). A configuration override can be set by each listener. Defaults to false. */
tags?: boolean;
/** 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 configuration is used. Defaults to false (a duplicate registration will throw an error). */
shared?: boolean;
}
/**
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener}
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumaddlistenercriteria-listener}
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncecriteria-listener}
*/
export interface CriteriaObject {
/** the event name string (required). */
name: string;
/** if true, the listener method receives an additional callback argument which must be called when the method completes. No other event will be emitted until the callback methods is called. The method signature is function(). If block is set to a positive integer, the value is used to set a timeout after which any pending events will be emitted, ignoring the eventual call to callback. Defaults to false (non blocking). */
block?: boolean | number;
/** 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 channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. */
channels?: string | string[];
/** if true, the data object passed to podium.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */
clone?: boolean;
/** 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 podium.once(). Defaults to no limit. */
count?: number;
/**
* the event tags (if present) to subscribe to which can be one of:
* * a tag string.
* * an array of tag strings.
* * an object with the following:
*/
filter?: string | string[] | CriteriaFilterOptionsObject;
/** if true, and the data object passed to podium.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). */
spread?: boolean;
/** if true and the criteria object passed to podium.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 the arguments list at the end (but before the callback argument if block is set). Defaults to the event registration option (which defaults to false). */
tags?: boolean;
/** the handler method set to receive event updates. The function signature depends on the block, spread, and tags options. */
listener?: Listener;
}
/**
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener}
*/
export interface CriteriaFilterOptionsObject {
/** a tag string or array of tag strings. */
tags?: string | string[];
/** if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). */
all?: boolean;
}
/**
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener}
*/
export type Criteria = string | CriteriaObject;
/**
* @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener}
*/
export interface Listener {
(data: any, tags?: Tags, callback?: () => void): void;
}
export type Tags = {[tag: string]: boolean};
}
declare var Podium: Podium;
export = Podium;

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/podium": [
"hapi__podium"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__podium-tests.ts"
]
}

View File

@@ -0,0 +1,80 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}

View File

@@ -0,0 +1,20 @@
// From: https://github.com/hapijs/shot#example
// Load modules
import { IncomingMessage, ServerResponse, createServer } from 'http';
import { inject } from '@hapi/shot';
// Declare internals
async function main() {
const dispatch = (req: IncomingMessage, res: ServerResponse) => {
const reply = 'Hello World';
res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length });
res.end(reply);
};
const server = createServer(dispatch);
console.log((await inject(dispatch, { method: 'get', url: '/', headers: { test: 'asd', test2: ['a', 'b'] } })).payload);
}

108
types/hapi__shot/index.d.ts vendored Normal file
View File

@@ -0,0 +1,108 @@
// Type definitions for @hapi/shot 4.1
// Project: https://github.com/hapijs/shot
// Definitions by: AJP <https://github.com/AJamesPhillips>
// Simon Schick <https://github.com/SimonSchick>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
import { ServerResponse } from "http";
import { Readable, Stream } from "stream";
/**
* Injects a fake request into an HTTP server.
* @param dispatchFunc listener function. The same as you would pass to Http.createServer when making a node HTTP server. @see IListener
* @param options request options object @see RequestOptions
* @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback}
*/
export function inject(dispatchFunc: Listener, options: RequestOptions): Promise<ResponseObject>;
/**
* Checks if given object obj is a Shot Request object.
* @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotisinjectionobj}
*/
export function isInjection(obj: any): boolean;
/**
* listener function. The same as you would pass to Http.createServer when making a node HTTP server. Has the signature function (req, res) where:
* * req - a simulated request object. Inherits from Stream.Readable.
* * res - a simulated response object. Inherits from node's Http.ServerResponse.
* @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback}
*/
export type Listener = (req: SimulatedRequestObject, res: SimulatedResponseObject) => void;
/**
* a simulated request object. Inherits from Stream.Readable.
* @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback}
*/
// tslint:disable-next-line:no-empty-interface
export interface SimulatedRequestObject extends Readable {}
/**
* a simulated response object. Inherits from node's Http.ServerResponse.
* @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback}
*/
// tslint:disable-next-line:no-empty-interface
export interface SimulatedResponseObject extends ServerResponse {}
/**
* @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback}
*/
export interface RequestOptions {
/** a string specifying the request URL. */
url: string;
/** a string specifying the HTTP request method, defaulting to 'GET'. */
method?: string;
/** a string specifying the HTTP HOST header value to be used if no header is provided, and the url does not include an authority component. Defaults to 'localhost'. */
authority?: string;
/** an optional object containing request headers. */
headers?: Headers;
/** an optional string specifying the client remote address. Defaults to '127.0.0.1'. */
remoteAddress?: string;
/** an optional request payload. Can be a string, Buffer, Stream or object. */
payload?: string | Buffer | Stream | object;
/** an object containing flags to simulate various conditions: */
simulate?: {
/** indicates whether the request will fire an end event. Defaults to undefined, meaning an end event will fire. */
end?: boolean;
/** indicates whether the request payload will be split into chunks. Defaults to `undefined`, meaning payload will not be chunked. */
split?: boolean;
/** whether the request will emit an error event. Defaults to undefined, meaning no error event will be emitted. If set to true, the emitted error will have a message of 'Simulated'. */
error?: boolean;
/** whether the request will emit a close event. Defaults to undefined, meaning no close event will be emitted. */
close?: boolean;
};
/** Optional flag to validate this options object. Defaults to true. */
validate?: boolean;
}
export interface Headers {
[header: string]: string | string[];
}
/**
* @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback}
*/
export interface ResponseObject {
/** an object containing the raw request and response objects where: */
raw: {
/** the simulated request object. */
req: SimulatedRequestObject;
/** the simulated response object. */
res: SimulatedResponseObject;
};
/** an object containing the response headers. */
headers: Headers;
/** the HTTP status code. */
statusCode: number;
/** the HTTP status message. */
statusMessage: string;
/** the payload as a UTF-8 encoded string. */
payload: string;
/** the raw payload as a Buffer. */
rawPayload: Buffer;
/** an object containing the response trailers. */
trailers: {[index: string]: any};
}

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"@hapi/shot": [
"hapi__shot"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi__shot-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -0,0 +1,15 @@
import Topo = require('@hapi/topo');
const morning = new Topo<string, 'breakfast' | 'prep' | 'dinner'>();
morning.add('Nap', { after: ['breakfast', 'prep'] }); // $ExpectType string[]
morning.add('Nap', { after: 'foo' }); // $ExpectError
morning.add(['Make toast', 'Pour juice'], { before: 'breakfast', group: 'prep' }); // $ExpectType string[]
morning.add('Eat breakfast', { group: 'breakfast' }); // $ExpectType string[]
morning.nodes; // $ExpectType string[]
const dinner = new Topo<string, 'breakfast' | 'prep' | 'dinner'>();
dinner.add('Eat dinner', { group: 'dinner', after: 'breakfast' }); // $ExpectType string[]
morning.merge(dinner);

Some files were not shown because too many files have changed in this diff Show More