From 1f26bbaecc5af29a7e8b2960e392ee0c23f9139f Mon Sep 17 00:00:00 2001 From: nnance Date: Sun, 12 Jun 2016 22:28:36 -0700 Subject: [PATCH 1/8] improve typings config --- .gitignore | 1 + tsconfig.json | 9 +- typings/globals/body-parser/index.d.ts | 133 - typings/globals/body-parser/typings.json | 8 - .../express-serve-static-core/index.d.ts | 1057 ------- .../express-serve-static-core/typings.json | 8 - typings/globals/express/index.d.ts | 41 - typings/globals/express/typings.json | 8 - typings/globals/hapi/index.d.ts | 2419 ----------------- typings/globals/hapi/typings.json | 8 - typings/globals/koa/index.d.ts | 126 - typings/globals/koa/typings.json | 8 - typings/globals/mime/index.d.ts | 15 - typings/globals/mime/typings.json | 8 - typings/globals/mocha/index.d.ts | 233 -- typings/globals/mocha/typings.json | 8 - typings/globals/node/index.d.ts | 2382 ---------------- typings/globals/node/typings.json | 8 - typings/globals/serve-static/index.d.ts | 79 - typings/globals/serve-static/typings.json | 8 - typings/index.d.ts | 11 - typings/modules/chai/index.d.ts | 547 ---- typings/modules/chai/typings.json | 21 - typings/modules/graphql/index.d.ts | 957 ------- typings/modules/graphql/typings.json | 11 - 25 files changed, 5 insertions(+), 8109 deletions(-) delete mode 100644 typings/globals/body-parser/index.d.ts delete mode 100644 typings/globals/body-parser/typings.json delete mode 100644 typings/globals/express-serve-static-core/index.d.ts delete mode 100644 typings/globals/express-serve-static-core/typings.json delete mode 100644 typings/globals/express/index.d.ts delete mode 100644 typings/globals/express/typings.json delete mode 100644 typings/globals/hapi/index.d.ts delete mode 100644 typings/globals/hapi/typings.json delete mode 100644 typings/globals/koa/index.d.ts delete mode 100644 typings/globals/koa/typings.json delete mode 100644 typings/globals/mime/index.d.ts delete mode 100644 typings/globals/mime/typings.json delete mode 100644 typings/globals/mocha/index.d.ts delete mode 100644 typings/globals/mocha/typings.json delete mode 100644 typings/globals/node/index.d.ts delete mode 100644 typings/globals/node/typings.json delete mode 100644 typings/globals/serve-static/index.d.ts delete mode 100644 typings/globals/serve-static/typings.json delete mode 100644 typings/index.d.ts delete mode 100644 typings/modules/chai/index.d.ts delete mode 100644 typings/modules/chai/typings.json delete mode 100644 typings/modules/graphql/index.d.ts delete mode 100644 typings/modules/graphql/typings.json diff --git a/.gitignore b/.gitignore index d9879887a..144e17745 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,7 @@ build/Release # Dependency directory node_modules +typings # Optional npm cache directory .npm diff --git a/tsconfig.json b/tsconfig.json index 1db12cb42..877ec8b84 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,9 +12,8 @@ "pretty": true, "removeComments": true }, - "files": [ - "typings/index.d.ts", - "src/core/runQuery.ts", - "src/test/tests.ts" - ] + "exclude": [ + "node_modules", + "dist" + ] } diff --git a/typings/globals/body-parser/index.d.ts b/typings/globals/body-parser/index.d.ts deleted file mode 100644 index 266b1c811..000000000 --- a/typings/globals/body-parser/index.d.ts +++ /dev/null @@ -1,133 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/body-parser/body-parser.d.ts -declare module "body-parser" { - import * as express from "express"; - - /** - * bodyParser: use individual json/urlencoded middlewares - * @deprecated - */ - - function bodyParser(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * only parse objects and arrays. (default: true) - */ - strict?: boolean; - /** - * passed to JSON.parse(). - */ - receiver?: (key: string, value: any) => any; - /** - * parse extended syntax with the qs module. (default: true) - */ - extended?: boolean; - }): express.RequestHandler; - - namespace bodyParser { - export function json(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'json') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * only parse objects and arrays. (default: true) - */ - strict?: boolean; - /** - * passed to JSON.parse(). - */ - receiver?: (key: string, value: any) => any; - }): express.RequestHandler; - - export function raw(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - }): express.RequestHandler; - - export function text(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * the default charset to parse as, if not specified in content-type. (default: 'utf-8') - */ - defaultCharset?: string; - }): express.RequestHandler; - - export function urlencoded(options: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * parse extended syntax with the qs module. - */ - extended: boolean; - }): express.RequestHandler; - } - - export = bodyParser; -} \ No newline at end of file diff --git a/typings/globals/body-parser/typings.json b/typings/globals/body-parser/typings.json deleted file mode 100644 index 253747209..000000000 --- a/typings/globals/body-parser/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/body-parser/body-parser.d.ts", - "raw": "registry:dt/body-parser#0.0.0+20160317120654", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/body-parser/body-parser.d.ts" - } -} diff --git a/typings/globals/express-serve-static-core/index.d.ts b/typings/globals/express-serve-static-core/index.d.ts deleted file mode 100644 index 77aa9a5bb..000000000 --- a/typings/globals/express-serve-static-core/index.d.ts +++ /dev/null @@ -1,1057 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/fb2e78984b7076eda628892770a4314d618ac0d7/express-serve-static-core/express-serve-static-core.d.ts -declare namespace Express { - - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/method-override/method-override.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } -} - -declare module "express-serve-static-core" { - import * as http from "http"; - - interface IRoute { - path: string; - stack: any; - all(...handler: RequestHandler[]): IRoute; - get(...handler: RequestHandler[]): IRoute; - post(...handler: RequestHandler[]): IRoute; - put(...handler: RequestHandler[]): IRoute; - delete(...handler: RequestHandler[]): IRoute; - patch(...handler: RequestHandler[]): IRoute; - options(...handler: RequestHandler[]): IRoute; - head(...handler: RequestHandler[]): IRoute; - } - - interface IRouterMatcher { - (name: string | RegExp, ...handlers: RequestHandler[]): T; - } - - interface IRouter extends RequestHandler { - /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ - param(name: string, handler: RequestParamHandler): T; - param(name: string, matcher: RegExp): T; - param(name: string, mapper: (param: any) => any): T; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - head: IRouterMatcher; - - route(path: string): IRoute; - - use(...handler: RequestHandler[]): T; - use(handler: ErrorRequestHandler | RequestHandler): T; - use(path: string, ...handler: RequestHandler[]): T; - use(path: string, handler: ErrorRequestHandler | RequestHandler): T; - use(path: string[], ...handler: RequestHandler[]): T; - use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandler[]): T; - use(path: RegExp, handler: ErrorRequestHandler): T; - use(path: string, router: Router): T; - } - - - export interface Router extends IRouter { } - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean; - } - - interface Errback { (err: Error): void; } - - interface Request extends http.ServerRequest, Express.Request { - - /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ - get(name: string): string; - - header(name: string): string; - - headers: { [key: string]: string; }; - - /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ - accepts(type: string): string; - - accepts(type: string[]): string; - - /** - * Returns the first accepted charset of the specified character sets, - * based on the request’s Accept-Charset HTTP header field. - * If none of the specified charsets is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param charset - */ - acceptsCharsets(charset?: string | string[]): string[]; - - /** - * Returns the first accepted encoding of the specified encodings, - * based on the request’s Accept-Encoding HTTP header field. - * If none of the specified encodings is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param encoding - */ - acceptsEncodings(encoding?: string | string[]): string[]; - - /** - * Returns the first accepted language of the specified languages, - * based on the request’s Accept-Language HTTP header field. - * If none of the specified languages is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * - * @param lang - */ - acceptsLanguages(lang?: string | string[]): string[]; - - /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ - range(size: number): any[]; - - /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ - accepted: MediaType[]; - - /** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ - param(name: string, defaultValue?: any): string; - - /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ - is(type: string): boolean; - - /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ - protocol: string; - - /** - * Short-hand for: - * - * req.protocol == 'https' - */ - secure: boolean; - - /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ - ip: string; - - /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ - ips: string[]; - - /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ - subdomains: string[]; - - /** - * Short-hand for `url.parse(req.url).pathname`. - */ - path: string; - - /** - * Parse the "Host" header field hostname. - */ - hostname: string; - - /** - * @deprecated Use hostname instead. - */ - host: string; - - /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ - fresh: boolean; - - /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ - stale: boolean; - - /** - * Check if the request was an _XMLHttpRequest_. - */ - xhr: boolean; - - //body: { username: string; password: string; remember: boolean; title: string; }; - body: any; - - //cookies: { string; remember: boolean; }; - cookies: any; - - method: string; - - params: any; - - user: any; - - authenticatedUser: any; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - query: any; - - route: any; - - signedCookies: any; - - originalUrl: string; - - url: string; - - baseUrl: string; - - app: Application; - } - - interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - interface Send { - (status: number, body?: any): Response; - (body: any): Response; - } - - interface Response extends http.ServerResponse, Express.Response { - /** - * Set status `code`. - * - * @param code - */ - status(code: number): Response; - - /** - * Set the response HTTP status code to `statusCode` and send its string representation as the response body. - * @link http://expressjs.com/4x/api.html#res.sendStatus - * - * Examples: - * - * res.sendStatus(200); // equivalent to res.status(200).send('OK') - * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') - * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') - * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') - * - * @param code - */ - sendStatus(code: number): Response; - - /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ - links(links: any): Response; - - /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - */ - send: Send; - - /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - */ - json: Send; - - /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - */ - jsonp: Send; - - /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ - sendFile(path: string): void; - sendFile(path: string, options: any): void; - sendFile(path: string, fn: Errback): void; - sendFile(path: string, options: any, fn: Errback): void; - - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, fn: Errback): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any, fn: Errback): void; - - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - */ - download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - contentType(type: string): Response; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - type(type: string): Response; - - /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ - format(obj: any): Response; - - /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ - attachment(filename?: string): Response; - - /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ - set(field: any): Response; - set(field: string, value?: string): Response; - - header(field: any): Response; - header(field: string, value?: string): Response; - - // Property indicating if HTTP headers has been sent for the response. - headersSent: boolean; - - /** - * Get value for header `field`. - * - * @param field - */ - get(field: string): string; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ - cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; - - /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ - location(url: string): Response; - - /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ - redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; - - /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(view: string, callback?: (err: Error, html: string) => void): void; - - locals: any; - - charset: string; - } - - interface NextFunction { - (err?: any): void; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; - } - - - interface Handler extends RequestHandler { } - - interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, param: any): any; - } - - interface Application extends IRouter, Express.Application { - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ - engine(ext: string, fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * app.set('foo', ['bar', 'baz']); - * app.get('foo'); - * // => ["bar", "baz"] - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set(setting: string, val: any): Application; - get: { - (name: string): any; // Getter - (name: string | RegExp, ...handlers: RequestHandler[]): Application; - }; - - /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ - path(): string; - - /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ - enabled(setting: string): boolean; - - /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ - disabled(setting: string): boolean; - - /** - * Enable `setting`. - * - * @param setting - */ - enable(setting: string): Application; - - /** - * Disable `setting`. - * - * @param setting - */ - disable(setting: string): Application; - - /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ - configure(fn: Function): Application; - configure(env0: string, fn: Function): Application; - configure(env0: string, env1: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ - render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; - - - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ - listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - - route(path: string): IRoute; - - router: string; - - settings: any; - - resource: any; - - map: any; - - locals: any; - - /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ - routes: any; - } - - interface Express extends Application { - /** - * Framework version. - */ - version: string; - - /** - * Expose mime. - */ - mime: string; - - (): Application; - - /** - * Create an express application. - */ - createApplication(): Application; - - createServer(): Application; - - application: any; - - request: Request; - - response: Response; - } - - interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; - } -} \ No newline at end of file diff --git a/typings/globals/express-serve-static-core/typings.json b/typings/globals/express-serve-static-core/typings.json deleted file mode 100644 index 8603ab296..000000000 --- a/typings/globals/express-serve-static-core/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/fb2e78984b7076eda628892770a4314d618ac0d7/express-serve-static-core/express-serve-static-core.d.ts", - "raw": "registry:dt/express-serve-static-core#0.0.0+20160322035842", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/fb2e78984b7076eda628892770a4314d618ac0d7/express-serve-static-core/express-serve-static-core.d.ts" - } -} diff --git a/typings/globals/express/index.d.ts b/typings/globals/express/index.d.ts deleted file mode 100644 index d43b8fb86..000000000 --- a/typings/globals/express/index.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/express/express.d.ts -declare module "express" { - import * as serveStatic from "serve-static"; - import * as core from "express-serve-static-core"; - - /** - * Creates an Express application. The express() function is a top-level function exported by the express module. - */ - function e(): core.Express; - - namespace e { - - /** - * This is the only built-in middleware function in Express. It serves static files and is based on serve-static. - */ - var static: typeof serveStatic; - - export function Router(options?: any): core.Router; - - interface Application extends core.Application { } - interface CookieOptions extends core.CookieOptions { } - interface Errback extends core.Errback { } - interface ErrorRequestHandler extends core.ErrorRequestHandler { } - interface Express extends core.Express { } - interface Handler extends core.Handler { } - interface IRoute extends core.IRoute { } - interface IRouter extends core.IRouter { } - interface IRouterMatcher extends core.IRouterMatcher { } - interface MediaType extends core.MediaType { } - interface NextFunction extends core.NextFunction { } - interface Request extends core.Request { } - interface RequestHandler extends core.RequestHandler { } - interface RequestParamHandler extends core.RequestParamHandler { } - export interface Response extends core.Response { } - interface Router extends core.Router { } - interface Send extends core.Send { } - } - - export = e; -} \ No newline at end of file diff --git a/typings/globals/express/typings.json b/typings/globals/express/typings.json deleted file mode 100644 index 152591ac5..000000000 --- a/typings/globals/express/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/express/express.d.ts", - "raw": "registry:dt/express#4.0.0+20160317120654", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/express/express.d.ts" - } -} diff --git a/typings/globals/hapi/index.d.ts b/typings/globals/hapi/index.d.ts deleted file mode 100644 index 358f4ef2a..000000000 --- a/typings/globals/hapi/index.d.ts +++ /dev/null @@ -1,2419 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/ccb4c316dcafde1bda8cd3aedbd2b95cbff20b47/hapi/hapi.d.ts -declare module "hapi" { - import http = require("http"); - import stream = require("stream"); - import Events = require("events"); - import url = require("url"); - - interface IDictionary { - [key: string]: T; - } - - interface IThenable { - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IThenable; - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IThenable; - } - - interface IPromise extends IThenable { - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IPromise; - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IPromise; - catch(onRejected?: (error: any) => U | IThenable): IPromise; - } - - export interface IHeaderOptions { - append?: boolean; - separator?: string; - override?: boolean; - duplicate?: boolean; - } - - /** Boom Module for errors. https://github.com/hapijs/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: */ - export interface IBoom extends Error { - /** if true, indicates this is a Boom object instance. */ - isBoom: boolean; - /** convenience bool indicating status code >= 500. */ - isServer: boolean; - /** the error message. */ - message: string; - /** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */ - output: { - /** the HTTP status code (typically 4xx or 5xx). */ - statusCode: number; - /** an object containing any HTTP headers where each key is a header name and value is the header content. */ - headers: IDictionary; - /** 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: { - /** the HTTP status code, derived from error.output.statusCode. */ - statusCode: number; - /** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ - error: string; - /** the error message derived from error.message. */ - message: string; - }; - }; - /** reformat()rebuilds error.output using the other object properties. */ - reformat(): void; - - } - - /** cache functionality via the "CatBox" module. */ - export interface ICatBoxCacheOptions { - /** a prototype function or catbox engine object. */ - engine: any; - /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */ - name?: string; - /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ - shared?: boolean; - } - - /** Any connections configuration server defaults can be included to override and customize the individual connection. */ - export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { - /** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/ - host?: string; - /** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/ - address?: string; - /** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/ - port?: string | number; - /** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/ - uri?: string; - /** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/ - listener?: any; - /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ - autoListen?: boolean; - /** caching headers configuration: */ - cache?: { - /** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */ - statuses: number[]; - }; - /** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/ - labels?: string | string[]; - /** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */ - tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object; - - } - - export interface IConnectionConfigurationServerDefaults { - /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ - app?: any; - /** connection load limits configuration where: */ - load?: { - /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxHeapUsedBytes: number; - /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxRssBytes: number; - /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxEventLoopDelay: number; - }; - /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ - plugins?: any; - /** controls how incoming request URIs are matched against the routing table: */ - router?: { - /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ - isCaseSensitive: boolean; - /** removes trailing slashes on incoming paths. Defaults to false. */ - stripTrailingSlash: boolean; - }; - /** a route options object used to set the default configuration for every route. */ - routes?: IRouteAdditionalConfigurationOptions; - state?: IServerState; - } - - /** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/ - export interface IServerOptions { - /** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ - app?: any; - /** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: - a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). - a configuration object with the following options: - enginea prototype function or catbox engine object. - namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. - sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. - other options passed to the catbox strategy used. - an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */ - cache?: string | ICatBoxCacheOptions | Array | any; - /** sets the default connections configuration which can be overridden by each connection where: */ - connections?: IConnectionConfigurationServerDefaults; - /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/ - debug?: boolean | { - /** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ - log: string[]; - /** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/ - request: string[]; - }; - /** file system related settings*/ - files?: { - /** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/ - etagsCacheMaxSize?: number; - }; - /** process load monitoring*/ - load?: { - /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/ - sampleInterval?: number; - }; - - /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ - mime?: any; - /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ - minimal?: boolean; - /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ - plugins?: IDictionary; - - } - - export interface IServerViewCompile { - (template: string, options: any): void; - (template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void; - } - - export interface IServerViewsAdditionalOptions { - /** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/ - path?: string; - /**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path). - */ - partialsPath?: string; - /**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/ - helpersPath?: string; - /**relativeTo - a base path used as prefix for path and partialsPath.No default.*/ - relativeTo?: string; - - /**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/ - layout?: boolean | string; - /**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/ - layoutPath?: string; - /**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/ - layoutKeywork?: string; - /**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/ - encoding?: string; - /**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/ - isCached?: boolean; - /**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/ - allowAbsolutePaths?: boolean; - /**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/ - allowInsecureAccess?: boolean; - /**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/ - compileOptions?: any; - /**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/ - runtimeOptions?: any; - /**contentType - the content type of the engine results.Defaults to 'text/html'.*/ - contentType?: string; - /**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/ - compileMode?: string; - /**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/ - context?: any; - } - - export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions { - /**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings. - * If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/ - module: { - compile?(template: any, options: any): (context: any, options: any) => void; - compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void; - }; - } - - /**Initializes the server views manager - var Hapi = require('hapi'); - var server = new Hapi.Server(); - - server.views({ - engines: { - html: require('handlebars'), - jade: require('jade') - }, - path: '/static/templates' - }); - When server.views() is called within a plugin, the views manager is only available to plugins methods. - */ - export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions { - /** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/ - engines: IDictionary | IServerViewsEnginesOptions; - /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ - defaultExtension?: string; - } - - /** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - resultan optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ - export interface IReply { - (err: Error, - result?: string | number | boolean | Buffer | stream.Stream | IPromise | T, - /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ - credentialData?: any): IBoom; - /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ - (result: string | number | boolean | Buffer | stream.Stream | IPromise | T): Response; - - /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. - * The data argument is only used for passing back authentication data and is ignored elsewhere. */ - continue(credentialData?: any): void; - - /** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */ - file(/** the file path. */ - path: string, - /** optional settings: */ - options?: { - /** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ - filename?: string; - /** specifies whether to include the 'Content-Disposition' header with the response. Available values: - false - header is not included. This is the default value. - 'attachment' - 'inline'*/ - mode?: boolean | string; - /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ - lookupCompressed: boolean; - }): void; - /** Concludes the handler activity by returning control over to the router with a templatized view response. - the response flow control rules apply. */ - view(/** the template filename and path, relative to the templates path configured via the server views manager. */ - template: string, - /** optional object used by the template to render context-specific result. Defaults to no context {}. */ - context?: {}, - /** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */ - options?: any): Response; - /** Sets a header on the response */ - header(name: string, value: string, options?: IHeaderOptions): Response; - - /** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed - The response flow control rules do not apply. */ - close(options?: { - /** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */ - end?: boolean; - }): void; - /** Proxies the request to an upstream endpoint. - the response flow control rules do not apply. */ - - proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */ - options: IProxyHandlerConfig): void; - /** Redirects the client to the specified uri. Same as calling reply().redirect(uri). - he response flow control rules apply. */ - redirect(uri: string): ResponseRedirect; - - /** Replies with the specified response */ - response(result: any): Response; - - /** Sets a cookie on the response */ - state(name: string, value: any, options?: any): void; - - /** Clears a cookie on the response */ - unstate(name: string, options?: any): void; - } - - export interface ISessionHandler { - (request: Request, reply: IReply): void; - } - export interface IRequestHandler { - (request: Request): T; - } - - - export interface IFailAction { - (source: string, error: any, next: () => void): void - } - /** generates a reverse proxy handler */ - export interface IProxyHandlerConfig { - /** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/ - host?: string; - /** the upstream service port. */ - port?: number; - /** The protocol to use when making a request to the proxied host: - 'http' - 'https'*/ - protocol?: string; - /** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/ - uri?: string; - /** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/ - passThrough?: boolean; - /** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/ - localStatePassThrough?: boolean; - /**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/ - acceptEncoding?: boolean; - /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/ - rejectUnauthorized?: boolean; - /**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/ - xforward?: boolean; - /** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/ - redirects?: boolean | number; - /**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/ - timeout?: number; - /** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where: - request - is the incoming request object. - callback - is function(err, uri, headers) where: - err - internal error condition. - uri - the absolute proxy URI. - headers - optional object where each key is an HTTP request header and the value is the header content.*/ - mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void; - /** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/ - onResponse?: (err: any, - res: http.ServerResponse, - req: Request, - reply: IReply, - settings: IProxyHandlerConfig, - ttl: number) => void; - /** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/ - ttl?: number; - /** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */ - agent?: http.Agent; - /** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/ - maxSockets?: boolean | number; - } - /** TODO: fill in joi definition */ - export interface IJoi { - - } - /** a validation function using the signature function(value, options, next) */ - export interface IValidationFunction { - - (/** the object containing the path parameters. */ - value: any, - /** the server validation options. */ - options: any, - /** the callback function called when validation is completed. */ - next: (err: any, value: any) => void): void; - } - /** a custom error handler function with the signature 'function(request, reply, source, error)` */ - export interface IRouteFailFunction { - /** a custom error handler function with the signature 'function(request, reply, source, error)` */ - (/** - the [request object]. */ - request: Request, - /** the continuation reply interface. */ - reply: IReply, - /** the source of the invalid field (e.g. 'path', 'query', 'payload'). */ - source: string, - /** the error object prepared for the client response (including the validation function error under error.data). */ - error: any): void; - } - - /** Each route can be customize to change the default behavior of the request lifecycle using the following options: */ - export interface IRouteAdditionalConfigurationOptions { - /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ - app?: any; - /** authentication configuration.Value can be: false to disable authentication if a default strategy is set. - a string with the name of an authentication strategy registered with server.auth.strategy(). - an object */ - auth?: boolean | string | - { - /** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values: - 'required'authentication is required. - 'optional'authentication is optional (must be valid if present). - 'try'same as 'optional' but allows for invalid authentication. */ - mode?: string; - /** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */ - strategies?: string | Array; - /** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values: - falseno payload authentication.This is the default value. - 'required'payload authentication required.This is the default value when the scheme sets options.payload to true. - 'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */ - payload?: string; - /** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */ - scope?: string | Array | boolean; - /** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values: - anythe authentication can be on behalf of a user or application.This is the default value. - userthe authentication must be on behalf of a user. - appthe authentication must be on behalf of an application. */ - entity?: string; - /** - * an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming - * request and access is granted if at least one rule matches. Each rule object must include at least one of: - */ - access?: IRouteAdditionalConfigurationAuthAccess | IRouteAdditionalConfigurationAuthAccess[]; - }; - /** an object passed back to the provided handler (via this) when called. */ - bind?: any; - /** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */ - cache?: { - /** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are: - fault'no privacy flag.This is the default setting. - 'public'mark the response as suitable for public caching. - 'private'mark the response as suitable only for private caching. */ - privacy: string; - /** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */ - expiresIn: number; - /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */ - expiresAt: string; - }; - /** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */ - cors?: { - /** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */ - origin?: Array; - /** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */ - matchOrigin?: boolean; - /** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */ - isOriginExposed?: boolean; - /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */ - maxAge?: number; - /** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */ - headers?: string[]; - /** a strings array of additional headers to headers.Use this to keep the default headers in place. */ - additionalHeaders?: string[]; - /** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */ - methods?: string[]; - /** a strings array of additional methods to methods.Use this to keep the default methods in place. */ - additionalMethods?: string[]; - /** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ - exposedHeaders?: string[]; - /** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */ - additionalExposedHeaders?: string[]; - /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */ - credentials?: boolean; - /** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */ - override?: boolean; - }; - /** defines the behavior for serving static resources using the built-in route handlers for files and directories: */ - files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */ - relativeTo: string; - }; - - /** an alternative location for the route handler option. */ - handler?: ISessionHandler | string | IRouteHandlerConfig; - /** an optional unique identifier used to look up the route using server.lookup(). */ - id?: number; - /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ - json?: { - /** the replacer function or array.Defaults to no action. */ - replacer?: Function | string[]; - /** number of spaces to indent nested object keys.Defaults to no indentation. */ - space?: number | string; - /** string suffix added after conversion to JSON string.Defaults to no suffix. */ - suffix?: string; - }; - /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */ - jsonp?: string; - /** determines how the request payload is processed: */ - payload?: { - /** the type of payload representation requested. The value must be one of: - 'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used. - 'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. - 'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */ - output?: string; - /** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: - 'application/json' - 'application/x-www-form-urlencoded' - 'application/octet-stream' - 'text/ *' - 'multipart/form-data' */ - parse?: string | boolean; - /** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ - allow?: string | string[]; - /** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */ - override?: string; - /** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */ - maxBytes?: number; - /** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */ - timeout?: number; - /** the directory used for writing file uploads.Defaults to os.tmpDir(). */ - uploads?: string; - /** determines how to handle payload parsing errors. Allowed values are: - 'error'return a Bad Request (400) error response. This is the default value. - 'log'report the error but continue processing the request. - 'ignore'take no action and continue processing the request. */ - failAction?: string; - }; - /** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */ - plugins?: IDictionary; - /** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */ - pre?: any[]; - /** validation rules for the outgoing response payload (response body).Can only validate object response: */ - response?: { - /** the default HTTP status code when the payload is empty. Value can be 200 or 204. - Note that a 200 status code is converted to a 204 only at the time or response transmission - (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ - emptyStatusCode?: number; - /** the default response object validation rules (for all non-error responses) expressed as one of: - true - any payload allowed (no validation performed). This is the default. - false - no payload allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - value - the object containing the response object. - options - the server validation options. - next(err) - the callback function called when validation is completed. */ - schema?: boolean | any; - /** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */ - status?: { [statusCode: number]: boolean | any }; - /** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */ - sample?: number; - /** defines what to do when a response fails validation.Options are: - errorreturn an Internal Server Error (500) error response.This is the default value. - loglog the error but send the response. */ - failAction?: string; - /** if true, applies the validation rule changes to the response.Defaults to false. */ - modify?: boolean; - /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options?: any; - }; - /** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */ - security?: boolean | { - /** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */ - hsts?: boolean | number | { - /** the max- age portion of the header, as a number.Default is 15768000. */ - maxAge?: number; - /** a boolean specifying whether to add the includeSubdomains flag to the header. */ - includeSubdomains?: boolean; - /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ - preload?: boolean; - }; - /** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */ - xframe?: { - /** either 'deny', 'sameorigin', or 'allow-from' */ - rule: string; - /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ - source: string; - }; - /** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */ - xss?: boolean; - /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */ - noOpen?: boolean; - /** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */ - noSniff?: boolean; - }; - /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */ - state?: { - /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */ - parse: boolean; - /** determines how to handle cookie parsing errors.Allowed values are: - 'error'return a Bad Request (400) error response.This is the default value. - 'log'report the error but continue processing the request. - 'ignore'take no action. */ - failAction: string; - }; - /** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */ - validate?: { - /** validation rules for incoming request headers.Values allowed: - * trueany headers allowed (no validation performed).This is the default. - falseno headers allowed (this will cause all valid HTTP requests to fail). - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the request headers. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. - */ - headers?: boolean | IJoi | IValidationFunction; - - - /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: - trueany path parameters allowed (no validation performed).This is the default. - falseno path variables allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the path parameters. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - params?: boolean | IJoi | IValidationFunction; - /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: - trueany query parameters allowed (no validation performed).This is the default. - falseno query parameters allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the query parameters. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - query?: boolean | IJoi | IValidationFunction; - /** validation rules for an incoming request payload (request body).Values allowed: - trueany payload allowed (no validation performed).This is the default. - falseno payload allowed. - a Joi validation object. - a validation function using the signature function(value, options, next) where: - valuethe object containing the payload object. - optionsthe server validation options. - next(err, value)the callback function called when validation is completed. */ - payload?: boolean | IJoi | IValidationFunction; - /** an optional object with error fields copied into every validation error response. */ - errorFields?: any; - /** determines how to handle invalid requests.Allowed values are: - 'error'return a Bad Request (400) error response.This is the default value. - 'log'log the error but continue processing the request. - 'ignore'take no action. - OR a custom error handler function with the signature 'function(request, reply, source, error)` where: - requestthe request object. - replythe continuation reply interface. - sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). - errorthe error object prepared for the client response (including the validation function error under error.data). */ - failAction?: string | IRouteFailFunction; - /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options?: any; - }; - /** define timeouts for processing durations: */ - timeout?: { - /** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */ - server: boolean | number; - /** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */ - socket: boolean | number; - }; - - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route description used for generating documentation (string). - */ - description?: string; - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route notes used for generating documentation (string or array of strings). - */ - notes?: string | string[]; - /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - *route tags used for generating documentation (array of strings). - */ - tags?: string[] - } - - /** - * specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches - */ - export interface IRouteAdditionalConfigurationAuthAccess { - /** - * the application scope required to access the route. Value can be a scope string or an array of scope strings. - * The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. - * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, - * that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' - * scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties - * on the request object (query and params} to populate a dynamic scope by using {} characters around the property name, - * such as 'user-{params.id}'. Defaults to false (no scope requirements). - */ - scope?: string | Array | boolean; - /** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: - * any - the authentication can be on behalf of a user or application. This is the default value. - * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. - * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. - */ - entity?: string; - } - - /** server.realm http://hapijs.com/api#serverrealm - The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), - the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). - Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. - The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). - exports.register = function (server, options, next) { - console.log(server.realm.modifiers.route.prefix); - return next(); - }; - */ - export interface IServerRealm { - /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */ - modifiers: { - /** routes preferences: */ - route: { - /** - the route path prefix used by any calls to server.route() from the server. */ - prefix: string; - /** the route virtual host settings used by any calls to server.route() from the server. */ - vhost: string; - }; - - }; - /** the active plugin name (empty string if at the server root). */ - plugin: string; - /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ - plugins: IDictionary; - /** settings overrides */ - settings: { - files: { - relativeTo: any; - }; - bind: any; - } - } - /** server.state(name, [options]) http://hapijs.com/api#serverstatename-options - HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ - export interface IServerState { - /** - the cookie name string. */name: string; - - /** - are the optional cookie settings: */options: { - /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number; - /** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean; - /** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean - /** - the path scope.Defaults to null (no path).*/path: any; - /** - the domain scope.Defaults to null (no domain). */domain: any; - /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: - request - the request object. - next - the continuation function using the function(err, value) signature.*/ - autoValue: (request: Request, next: (err: any, value: any) => void) => void; - /** - encoding performs on the provided value before serialization. Options are: - 'none' - no encoding. When used, the cookie value must be a string. This is the default value. - 'base64' - string value is encoded using Base64. - 'base64json' - object value is JSON-stringified than encoded using Base64. - 'form' - object value is encoded using the x-www-form-urlencoded method. - 'iron' - Encrypts and sign the value using iron.*/ - encoding: string; - /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: { - /** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any; - /** - password used for HMAC key generation.*/password: string; - }; - /** - password used for 'iron' encoding.*/password: string; - /** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any; - /** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean; - /** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean; - /** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean; - /** - overrides the default proxy localStatePassThrough setting.*/passThrough: any; - }; - } - - export interface IFileHandlerConfig { - /** a path string or function as described above.*/ - path: string; - /** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/ - filename?: string; - /**- specifies whether to include the 'Content-Disposition' header with the response. Available values: - false - header is not included. This is the default value. - 'attachment' - 'inline'*/ - mode?: boolean | string; - /** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/ - lookupCompressed: boolean; - } - - /**http://hapijs.com/api#route-handler - Built-in handlers - - The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/ - export interface IRouteHandlerConfig { - /** generates a static file endpoint for serving a single file. file can be set to: - a relative or absolute file path string (relative paths are resolved based on the route files configuration). - a function with the signature function(request) which returns the relative or absolute file path. - an object with the following options */ - file?: string | IRequestHandler | IFileHandlerConfig; - /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: - path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: - a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. - an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). - a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. - index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. - listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. - showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. - redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. - lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. - defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ - directory?: { - path: string | Array | IRequestHandler | IRequestHandler>; - index?: boolean | string | string[]; - listing?: boolean; - showHidden?: boolean; - redirectToSlash?: boolean; - lookupCompressed?: boolean; - defaultExtension?: string; - }; - proxy?: IProxyHandlerConfig; - view?: string | { - template: string; - context: { - payload: any; - params: any; - query: any; - pre: any; - } - }; - config?: { - handler: any; - bind: any; - app: any; - plugins: { - [name: string]: any; - }; - pre: Array<() => void>; - validate: { - headers: any; - params: any; - query: any; - payload: any; - errorFields?: any; - failAction?: string | IFailAction; - }; - payload: { - output: { - data: any; - stream: any; - file: any; - }; - parse?: any; - allow?: string | Array; - override?: string; - maxBytes?: number; - uploads?: number; - failAction?: string; - }; - response: { - schema: any; - sample: number; - failAction: string; - }; - cache: { - privacy: string; - expiresIn: number; - expiresAt: number; - }; - auth: string | boolean | { - mode: string; - strategies: Array; - payload?: boolean | string; - tos?: boolean | string; - scope?: string | Array; - entity: string; - }; - cors?: boolean; - jsonp?: string; - description?: string; - notes?: string | Array; - tags?: Array; - }; - } - /** Route configuration - The route configuration object*/ - export interface IRouteConfiguration { - /** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/ - path: string; - /** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). - * Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/ - method: string | string[]; - /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ - vhost?: string; - /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ - handler: ISessionHandler | string | IRouteHandlerConfig; - /** - additional route options.*/ - config?: IRouteAdditionalConfigurationOptions; - } - /** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */ - export interface IRoute { - - - /** the route HTTP method. */ - method: string; - /** the route path. */ - path: string; - /** the route vhost option if configured. */ - vhost?: string | Array; - /** the [active realm] associated with the route.*/ - realm: IServerRealm; - /** the [route options] object with all defaults applied. */ - settings: IRouteAdditionalConfigurationOptions; - } - - export interface IServerAuthScheme { - /** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where: - request - the request object. - reply - the reply interface the authentication method must call when done authenticating the request where: - reply(err, response, result) - is called if authentication failed where: - err - any authentication error. - response - any authentication response action such as redirection. Ignored if err is present, otherwise required. - result - an object containing: - credentials - the authenticated credentials. - artifacts - optional authentication artifacts. - reply.continue(result) - is called if authentication succeeded where: - result - same object as result above. - When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. - .If the err returned by the reply() method includes a message, no additional strategies will be attempted. - If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var scheme = function (server, options) { - return { - authenticate: function (request, reply) { - var req = request.raw.req; - var authorization = req.headers.authorization; - if (!authorization) { - return reply(Boom.unauthorized(null, 'Custom')); - } - return reply(null, { credentials: { user: 'john' } }); - } - }; - }; - server.auth.scheme('custom', scheme);*/ - authenticate(request: Request, reply: IReply): void; - /** payload(request, reply) - optional function called to authenticate the request payload where: - request - the request object. - reply(err, response) - is called if authentication failed where: - err - any authentication error. - response - any authentication response action such as redirection. Ignored if err is present, otherwise required. - reply.continue() - is called if payload authentication succeeded. - When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ - payload?(request: Request, reply: IReply): void; - /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: - request - the request object. - reply(err, response) - is called if an error occurred where: - err - any authentication error. - response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. - reply.continue() - is called if the operation succeeded.*/ - response?(request: Request, reply: IReply): void; - /** an optional object */ - options?: { - /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ - payload: boolean; - } - } - - /**the response object where: - statusCode - the HTTP status code. - headers - an object containing the headers set. - payload - the response payload string. - rawPayload - the raw response payload buffer. - raw - an object with the injection request and response objects: - req - the simulated node request object. - res - the simulated node response object. - result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). - request - the request object.*/ - export interface IServerInjectResponse { - statusCode: number; - headers: IDictionary; - payload: string; - rawPayload: Buffer; - raw: { - req: http.ClientRequest; - res: http.ServerResponse - }; - result: string; - request: Request; - } - - export interface IServerInject { - (options: string | IServerInjectOptions, callback: (res: IServerInjectResponse) => void): void; - (options: string | IServerInjectOptions): IPromise; - } - - export interface IServerInjectOptions { - /** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/ - method: string; - /** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/ - url: string; - /** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/ - headers?: IDictionary; - /** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/ - payload?: string | {} | Buffer; - /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/ - credentials?: any; - /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/ - artifacts?: any; - /** sets the initial value of request.app*/ - app?: any; - /** sets the initial value of request.plugins*/ - plugins?: any; - /** allows access to routes with config.isInternal set to true. Defaults to false.*/ - allowInternals?: boolean; - /** sets the remote address for the incoming connection.*/ - remoteAddress?: boolean; - /**object with options used to simulate client request stream conditions for testing: - error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. - close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. - end - if false, does not end the stream. Defaults to true.*/ - simulate?: { - error: boolean; - close: boolean; - end: boolean; - }; - } - - - /** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. - The return value is an array where each item is an object containing: - info - the connection.info the connection the table was generated for. - labels - the connection labels. - table - an array of routes where each route contains: - settings - the route config with defaults applied. - method - the HTTP method in lower case. - path - the route path.*/ - export interface IConnectionTable { - info: any; - labels: any; - table: IRoute[]; - } - - export interface ICookieSettings { - /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ - ttl?: number; - /** - sets the 'Secure' flag.Defaults to false.*/ - isSecure?: boolean; - /** - sets the 'HttpOnly' flag.Defaults to false.*/ - isHttpOnly?: boolean; - /** - the path scope.Defaults to null (no path).*/ - path?: string; - /** - the domain scope.Defaults to null (no domain).*/ - domain?: any; - /** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where: - request - the request object. - next - the continuation function using the function(err, value) signature.*/ - autoValue?: (request: Request, next: (err: any, value: any) => void) => void; - /** - encoding performs on the provided value before serialization.Options are: - 'none' - no encoding.When used, the cookie value must be a string.This is the default value. - 'base64' - string value is encoded using Base64. - 'base64json' - object value is JSON- stringified than encoded using Base64. - 'form' - object value is encoded using the x- www - form - urlencoded method. */ - encoding?: string; - /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are: - integrity - algorithm options.Defaults to require('iron').defaults.integrity. - password - password used for HMAC key generation. */ - sign?: { integrity: any; password: string; } - password?: string; - iron?: any; - ignoreErrors?: boolean; - clearInvalid?: boolean; - strictHeader?: boolean; - passThrough?: any; - } - - /** method - the method function with the signature is one of: - function(arg1, arg2, ..., argn, next) where: - arg1, arg2, etc. - the method function arguments. - next - the function called when the method is done with the signature function(err, result, ttl) where: - err - error response if the method failed. - result - the return value. - ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. - function(arg1, arg2, ..., argn) where: - arg1, arg2, etc. - the method function arguments. - the callback option is set to false. - the method must returns a value (result, Error, or a promise) or throw an Error.*/ - export interface IServerMethod { - //(): void; - //(next: (err: any, result: any, ttl: number) => void): void; - //(arg1: any): void; - //(arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void; - //(arg1: any, arg2: any): void; - (...args: any[]): void; - - } - /** options - optional configuration: - bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. - cache - the same cache configuration used in server.cache(). - callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. - generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ - export interface IServerMethodOptions { - bind?: any; - cache?: ICatBoxCacheOptions; - callback?: boolean; - generateKey?(args: any[]): string; - } - /** Request object - - The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. - Request events - - The request object supports the following events: - - 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - 'finish' - emitted when the request payload finished reading. The event method signature is function (). - 'disconnect' - emitted when a request errors or aborts unexpectedly. - var Crypto = require('crypto'); - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onRequest', function (request, reply) { - - var hash = Crypto.createHash('sha1'); - request.on('peek', function (chunk) { - - hash.update(chunk); - }); - - request.once('finish', function () { - - console.log(hash.digest('hex')); - }); - - request.once('disconnect', function () { - - console.error('request aborted'); - }); - - return reply.continue(); - });*/ - export class Request extends Events.EventEmitter { - /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ - app: any; - /** authentication information*/ - auth: { - /** true is the request has been successfully authenticated, otherwise false.*/ - isAuthenticated: boolean; - /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/ - credentials: any; - /** an artifact object received from the authentication strategy and used in authentication-related actions.*/ - artifacts: any; - /** the route authentication mode.*/ - mode: any; - /** the authentication error is failed and mode set to 'try'.*/ - error: any; - }; - /** the connection used by this request*/ - connection: ServerConnection; - /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/ - domain: any; - /** the raw request headers (references request.raw.headers).*/ - headers: IDictionary; - /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ - id: number; - /** request information */ - info: { - /** the request preferred encoding. */ - acceptEncoding: string; - /** if CORS is enabled for the route, contains the following: */ - cors: { - isOriginMatch: boolean; /** true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */ - }; - /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ - host: string; - /** the hostname part of the 'Host' header (e.g. 'example.com').*/ - hostname: string; - /** request reception timestamp. */ - received: number; - /** content of the HTTP 'Referrer' (or 'Referer') header. */ - referrer: string; - /** remote client IP address. */ - remoteAddress: string; - /** remote client port. */ - remotePort: number; - /** request response timestamp (0 is not responded yet). */ - responded: number; - }; - /** the request method in lower case (e.g. 'get', 'post'). */ - method: string; - /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ - mime: string; - /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/ - orig: { - params: any; - query: any; - payload: any; - }; - /** an object where each key is a path parameter name with matching value as described in Path parameters.*/ - params: IDictionary; - /** an array containing all the path params values in the order they appeared in the path.*/ - paramsArray: string[]; - /** the request URI's path component. */ - path: string; - /** the request payload based on the route payload.output and payload.parse settings.*/ - payload: stream.Readable | Buffer | any; - /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/ - plugins: any; - /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/ - pre: IDictionary; - /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/ - response: Response; - /**preResponses - same as pre but represented as the response object created by the pre method.*/ - preResponses: any; - /**an object containing the query parameters.*/ - query: any; - /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ - raw: { - req: http.ClientRequest; - res: http.ServerResponse; - }; - /** the route public interface.*/ - route: IRoute; - /** the server object. */ - server: Server; - /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ - state: any; - /** complex object contining details on the url */ - url: { - /** null when i tested */ - auth: any; - /** null when i tested */ - hash: any; - /** null when i tested */ - host: any; - /** null when i tested */ - hostname: any; - href: string; - path: string; - /** path without search*/ - pathname: string; - /** null when i tested */ - port: any; - /** null when i tested */ - protocol: any; - /** querystring parameters*/ - query: IDictionary; - /** querystring parameters as a string*/ - search: string; - /** null when i tested */ - slashes: any; - }; - - /** request.setUrl(url) - - Available only in 'onRequest' extension methods. - - Changes the request URI before the router begins processing the request where: - - url - the new request path value. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onRequest', function (request, reply) { - - // Change all requests to '/test' - request.setUrl('/test'); - return reply.continue(); - });*/ - setUrl(url: string | url.Url): void; - /** request.setMethod(method) - - Available only in 'onRequest' extension methods. - - Changes the request method before the router begins processing the request where: - - method - is the request HTTP method (e.g. 'GET'). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onRequest', function (request, reply) { - - // Change all requests to 'GET' - request.setMethod('GET'); - return reply.continue(); - });*/ - setMethod(method: string): void; - - /** request.log(tags, [data, [timestamp]]) - - Always available. - - Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: - - data - an optional message string or object with the application data being logged. - timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). - Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. - - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.on('request', function (request, event, tags) { - - if (tags.error) { - console.log(event); - } - }); - - var handler = function (request, reply) { - - request.log(['test', 'error'], 'Test event'); - return reply(); - }; - */ - log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ - tags: string | string[], - /** an optional message string or object with the application data being logged.*/ - data?: any, - /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ - timestamp?: number): void; - - /** request.getLog([tags], [internal]) - - Always available. - - Returns an array containing the events matching any of the tags specified (logical OR) - request.getLog(); - request.getLog('error'); - request.getLog(['error', 'auth']); - request.getLog(['error'], true); - request.getLog(false);*/ - - getLog(/** is a single tag string or array of tag strings. If no tags specified, returns all events.*/ - tags?: string, - /** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/ - internal?: boolean): string[]; - - /** request.tail([name]) - - Available until immediately after the 'response' event is emitted. - - Adds a request tail which has to complete before the request lifecycle is complete where: - - name - an optional tail name used for logging purposes. - Returns a tail function which must be called when the tail activity is completed. - - Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). - - When all tails completed, the server emits a 'tail' event. - - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - var get = function (request, reply) { - - var dbTail = request.tail('write to database'); - - db.save('key', 'value', function () { - - dbTail(); - }); - - return reply('Success!'); - }; - - server.route({ method: 'GET', path: '/', handler: get }); - - server.on('tail', function (request) { - - console.log('Request completed including db activity'); - });*/ - tail(/** an optional tail name used for logging purposes.*/ - name?: string): Function; - } - /** Response events - - The response object supports the following events: - - 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). - var Crypto = require('crypto'); - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - - server.ext('onPreResponse', function (request, reply) { - - var response = request.response; - if (response.isBoom) { - return reply(); - } - - var hash = Crypto.createHash('sha1'); - response.on('peek', function (chunk) { - - hash.update(chunk); - }); - - response.once('finish', function () { - - console.log(hash.digest('hex')); - }); - - return reply.continue(); - });*/ - export class Response extends Events.EventEmitter { - isBoom: boolean; - /** the HTTP response status code. Defaults to 200 (except for errors).*/ - statusCode: number; - /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/ - headers: IDictionary; - /** the value provided using the reply interface.*/ - source: any; - /** a string indicating the type of source with available values: - 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). - 'buffer' - a Buffer. - 'view' - a view generated with reply.view(). - 'file' - a file generated with reply.file() of via the directory handler. - 'stream' - a Stream. - 'promise' - a Promise object. */ - variety: string; - /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/ - app: any; - /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ - plugins: any; - /** settings - response handling flags: - charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. - encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. - passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. - stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding. - ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. - varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/ - settings: { - charset: string; - encoding: string; - passThrough: boolean; - stringify: any; - ttl: number; - varyEtag: boolean; - } - - /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: - length - the header value. Must match the actual payload size.*/ - bytes(length: number): Response; - - /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ - charset(charset: string): Response; - - /** sets the HTTP status code where: - statusCode - the HTTP status code.*/ - code(statusCode: number): Response; - - /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ - created(uri: string): Response; - - - /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ - encoding(encoding: string): Response; - - /** etag(tag, options) - sets the representation entity tag where: - tag - the entity tag string without the double-quote. - options - optional settings where: - weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. - vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ - etag(tag: string, options: { - weak: boolean; vary: boolean; - }): Response; - - /**header(name, value, options) - sets an HTTP header where: - name - the header name. - value - the header value. - options - optional settings where: - append - if true, the value is appended to any existing header value using separator. Defaults to false. - separator - string used as separator when appending to an exiting value. Defaults to ','. - override - if false, the header value is not set if an existing value present. Defaults to true.*/ - header(name: string, value: string, options?: IHeaderOptions): Response; - - /** hold() - puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. */ - hold(): Response; - - /** location(uri) - sets the HTTP 'Location' header where: - uri - an absolute or relative URI used as the 'Location' header value.*/ - location(uri: string): Response; - - /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: - uri - an absolute or relative URI used to redirect the client to another resource. */ - redirect(uri: string): Response; - - /** replacer(method) - sets the JSON.stringify() replacer argument where: - method - the replacer function or array. Defaults to none.*/ - replacer(method: Function | Array): Response; - - /** spaces(count) - sets the JSON.stringify() space argument where: - count - the number of spaces to indent nested object keys. Defaults to no indentation. */ - spaces(count: number): Response; - - /**state(name, value, [options]) - sets an HTTP cookie where: - name - the cookie name. - value - the cookie value. If no encoding is defined, must be a string. - options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ - state(name: string, value: string, options?: any): Response; - - /** send() - resume the response which will be transmitted in the next tick. Available only after response.hold() is called and until response.send() is invoked once. */ - send(): void; - - /** sets a string suffix when the response is process via JSON.stringify().*/ - suffix(suffix: string): void; - - /** overrides the default route cache expiration rule for this response instance where: - msec - the time-to-live value in milliseconds.*/ - ttl(msec: number): void; - - /** type(mimeType) - sets the HTTP 'Content-Type' header where: - mimeType - is the mime type. Should only be used to override the built-in default for each response type. */ - type(mimeType: string): Response; - - /** clears the HTTP cookie by setting an expired value where: - name - the cookie name. - options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ - unstate(name: string, options?: { [key: string]: string }): Response; - - /** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: - header - the HTTP request header name.*/ - vary(header: string): void; - } - /** When using the redirect() method, the response object provides these additional methods */ - export class ResponseRedirect extends Response { - /** sets the status code to 302 or 307 (based on the rewritable() setting) where: - isTemporary - if false, sets status to permanent. Defaults to true.*/ - temporary(isTemporary: boolean): void; - - /** sets the status code to 301 or 308 (based on the rewritable() setting) where: - isPermanent - if true, sets status to temporary. Defaults to false. */ - permanent(isPermanent: boolean): void; - - /** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: - isRewritable - if false, sets to non-rewritable. Defaults to true. - Permanent Temporary - Rewritable 301 302(1) - Non-rewritable 308(2) 307 - Notes: 1. Default value. 2. Proposed code, not supported by all clients. */ - rewritable(isRewritable: boolean): void; - } - /** info about a server connection */ - export interface IServerConnectionInfo { - /** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/ - id: string; - /** - the connection creation timestamp.*/ - created: number; - /** - the connection start timestamp (0 when stopped).*/ - started: number; - /** the connection port based on the following rules: - the configured port value before the server has been started. - the actual port assigned when no port is configured or set to 0 after the server has been started.*/ - port: number; - - /** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/ - host: string; - /** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/ - address: string; - /** - the protocol used: - 'http' - HTTP. - 'https' - HTTPS. - 'socket' - UNIX domain socket or Windows named pipe.*/ - protocol: string; - /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/ - uri: string; - } - /** - * undocumented. The connection object constructed after calling server.connection(); - * can be accessed via server.connections; or request.connection; - */ - export class ServerConnection extends Events.EventEmitter { - domain: any; - _events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function }; - _eventsCount: number; - settings: IServerConnectionOptions; - server: Server; - /** ex: "tcp" */ - type: string; - _started: boolean; - /** dictionary of sockets */ - _connections: { [ip_port: string]: any }; - _onConnection: Function; - registrations: any; - _extensions: any; - _requestCounter: { value: number; min: number; max: number }; - _load: any; - states: { - settings: any; cookies: any; names: any[] - }; - auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; api: any; }; - _router: any; - MSPluginsCollection: any; - applicationCache: any; - addEventListener: any; - info: IServerConnectionInfo; - } - - /** Server http://hapijs.com/api#server - rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). - Server events - The server object inherits from Events.EventEmitter and emits the following events: - 'log' - events logged with server.log() and server events generated internally by the framework. - 'start' - emitted when the server is started using server.start(). - 'stop' - emitted when the server is stopped using server.stop(). - 'request' - events generated by request.log(). Does not include any internally generated events. - 'request-internal' - request events generated internally by the framework (multiple events per request). - 'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request. - 'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request. - 'tail' - emitted when a request finished processing, including any registered tails. Single event per request. - Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events. - MORE EVENTS HERE: http://hapijs.com/api#server-events*/ - export class Server extends Events.EventEmitter { - - constructor(options?: IServerOptions); - - /** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. - var Hapi = require('hapi'); - server = new Hapi.Server(); - server.app.key = 'value'; - var handler = function (request, reply) { - return reply(request.server.app.key); - }; */ - app: any; - /** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. - var server = new Hapi.Server(); - server.connection({ port: 80, labels: 'a' }); - server.connection({ port: 8080, labels: 'b' }); - // server.connections.length === 2 - var a = server.select('a'); - // a.connections.length === 1*/ - connections: Array; - /** When the server contains exactly one connection, info is an object containing information about the sole connection. - * When the server contains more than one connection, each server.connections array member provides its own connection.info. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // server.info.port === 80 - server.connection({ port: 8080 }); - // server.info === null - // server.connections[1].info.port === 8080 - */ - info: IServerConnectionInfo; - /** An object containing the process load metrics (when load.sampleInterval is enabled): - rss - RSS memory usage. - var Hapi = require('hapi'); - var server = new Hapi.Server({ load: { sampleInterval: 1000 } }); - console.log(server.load.rss);*/ - load: { - /** - event loop delay milliseconds.*/ - eventLoopDelay: number; - /** - V8 heap usage.*/ - heapUsed: number; - }; - /** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. - When the server contains more than one connection, each server.connections array member provides its own connection.listener. - var Hapi = require('hapi'); - var SocketIO = require('socket.io'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var io = SocketIO.listen(server.listener); - io.sockets.on('connection', function(socket) { - socket.emit({ msg: 'welcome' }); - });*/ - listener: http.Server; - - /** server.methods - An object providing access to the server methods where each server method name is an object property. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.method('add', function (a, b, next) { - return next(null, a + b); - }); - server.methods.add(1, 2, function (err, result) { - // result === 3 - });*/ - methods: IDictionary; - - /** server.mime - Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. - var Hapi = require('hapi'); - var options = { - mime: { - override: { - 'node/module': { - source: 'steve', - compressible: false, - extensions: ['node', 'module', 'npm'], - type: 'node/module' - } - } - } - }; - var server = new Hapi.Server(options); - // server.mime.path('code.js').type === 'application/javascript' - // server.mime.path('file.npm').type === 'node/module'*/ - mime: any; - /**server.plugins - An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. - exports.register = function (server, options, next) { - server.expose('key', 'value'); - // server.plugins.example.key === 'value' - return next(); - }; - exports.register.attributes = { - name: 'example' - };*/ - plugins: IDictionary; - /** server.realm - The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. - modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: - route - routes preferences: - prefix - the route path prefix used by any calls to server.route() from the server. - vhost - the route virtual host settings used by any calls to server.route() from the server. - plugin - the active plugin name (empty string if at the server root). - plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. - settings - settings overrides: - files.relativeTo - bind - The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]). - exports.register = function (server, options, next) { - console.log(server.realm.modifiers.route.prefix); - return next(); - };*/ - realm: IServerRealm; - - /** server.root - The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/ - root: Server; - /** server.settings - The server configuration object after defaults applied. - var Hapi = require('hapi'); - var server = new Hapi.Server({ - app: { - key: 'value' - } - }); - // server.settings.app === { key: 'value' }*/ - settings: IServerOptions; - - /** server.version - The hapi module version number. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - // server.version === '8.0.0'*/ - version: string; - - /** server.after(method, [dependencies]) - Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where: - after - the method with signature function(plugin, next) where: - server - server object the after() method was called on. - next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: - err - internal error which is returned back via the server.start() callback. - dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.after(function () { - // Perform some pre-start logic - }); - server.start(function (err) { - // After method already executed - }); - server.auth.default(options)*/ - after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void; - - auth: { - /** server.auth.api - An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function. - When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object. - const server = new Hapi.Server(); - server.connection({ port: 80 }); - const scheme = function (server, options) { - return { - api: { - settings: { - x: 5 - } - }, - authenticate: function (request, reply) { - const req = request.raw.req; - const authorization = req.headers.authorization; - if (!authorization) { - return reply(Boom.unauthorized(null, 'Custom')); - } - return reply.continue({ credentials: { user: 'john' } }); - } - }; - }; - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - console.log(server.auth.api.default.settings.x); // 5 - */ - api: { - [index: string]: any; - } - /** server.auth.default(options) - Sets a default strategy which is applied to every route where: - options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options. - The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior. - The default auth strategy configuration can be accessed via connection.auth.settings.default. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - server.auth.default('default'); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - return reply(request.auth.credentials.user); - } - });*/ - default(options: string): void; - default(options: { strategy: string }): void; - default(options: { strategies: string[] }): void; - /** server.auth.scheme(name, scheme) - Registers an authentication scheme where: - name - the scheme name. - scheme - the method implementing the scheme with signature function(server, options) where: - server - a reference to the server object the scheme is added to. - options - optional scheme settings used to instantiate a strategy.*/ - scheme(name: string, - /** When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. - n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. - server = new Hapi.Server(); - server.connection({ port: 80 }); - scheme = function (server, options) { - urn { - authenticate: function (request, reply) { - req = request.raw.req; - var authorization = req.headers.authorization; - if (!authorization) { - return reply(Boom.unauthorized(null, 'Custom')); - } - urn reply(null, { credentials: { user: 'john' } }); - } - }; - }; - */ - scheme: (server: Server, options: any) => IServerAuthScheme): void; - - /** server.auth.strategy(name, scheme, [mode], [options]) - Registers an authentication strategy where: - name - the strategy name. - scheme - the scheme name (must be previously registered using server.auth.scheme()). - mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false. - options - scheme options based on the scheme requirements. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - server.route({ - method: 'GET', - path: '/', - config: { - auth: 'default', - handler: function (request, reply) { - return reply(request.auth.credentials.user); - } - } - });*/ - strategy(name: string, scheme: any, mode?: boolean | string, options?: any): void; - - /** server.auth.test(strategy, request, next) - Tests a request against an authentication strategy where: - strategy - the strategy name registered with server.auth.strategy(). - request - the request object. - next - the callback function with signature function(err, credentials) where: - err - the error if authentication failed. - credentials - the authentication credentials object if authentication was successful. - Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.auth.scheme('custom', scheme); - server.auth.strategy('default', 'custom'); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - request.server.auth.test('default', request, function (err, credentials) { - if (err) { - return reply({ status: false }); - } - return reply({ status: true, user: credentials.name }); - }); - } - });*/ - test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void; - }; - - /** server.bind(context) - Sets a global context used as the default bind object when adding a route or an extension where: - context - the object used to bind this in handler and extension methods. - When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. - var handler = function (request, reply) { - return reply(this.message); - }; - exports.register = function (server, options, next) { - var bind = { - message: 'hello' - }; - server.bind(bind); - server.route({ method: 'GET', path: '/', handler: handler }); - return next(); - };*/ - bind(context: any): void; - - - /** server.cache(options) - Provisions a cache segment within the server cache facility where: - options - catbox policy configuration where: - expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. - expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. - 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: - id - the id string or object provided to the get() method. - 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. - 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. - staleTimeout - number of milliseconds to wait before checking if an item is stale. - 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. - cache - the cache name configured in 'server.cache`. Defaults to the default cache. - segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin. - shared - if true, allows multiple cache provisions to share the same segment. Default to false. - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); - cache.set('norway', { capital: 'oslo' }, null, function (err) { - cache.get('norway', function (err, value, cached, log) { - // value === { capital: 'oslo' }; - }); - });*/ - cache(options: ICatBoxCacheOptions): void; - - /** server.connection([options]) - Adds an incoming server connection - Returns a server object with the new connection selected. - Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()). - Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); - var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] }); - // server.connections.length === 2 - // web.connections.length === 1 - // admin.connections.length === 1 */ - connection(options: IServerConnectionOptions): Server; - - /** server.decorate(type, property, method, [options]) - Extends various framework interfaces with custom methods where: - type - the interface being decorated. Supported types: - 'reply' - adds methods to the reply interface. - 'server' - adds methods to the Server object. - property - the object decoration key name. - method - the extension function. - options - if the type is 'request', supports the following optional settings: - 'apply' - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. - Note that decorations apply to the entire server and all its connections regardless of current selection. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.decorate('reply', 'success', function () { - return this.response({ status: 'ok' }); - }); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - return reply.success(); - } - });*/ - decorate(type: string, property: string, method: Function, options?: { apply: boolean }): void; - - /** server.dependency(dependencies, [after]) - Used within a plugin to declares a required dependency on other plugins where: - dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies. - after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: - server - the server the dependency() method was called on. - next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: - err - internal error condition, which is returned back via the server.start() callback. - exports.register = function (server, options, next) { - server.dependency('yar', after); - return next(); - }; - var after = function (server, next) { - // Additional plugin registration logic - return next(); - };*/ - dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void; - - - /** server.expose(key, value) - Used within a plugin to expose a property via server.plugins[name] where: - key - the key assigned (server.plugins[name][key]). - value - the value assigned. - exports.register = function (server, options, next) { - server.expose('util', function () { console.log('something'); }); - return next(); - };*/ - expose(key: string, value: any): void; - - /** server.expose(obj) - Merges a deep copy of an object into to the existing content of server.plugins[name] where: - obj - the object merged into the exposed properties container. - exports.register = function (server, options, next) { - server.expose({ util: function () { console.log('something'); } }); - return next(); - };*/ - expose(obj: any): void; - - /** server.ext(event, method, [options]) - Registers an extension function in one of the available extension points where: - event - the event name. - method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where: - request - the request object. NOTE: Access the Response via request.response - reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. - this - the object provided via options.bind or the current active context set with server.bind(). - options - an optional object with the following: - before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - bind - a context object passed back to the provided method (via this) when called. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.ext('onRequest', function (request, reply) { - // Change all requests to '/test' - request.setUrl('/test'); - return reply.continue(); - }); - var handler = function (request, reply) { - return reply({ status: 'ok' }); - }; - server.route({ method: 'GET', path: '/test', handler: handler }); - server.start(); - // All requests will get routed to '/test'*/ - ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - - /** server.handler(name, method) - Registers a new handler type to be used in routes where: - name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type. - method - the function used to generate the route handler using the signature function(route, options) where: - route - the route public interface object. - options - the configuration object provided in the handler config. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ host: 'localhost', port: 8000 }); - // Defines new handler for routes on this server - server.handler('test', function (route, options) { - return function (request, reply) { - return reply('new handler: ' + options.msg); - } - }); - server.route({ - method: 'GET', - path: '/', - handler: { test: { msg: 'test' } } - }); - server.start(); - The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ host: 'localhost', port: 8000 }); - var handler = function (route, options) { - return function (request, reply) { - return reply('new handler: ' + options.msg); - } - }; - // Change the default payload processing for this handler - handler.defaults = { - payload: { - output: 'stream', - parse: false - } - }; - server.handler('test', handler);*/ - handler(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void; - - /** server.initialize([callback]) - Initializes the server (starts the caches, finalizes plugin registration) but does not start listening - on the connection ports, where: - - `callback` - the callback method when server initialization is completed or failed with the signature - `function(err)` where: - - `err` - any initialization error condition. - - If no `callback` is provided, a `Promise` object is returned. - - Note that if the method fails and the callback includes an error, the server is considered to be in - an undefined state and should be shut down. In most cases it would be impossible to fully recover as - the various plugins, caches, and other event listeners will get confused by repeated attempts to - start the server or make assumptions about the healthy state of the environment. It is recommended - to assert that no error has been returned after calling `initialize()` to abort the process when the - server fails to start properly. If you must try to resume after an error, call `server.stop()` - first to reset the server state. - */ - initialize(callback?: (error: any) => void): IPromise; - - /** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. - Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. - Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties - * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - var handler = function (request, reply) { - return reply('Success!'); - }; - server.route({ method: 'GET', path: '/', handler: handler }); - server.inject('/', function (res) { - console.log(res.result); - }); - */ - inject: IServerInject; - - /** server.log(tags, [data, [timestamp]]) - Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: - tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. - data - an optional message string or object with the application data being logged. - timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.on('log', function (event, tags) { - if (tags.error) { - console.log(event); - } - }); - server.log(['test', 'error'], 'Test event');*/ - log(tags: string | string[], data?: string | any, timestamp?: number): void; - - /**server.lookup(id) - When the server contains exactly one connection, looks up a route configuration where: - id - the route identifier as set in the route options. - returns the route public interface object if found, otherwise null. - var server = new Hapi.Server(); - server.connection(); - server.route({ - method: 'GET', - path: '/', - config: { - handler: function (request, reply) { return reply(); }, - id: 'root' - } - }); - var route = server.lookup('root'); - When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/ - lookup(id: string): IRoute; - - /** server.match(method, path, [host]) - When the server contains exactly one connection, looks up a route configuration where: - method - the HTTP method (e.g. 'GET', 'POST'). - path - the requested path (must begin with '/'). - host - optional hostname (to match against routes with vhost). - returns the route public interface object if found, otherwise null. - var server = new Hapi.Server(); - server.connection(); - server.route({ - method: 'GET', - path: '/', - config: { - handler: function (request, reply) { return reply(); }, - id: 'root' - } - }); - var route = server.match('get', '/'); - When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/ - match(method: string, path: string, host?: string): IRoute; - - - /** server.method(name, method, [options]) - Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. - Methods are registered via server.method(name, method, [options]) - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // Simple arguments - var add = function (a, b, next) { - return next(null, a + b); - }; - server.method('sum', add, { cache: { expiresIn: 2000 } }); - server.methods.sum(4, 5, function (err, result) { - console.log(result); - }); - // Object argument - var addArray = function (array, next) { - var sum = 0; - array.forEach(function (item) { - sum += item; - }); - return next(null, sum); - }; - server.method('sumObj', addArray, { - cache: { expiresIn: 2000 }, - generateKey: function (array) { - return array.join(','); - } - }); - server.methods.sumObj([5, 6], function (err, result) { - console.log(result); - }); - // Synchronous method with cache - var addSync = function (a, b) { - return a + b; - }; - server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false }); - server.methods.sumSync(4, 5, function (err, result) { - console.log(result); - }); */ - method(/** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/ - name: string, - method: IServerMethod, - options?: IServerMethodOptions): void; - - - /**server.method(methods) - Registers a server method function as described in server.method() using a configuration object where: - methods - an object or an array of objects where each one contains: - name - the method name. - method - the method function. - options - optional settings. - var add = function (a, b, next) { - next(null, a + b); - }; - server.method({ - name: 'sum', - method: add, - options: { - cache: { - expiresIn: 2000 - } - } - });*/ - method(methods: { - name: string; method: IServerMethod; options?: IServerMethodOptions - } | Array<{ - name: string; method: IServerMethod; options?: IServerMethodOptions - }>): void; - - /**server.path(relativeTo) - Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: - relativeTo - the path prefix added to any relative file path starting with '.'. - Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. - exports.register = function (server, options, next) { - server.path(__dirname + '../static'); - server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); - next(); - };*/ - path(relativeTo: string): void; - - - /** - * server.register(plugins, [options], callback) - * Registers a plugin where: - * plugins - an object or array of objects where each one is either: - * a plugin registration function. - * an object with the following: - * register - the plugin registration function. - * options - optional options passed to the registration function when called. - * options - optional registration options (different from the options passed to the registration function): - * select - a string or array of string labels used to pre-select connections for plugin registration. - * routes - modifiers applied to each route added by the plugin: - * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. - * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. - * callback - the callback function with signature function(err) where: - * err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. - * - * If no callback is provided, a Promise object is returned. - */ - register(plugins: any | any[], options: { - select: string | string[]; - routes: { - prefix: string; vhost?: string | string[] - }; - }, callback: (err: any) => void): void; - register(plugins: any | any[], options: { - select: string | string[]; - routes: { - prefix: string; vhost?: string | string[] - }; - }): IPromise; - - register(plugins: any | any[], callback: (err: any) => void): void; - register(plugins: any | any[]): IPromise; - - /**server.render(template, context, [options], callback) - Utilizes the server views manager to render a template where: - template - the template filename and path, relative to the views manager templates path (path or relativeTo). - context - optional object used by the template to render context-specific result. Defaults to no context ({}). - options - optional object used to override the views manager configuration. - callback - the callback function with signature function (err, rendered, config) where: - err - the rendering error if any. - rendered - the result view string. - config - the configuration used to render the template. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.views({ - engines: { html: require('handlebars') }, - path: __dirname + '/templates' - }); - var context = { - title: 'Views Example', - message: 'Hello, World' - }; - server.render('hello', context, function (err, rendered, config) { - console.log(rendered); - });*/ - render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void; - - /** server.route(options) - Adds a connection route where: - options - a route configuration object or an array of configuration objects. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } }); - server.route([ - { method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } }, - { method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } } - ]);*/ - route(options: IRouteConfiguration): void; - route(options: IRouteConfiguration[]): void; - - /**server.select(labels) - Selects a subset of the server's connections where: - labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. - Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, labels: ['a'] }); - server.connection({ port: 8080, labels: ['b'] }); - server.connection({ port: 8081, labels: ['c'] }); - server.connection({ port: 8082, labels: ['c','d'] }); - var a = server.select('a'); // The server with port 80 - var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080 - var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */ - select(labels: string | string[]): Server | Server[]; - - /** server.start([callback]) - Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where: - callback - optional callback when server startup is completed or failed with the signature function(err) where: - err - any startup error condition. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.start(function (err) { - console.log('Server started at: ' + server.info.uri); - });*/ - start(callback?: (err: any) => void): IPromise; - - /** server.state(name, [options]) - HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions - State defaults can be modified via the server connections.routes.state configuration option. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - // Set cookie definition - server.state('session', { - ttl: 24 * 60 * 60 * 1000, // One day - isSecure: true, - path: '/', - encoding: 'base64json' - }); - // Set state in route handler - var handler = function (request, reply) { - var session = request.state.session; - if (!session) { - session = { user: 'joe' }; - } - session.last = Date.now(); - return reply('Success').state('session', session); - }; - Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags: - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.on('request-internal', function (request, event, tags) { - if (tags.error && tags.state) { - console.error(event); - } - }); */ - state(name: string, options?: ICookieSettings): void; - - /** server.stop([options], [callback]) - Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: - options - optional object with: - timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). - callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80 }); - server.stop({ timeout: 60 * 1000 }, function () { - console.log('Server stopped'); - });*/ - stop(options?: { timeout: number }, callback?: () => void): IPromise; - - /**server.table([host]) - Returns a copy of the routing table where: - host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. - The return value is an array where each item is an object containing: - info - the connection.info the connection the table was generated for. - labels - the connection labels. - table - an array of routes where each route contains: - settings - the route config with defaults applied. - method - the HTTP method in lower case. - path - the route path. - Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, host: 'example.com' }); - server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); - var table = server.table(); - When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection: - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.connection({ port: 80, host: 'example.com' }); - server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); - var table = server.connections[0].table(); - //[ - // { - // method: 'get', - // path: '/example', - // settings: { ... } - // } - //] - */ - table(host?: any): IConnectionTable; - - /**server.views(options) - Initializes the server views manager - var Hapi = require('hapi'); - var server = new Hapi.Server(); - server.views({ - engines: { - html: require('handlebars'), - jade: require('jade') - }, - path: '/static/templates' - }); - When server.views() is called within a plugin, the views manager is only available to plugins methods.*/ - views(options: IServerViewsConfiguration): void; - - } -} \ No newline at end of file diff --git a/typings/globals/hapi/typings.json b/typings/globals/hapi/typings.json deleted file mode 100644 index b9fdb3895..000000000 --- a/typings/globals/hapi/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/ccb4c316dcafde1bda8cd3aedbd2b95cbff20b47/hapi/hapi.d.ts", - "raw": "registry:dt/hapi#13.0.0+20160521152637", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/ccb4c316dcafde1bda8cd3aedbd2b95cbff20b47/hapi/hapi.d.ts" - } -} diff --git a/typings/globals/koa/index.d.ts b/typings/globals/koa/index.d.ts deleted file mode 100644 index 1806e3a28..000000000 --- a/typings/globals/koa/index.d.ts +++ /dev/null @@ -1,126 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/koa/koa.d.ts -declare module "koa" { - import { EventEmitter } from "events"; - import * as http from "http"; - import * as net from "net"; - - namespace Koa { - export interface Context extends Request, Response { - body?: any; - request?: Request; - response?: Response; - originalUrl?: string; - state?: any; - name?: string; - cookies?: any; - writable?: Boolean; - respond?: Boolean; - app?: Koa; - req?: http.IncomingMessage; - res?: http.ServerResponse; - onerror(err: any): void; - toJSON(): any; - inspect(): any; - throw(code?: any, message?: any): void; - assert(): void; - } - - export interface Request { - _querycache?: string; - app?: Koa; - req?: http.IncomingMessage; - res?: http.ServerResponse; - response?: Response; - ctx?: Context; - headers?: any; - header?: any; - method?: string; - length?: any; - url?: string; - origin?: string; - originalUrl?: string; - href?: string; - path?: string; - querystring?: string; - query?: any; - search?: string; - idempotent?: Boolean; - socket?: net.Socket; - protocol?: string; - host?: string; - hostname?: string; - fresh?: Boolean; - stale?: Boolean; - charset?: string; - secure?: Boolean; - ips?: Array; - ip?: string; - subdomains?: Array; - accept?: any; - type?: string; - accepts?: () => any; - acceptsEncodings?: () => any; - acceptsCharsets?: () => any; - acceptsLanguages?: () => any; - is?: (types: any) => any; - toJSON?: () => any; - inspect?: () => any; - get?: (field: string) => string; - } - - export interface Response { - _body?: any; - _explicitStatus?: Boolean; - app?: Koa; - res?: http.ServerResponse; - req?: http.IncomingMessage; - ctx?: Context; - request?: Request; - socket?: net.Socket; - header?: any; - headers?: any; - status?: number; - message?: string; - type?: string; - body?: any; - length?: any; - headerSent?: Boolean; - lastModified?: Date; - etag?: string; - writable?: Boolean; - is?: (types: any) => any; - redirect?: (url: string, alt: string) => void; - attachment?: (filename?: string) => void; - vary?: (field: string) => void; - get?: (field: string) => string; - set?: (field: any, val: any) => void; - remove?: (field: string) => void; - append?: (field: string, val: any) => void; - toJSON?: () => any; - inspect?: () => any; - } - } - - class Koa extends EventEmitter { - keys: Array; - subdomainOffset: number; - proxy: Boolean; - server: http.Server; - env: string; - context: Koa.Context; - request: Koa.Request; - response: Koa.Response; - silent: Boolean; - constructor(); - use(middleware: (ctx: Koa.Context, next: Function) => any): Koa; - callback(): (req: http.IncomingMessage, res: http.ServerResponse) => void; - listen(port: number, callback?: Function): http.Server; - toJSON(): any; - inspect(): any; - onerror(err: any): void; - } - - namespace Koa {} - export = Koa; -} \ No newline at end of file diff --git a/typings/globals/koa/typings.json b/typings/globals/koa/typings.json deleted file mode 100644 index 343f52cab..000000000 --- a/typings/globals/koa/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/koa/koa.d.ts", - "raw": "registry:dt/koa#2.0.0+20160317120654", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/koa/koa.d.ts" - } -} diff --git a/typings/globals/mime/index.d.ts b/typings/globals/mime/index.d.ts deleted file mode 100644 index bccc6f9bb..000000000 --- a/typings/globals/mime/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/mime/mime.d.ts -declare module "mime" { - export function lookup(path: string): string; - export function extension(mime: string): string; - export function load(filepath: string): void; - export function define(mimes: Object): void; - - interface Charsets { - lookup(mime: string): string; - } - - export var charsets: Charsets; - export var default_type: string; -} \ No newline at end of file diff --git a/typings/globals/mime/typings.json b/typings/globals/mime/typings.json deleted file mode 100644 index a05df9548..000000000 --- a/typings/globals/mime/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/mime/mime.d.ts", - "raw": "registry:dt/mime#0.0.0+20160316155526", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/mime/mime.d.ts" - } -} diff --git a/typings/globals/mocha/index.d.ts b/typings/globals/mocha/index.d.ts deleted file mode 100644 index 852e7b6ac..000000000 --- a/typings/globals/mocha/index.d.ts +++ /dev/null @@ -1,233 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/mocha/mocha.d.ts -interface MochaSetupOptions { - //milliseconds to wait before considering a test slow - slow?: number; - - // timeout in milliseconds - timeout?: number; - - // ui name "bdd", "tdd", "exports" etc - ui?: string; - - //array of accepted globals - globals?: any[]; - - // reporter instance (function or string), defaults to `mocha.reporters.Spec` - reporter?: any; - - // bail on the first test failure - bail?: boolean; - - // ignore global leaks - ignoreLeaks?: boolean; - - // grep string or regexp to filter tests with - grep?: any; -} - -interface MochaDone { - (error?: Error): void; -} - -declare var mocha: Mocha; -declare var describe: Mocha.IContextDefinition; -declare var xdescribe: Mocha.IContextDefinition; -// alias for `describe` -declare var context: Mocha.IContextDefinition; -// alias for `describe` -declare var suite: Mocha.IContextDefinition; -declare var it: Mocha.ITestDefinition; -declare var xit: Mocha.ITestDefinition; -// alias for `it` -declare var test: Mocha.ITestDefinition; - -declare function before(action: () => void): void; - -declare function before(action: (done: MochaDone) => void): void; - -declare function before(description: string, action: () => void): void; - -declare function before(description: string, action: (done: MochaDone) => void): void; - -declare function setup(action: () => void): void; - -declare function setup(action: (done: MochaDone) => void): void; - -declare function after(action: () => void): void; - -declare function after(action: (done: MochaDone) => void): void; - -declare function after(description: string, action: () => void): void; - -declare function after(description: string, action: (done: MochaDone) => void): void; - -declare function teardown(action: () => void): void; - -declare function teardown(action: (done: MochaDone) => void): void; - -declare function beforeEach(action: () => void): void; - -declare function beforeEach(action: (done: MochaDone) => void): void; - -declare function beforeEach(description: string, action: () => void): void; - -declare function beforeEach(description: string, action: (done: MochaDone) => void): void; - -declare function suiteSetup(action: () => void): void; - -declare function suiteSetup(action: (done: MochaDone) => void): void; - -declare function afterEach(action: () => void): void; - -declare function afterEach(action: (done: MochaDone) => void): void; - -declare function afterEach(description: string, action: () => void): void; - -declare function afterEach(description: string, action: (done: MochaDone) => void): void; - -declare function suiteTeardown(action: () => void): void; - -declare function suiteTeardown(action: (done: MochaDone) => void): void; - -declare class Mocha { - constructor(options?: { - grep?: RegExp; - ui?: string; - reporter?: string; - timeout?: number; - bail?: boolean; - }); - - /** Setup mocha with the given options. */ - setup(options: MochaSetupOptions): Mocha; - bail(value?: boolean): Mocha; - addFile(file: string): Mocha; - /** Sets reporter by name, defaults to "spec". */ - reporter(name: string): Mocha; - /** Sets reporter constructor, defaults to mocha.reporters.Spec. */ - reporter(reporter: (runner: Mocha.IRunner, options: any) => any): Mocha; - ui(value: string): Mocha; - grep(value: string): Mocha; - grep(value: RegExp): Mocha; - invert(): Mocha; - ignoreLeaks(value: boolean): Mocha; - checkLeaks(): Mocha; - /** - * Function to allow assertion libraries to throw errors directly into mocha. - * This is useful when running tests in a browser because window.onerror will - * only receive the 'message' attribute of the Error. - */ - throwError(error: Error): void; - /** Enables growl support. */ - growl(): Mocha; - globals(value: string): Mocha; - globals(values: string[]): Mocha; - useColors(value: boolean): Mocha; - useInlineDiffs(value: boolean): Mocha; - timeout(value: number): Mocha; - slow(value: number): Mocha; - enableTimeouts(value: boolean): Mocha; - asyncOnly(value: boolean): Mocha; - noHighlighting(value: boolean): Mocha; - /** Runs tests and invokes `onComplete()` when finished. */ - run(onComplete?: (failures: number) => void): Mocha.IRunner; -} - -// merge the Mocha class declaration with a module -declare namespace Mocha { - /** Partial interface for Mocha's `Runnable` class. */ - interface IRunnable { - title: string; - fn: Function; - async: boolean; - sync: boolean; - timedOut: boolean; - } - - /** Partial interface for Mocha's `Suite` class. */ - interface ISuite { - parent: ISuite; - title: string; - - fullTitle(): string; - } - - /** Partial interface for Mocha's `Test` class. */ - interface ITest extends IRunnable { - parent: ISuite; - pending: boolean; - - fullTitle(): string; - } - - /** Partial interface for Mocha's `Runner` class. */ - interface IRunner {} - - interface IContextDefinition { - (description: string, spec: () => void): ISuite; - only(description: string, spec: () => void): ISuite; - skip(description: string, spec: () => void): void; - timeout(ms: number): void; - } - - interface ITestDefinition { - (expectation: string, assertion?: () => void): ITest; - (expectation: string, assertion?: (done: MochaDone) => void): ITest; - only(expectation: string, assertion?: () => void): ITest; - only(expectation: string, assertion?: (done: MochaDone) => void): ITest; - skip(expectation: string, assertion?: () => void): void; - skip(expectation: string, assertion?: (done: MochaDone) => void): void; - timeout(ms: number): void; - } - - export module reporters { - export class Base { - stats: { - suites: number; - tests: number; - passes: number; - pending: number; - failures: number; - }; - - constructor(runner: IRunner); - } - - export class Doc extends Base {} - export class Dot extends Base {} - export class HTML extends Base {} - export class HTMLCov extends Base {} - export class JSON extends Base {} - export class JSONCov extends Base {} - export class JSONStream extends Base {} - export class Landing extends Base {} - export class List extends Base {} - export class Markdown extends Base {} - export class Min extends Base {} - export class Nyan extends Base {} - export class Progress extends Base { - /** - * @param options.open String used to indicate the start of the progress bar. - * @param options.complete String used to indicate a complete test on the progress bar. - * @param options.incomplete String used to indicate an incomplete test on the progress bar. - * @param options.close String used to indicate the end of the progress bar. - */ - constructor(runner: IRunner, options?: { - open?: string; - complete?: string; - incomplete?: string; - close?: string; - }); - } - export class Spec extends Base {} - export class TAP extends Base {} - export class XUnit extends Base { - constructor(runner: IRunner, options?: any); - } - } -} - -declare module "mocha" { - export = Mocha; -} \ No newline at end of file diff --git a/typings/globals/mocha/typings.json b/typings/globals/mocha/typings.json deleted file mode 100644 index e0c039d7f..000000000 --- a/typings/globals/mocha/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/mocha/mocha.d.ts", - "raw": "registry:dt/mocha#2.2.5+20160317120654", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/mocha/mocha.d.ts" - } -} diff --git a/typings/globals/node/index.d.ts b/typings/globals/node/index.d.ts deleted file mode 100644 index 21823817b..000000000 --- a/typings/globals/node/index.d.ts +++ /dev/null @@ -1,2382 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/9081e075b730c9948b643a6c38d6deb18cb0ebdd/node/node.d.ts -interface Error { - stack?: string; -} - - -// compat for TypeScript 1.8 -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor {} -interface WeakMapConstructor {} -interface SetConstructor {} -interface WeakSetConstructor {} - -/************************************************ -* * -* GLOBAL * -* * -************************************************/ -declare var process: NodeJS.Process; -declare var global: NodeJS.Global; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare function clearTimeout(timeoutId: NodeJS.Timer): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare function clearInterval(intervalId: NodeJS.Timer): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; -declare function clearImmediate(immediateId: any): void; - -interface NodeRequireFunction { - (id: string): any; -} - -interface NodeRequire extends NodeRequireFunction { - resolve(id:string): string; - cache: any; - extensions: any; - main: any; -} - -declare var require: NodeRequire; - -interface NodeModule { - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: any; - children: any[]; -} - -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; -declare var SlowBuffer: { - new (str: string, encoding?: string): Buffer; - new (size: number): Buffer; - new (size: Uint8Array): Buffer; - new (array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; -}; - - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; -interface Buffer extends NodeBuffer {} - -/** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - */ -declare var Buffer: { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - new (str: string, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - new (size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new (array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - new (arrayBuffer: ArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new (array: any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - new (buffer: Buffer): Buffer; - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Buffer, buf2: Buffer): number; -}; - -/************************************************ -* * -* GLOBAL INTERFACES * -* * -************************************************/ -declare namespace NodeJS { - export interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - export interface EventEmitter { - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; - } - - export interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string|Buffer; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - } - - export interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Buffer|string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export interface ReadWriteStream extends ReadableStream, WritableStream {} - - export interface Events extends EventEmitter { } - - export interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - } - - export interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - } - - export interface Process extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - openssl: string; - }; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid:number, signal?: string|number): void; - pid: number; - title: string; - arch: string; - platform: string; - memoryUsage(): MemoryUsage; - nextTick(callback: Function): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?:number[]): number[]; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - } - - export interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: NodeJS.Timer) => void; - clearTimeout: (timeoutId: NodeJS.Timer) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - export interface Timer { - ref() : void; - unref() : void; - } -} - -/** - * @deprecated - */ -interface NodeBuffer extends Uint8Array { - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - // TODO: encoding param - indexOf(value: string | number | Buffer, byteOffset?: number): number; - // TODO: entries - // TODO: includes - // TODO: keys - // TODO: values -} - -/************************************************ -* * -* MODULES * -* * -************************************************/ -declare module "buffer" { - export var INSPECT_MAX_BYTES: number; - var BuffType: typeof Buffer; - var SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; -} - -declare module "querystring" { - export interface StringifyOptions { - encodeURIComponent?: Function; - } - - export interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } - - export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; - export function escape(str: string): string; - export function unescape(str: string): string; -} - -declare module "events" { - export class EventEmitter implements NodeJS.EventEmitter { - static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string): number; // deprecated - static defaultMaxListeners: number; - - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; - } -} - -declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; - - export interface RequestOptions { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: { [key: string]: any }; - auth?: string; - agent?: Agent|boolean; - } - - export interface Server extends events.EventEmitter, net.Server { - setTimeout(msecs: number, callback: Function): void; - maxHeadersCount: number; - timeout: number; - } - /** - * @deprecated Use IncomingMessage - */ - export interface ServerRequest extends IncomingMessage { - connection: net.Socket; - } - export interface ServerResponse extends events.EventEmitter, stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - statusMessage: string; - headersSent: boolean; - setHeader(name: string, value: string | string[]): void; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface ClientRequest extends events.EventEmitter, stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - write(chunk: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - setHeader(name: string, value: string | string[]): void; - getHeader(name: string): string; - removeHeader(name: string): void; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface IncomingMessage extends events.EventEmitter, stream.Readable { - httpVersion: string; - headers: any; - rawHeaders: string[]; - trailers: any; - rawTrailers: any; - setTimeout(msecs: number, callback: Function): NodeJS.Timer; - /** - * Only valid for request obtained from http.Server. - */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - socket: net.Socket; - } - /** - * @deprecated Use IncomingMessage - */ - export interface ClientResponse extends IncomingMessage { } - - export interface AgentOptions { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - } - - export class Agent { - maxSockets: number; - sockets: any; - requests: any; - - constructor(opts?: AgentOptions); - - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } - - export var METHODS: string[]; - - export var STATUS_CODES: { - [errorCode: number]: string; - [errorCode: string]: string; - }; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; - export var globalAgent: Agent; -} - -declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - - export interface ClusterSettings { - exec?: string; - args?: string[]; - silent?: boolean; - } - - export interface Address { - address: string; - port: number; - addressType: string; - } - - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): void; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - } - - export var settings: ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var worker: Worker; - export var workers: { - [index: string]: Worker - }; - - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; - export function listeners(event: string): Function[]; - export function emit(event: string, ...args: any[]): boolean; -} - -declare module "zlib" { - import * as stream from "stream"; - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - - export interface Gzip extends stream.Transform { } - export interface Gunzip extends stream.Transform { } - export interface Deflate extends stream.Transform { } - export interface Inflate extends stream.Transform { } - export interface DeflateRaw extends stream.Transform { } - export interface InflateRaw extends stream.Transform { } - export interface Unzip extends stream.Transform { } - - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; - - export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function deflateSync(buf: Buffer, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gzipSync(buf: Buffer, options?: ZlibOptions): any; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; - export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflateSync(buf: Buffer, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function unzipSync(buf: Buffer, options?: ZlibOptions): any; - - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; -} - -declare module "os" { - export interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - - export interface NetworkInterfaceInfo { - address: string; - netmask: string; - family: string; - mac: string; - internal: boolean; - } - - export function tmpdir(): string; - export function homedir(): string; - export function endianness(): string; - export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; - export function loadavg(): number[]; - export function totalmem(): number; - export function freemem(): number; - export function cpus(): CpuInfo[]; - export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]}; - export var EOL: string; -} - -declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; - - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string) => any; - } - - export interface RequestOptions extends http.RequestOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - } - - export interface Agent extends http.Agent { } - - export interface AgentOptions extends http.AgentOptions { - maxCachedSessions?: number; - } - - export var Agent: { - new (options?: AgentOptions): Agent; - }; - export interface Server extends tls.Server { } - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; - export var globalAgent: Agent; -} - -declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): number[]; - encode(codePoints: number[]): string; - } - export var version: any; -} - -declare module "repl" { - import * as stream from "stream"; - import * as events from "events"; - - export interface ReplOptions { - prompt?: string; - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - } - export function start(options: ReplOptions): events.EventEmitter; -} - -declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; - - export interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } - - export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): ReadLine; - resume(): ReadLine; - close(): void; - write(data: string|Buffer, key?: Key): void; - } - - export interface Completer { - (line: string): CompleterResult; - (line: string, callback: (err: any, result: CompleterResult) => void): any; - } - - export interface CompleterResult { - completions: string[]; - line: string; - } - - export interface ReadLineOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer; - terminal?: boolean; - historySize?: number; - } - - export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; - export function createInterface(options: ReadLineOptions): ReadLine; - - export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number|string, dy: number|string): void; - export function clearLine(stream: NodeJS.WritableStream, dir: number): void; - export function clearScreenDown(stream: NodeJS.WritableStream): void; -} - -declare module "vm" { - export interface Context { } - export interface ScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - export interface RunningScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - } - export class Script { - constructor(code: string, options?: ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; - runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; - runInThisContext(options?: RunningScriptOptions): any; - } - export function createContext(sandbox?: Context): Context; - export function isContext(sandbox: Context): boolean; - export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; - export function runInDebugContext(code: string): any; - export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; - export function runInThisContext(code: string, options?: RunningScriptOptions): any; -} - -declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; - - export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle?: any): void; - connected: boolean; - disconnect(): void; - unref(): void; - } - - export interface SpawnOptions { - cwd?: string; - env?: any; - stdio?: any; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; - - export interface ExecOptions { - cwd?: string; - env?: any; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - export interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: string; // specify `null`. - } - export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); - export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - - export interface ExecFileOptions { - cwd?: string; - env?: any; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: string; // specify `null`. - } - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - - export interface ForkOptions { - cwd?: string; - env?: any; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - uid?: number; - gid?: number; - } - export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; - - export interface SpawnSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - shell?: boolean | string; - } - export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding: string; // specify `null`. - } - export interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - export function spawnSync(command: string): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; - - export interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - shell?: string; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding: string; // specify `null`. - } - export function execSync(command: string): Buffer; - export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; - export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; - export function execSync(command: string, options?: ExecSyncOptions): Buffer; - - export interface ExecFileSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: string; // specify `null`. - } - export function execFileSync(command: string): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; -} - -declare module "url" { - export interface Url { - href?: string; - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: string | any; - slashes?: boolean; - hash?: string; - path?: string; - } - - export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; - export function format(url: Url): string; - export function resolve(from: string, to: string): string; -} - -declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; -} - -declare module "net" { - import * as stream from "stream"; - - export interface Socket extends stream.Duplex { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - setEncoding(encoding?: string): void; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - pause(): void; - resume(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - unref(): void; - ref(): void; - - remoteAddress: string; - remoteFamily: string; - remotePort: number; - localAddress: string; - localPort: number; - bytesRead: number; - bytesWritten: number; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - - export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; - }; - - export interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - } - - export interface Server extends Socket { - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; - listen(port: number, hostname?: string, listeningListener?: Function): Server; - listen(port: number, backlog?: number, listeningListener?: Function): Server; - listen(port: number, listeningListener?: Function): Server; - listen(path: string, backlog?: number, listeningListener?: Function): Server; - listen(path: string, listeningListener?: Function): Server; - listen(handle: any, backlog?: number, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - listen(options: ListenOptions, listeningListener?: Function): Server; - close(callback?: Function): Server; - address(): { port: number; family: string; address: string; }; - getConnections(cb: (error: Error, count: number) => void): void; - ref(): Server; - unref(): Server; - maxConnections: number; - connections: number; - } - export function createServer(connectionListener?: (socket: Socket) =>void ): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; - export function connect(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function connect(port: number, host?: string, connectionListener?: Function): Socket; - export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; -} - -declare module "dgram" { - import * as events from "events"; - - interface RemoteInfo { - address: string; - port: number; - size: number; - } - - interface AddressInfo { - address: string; - family: string; - port: number; - } - - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - - interface Socket extends events.EventEmitter { - send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port: number, address?: string, callback?: () => void): void; - close(): void; - address(): AddressInfo; - setBroadcast(flag: boolean): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - } -} - -declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - - interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - interface FSWatcher extends events.EventEmitter { - close(): void; - } - - export interface ReadStream extends stream.Readable { - close(): void; - } - export interface WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - } - - /** - * Asynchronous rename. - * @param oldPath - * @param newPath - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /** - * Synchronous rename - * @param oldPath - * @param newPath - */ - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string | Buffer, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string | Buffer, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string | Buffer, uid: number, gid: number): void; - export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string | Buffer, mode: number): void; - export function chmodSync(path: string | Buffer, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string | Buffer, mode: number): void; - export function lchmodSync(path: string | Buffer, mode: string): void; - export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string | Buffer): Stats; - export function lstatSync(path: string | Buffer): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; - export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; - export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string | Buffer): string; - export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string | Buffer, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; - /* - * Asynchronous unlink - deletes the file specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous unlink - deletes the file specified in {path} - * - * @param path - */ - export function unlinkSync(path: string | Buffer): void; - /* - * Asynchronous rmdir - removes the directory specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous rmdir - removes the directory specified in {path} - * - * @param path - */ - export function rmdirSync(path: string | Buffer): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdirSync(path: string | Buffer, mode?: number): void; - /* - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdirSync(path: string | Buffer, mode?: string): void; - /* - * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @param callback The created folder path is passed as a string to the callback's second parameter. - */ - export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; - /* - * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @returns Returns the created folder path. - */ - export function mkdtempSync(prefix: string): string; - export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string | Buffer): string[]; - export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function closeSync(fd: number): void; - export function open(path: string | Buffer, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string | Buffer, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string | Buffer, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function openSync(path: string | Buffer, flags: string, mode?: number): number; - export function openSync(path: string | Buffer, flags: string, mode?: string): number; - export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; - export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function futimesSync(fd: number, atime: Date, mtime: Date): void; - export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; - export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; - export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - */ - export function readFileSync(filename: string, encoding: string): string; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. - */ - export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. - */ - export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; - export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; - export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; - export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; - export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; - export function existsSync(path: string | Buffer): boolean; - /** Constant for fs.access(). File is visible to the calling process. */ - export var F_OK: number; - /** Constant for fs.access(). File can be read by the calling process. */ - export var R_OK: number; - /** Constant for fs.access(). File can be written by the calling process. */ - export var W_OK: number; - /** Constant for fs.access(). File can be executed by the calling process. */ - export var X_OK: number; - /** Tests a user's permissions for the file specified by path. */ - export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; - export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; - /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string | Buffer, mode ?: number): void; - export function createReadStream(path: string | Buffer, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - }): ReadStream; - export function createWriteStream(path: string | Buffer, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - }): WriteStream; -} - -declare module "path" { - - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - export interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } - - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ - export function normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths string paths to join. - */ - export function join(...paths: any[]): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths string paths to join. - */ - export function join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ - export function resolve(...pathSegments: any[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - export function isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to - */ - export function relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ - export function dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ - export function basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ - export function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ - export var sep: string; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - export var delimiter: string; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - export function parse(pathString: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - export function format(pathObject: ParsedPath): string; - - export module posix { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } - - export module win32 { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } -} - -declare module "string_decoder" { - export interface NodeStringDecoder { - write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; - } - export var StringDecoder: { - new (encoding: string): NodeStringDecoder; - }; -} - -declare module "tls" { - import * as crypto from "crypto"; - import * as net from "net"; - import * as stream from "stream"; - - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; - - export interface TlsOptions { - host?: string; - port?: number; - pfx?: any; //string or buffer - key?: any; //string or buffer - passphrase?: string; - cert?: any; - ca?: any; //string or buffer - crl?: any; //string or string array - ciphers?: string; - honorCipherOrder?: any; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string) => any; - } - - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: net.Socket; - pfx?: string | Buffer - key?: string | Buffer - passphrase?: string; - cert?: string | Buffer - ca?: (string | Buffer)[]; - rejectUnauthorized?: boolean; - NPNProtocols?: (string | Buffer)[]; - servername?: string; - } - - export interface Server extends net.Server { - close(): Server; - address(): { port: number; family: string; address: string; }; - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - maxConnections: number; - connections: number; - } - - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - - export interface SecurePair { - encrypted: any; - cleartext: any; - } - - export interface SecureContextOptions { - pfx?: string | Buffer; - key?: string | Buffer; - passphrase?: string; - cert?: string | Buffer; - ca?: string | Buffer; - crl?: string | string[] - ciphers?: string; - honorCipherOrder?: boolean; - } - - export interface SecureContext { - context: any; - } - - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; - export function createSecureContext(details: SecureContextOptions): SecureContext; -} - -declare module "crypto" { - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: string | string[]; - crl: string | string[]; - ciphers: string; - } - export interface Credentials { context?: any; } - export function createCredentials(details: CredentialDetails): Credentials; - export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string): Hmac; - export function createHmac(algorithm: string, key: Buffer): Hmac; - export interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; - digest(): Buffer; - } - export interface Hmac extends NodeJS.ReadWriteStream { - update(data: any, input_encoding?: string): Hmac; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; - digest(): Buffer; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - export interface Cipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; - update(data: string, input_encoding: "utf8"|"ascii"|"binary"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "binary"|"base64"|"hex"): string; - update(data: string, input_encoding: "utf8"|"ascii"|"binary", output_encoding: "binary"|"base64"|"hex"): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; - getAuthTag(): Buffer; - } - export function createDecipher(algorithm: string, password: any): Decipher; - export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - export interface Decipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; - update(data: string, input_encoding: "binary"|"base64"|"hex"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "utf8"|"ascii"|"binary"): string; - update(data: string, input_encoding: "binary"|"base64"|"hex", output_encoding: "utf8"|"ascii"|"binary"): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; - setAuthTag(tag: Buffer): void; - } - export function createSign(algorithm: string): Signer; - export interface Signer extends NodeJS.WritableStream { - update(data: any): void; - sign(private_key: string, output_format: string): string; - } - export function createVerify(algorith: string): Verify; - export interface Verify extends NodeJS.WritableStream { - update(data: any): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - export function createDiffieHellman(prime_length: number): DiffieHellman; - export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; - export interface DiffieHellman { - generateKeys(encoding?: string): string; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; - } - export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; - export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string) : Buffer; - export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; - export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; - export interface RsaPublicKey { - key: string; - padding?: any; - } - export interface RsaPrivateKey { - key: string; - passphrase?: string, - padding?: any; - } - export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer - export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer -} - -declare module "stream" { - import * as events from "events"; - - export class Stream extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - } - - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - } - - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - writable: boolean; - constructor(opts?: DuplexOptions); - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface TransformOptions extends ReadableOptions, WritableOptions {} - - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: Function): void; - _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform {} -} - -declare module "util" { - export interface InspectOptions { - showHidden?: boolean; - depth?: number; - colors?: boolean; - customInspect?: boolean; - } - - export function format(format: any, ...param: any[]): string; - export function debug(string: string): void; - export function error(...param: any[]): void; - export function puts(...param: any[]): void; - export function print(...param: any[]): void; - export function log(string: string): void; - export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; - export function inspect(object: any, options: InspectOptions): string; - export function isArray(object: any): boolean; - export function isRegExp(object: any): boolean; - export function isDate(object: any): boolean; - export function isError(object: any): boolean; - export function inherits(constructor: any, superConstructor: any): void; - export function debuglog(key:string): (msg:string,...param: any[])=>void; -} - -declare module "assert" { - function internal (value: any, message?: string): void; - namespace internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); - } - - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export function ifError(value: any): void; - } - - export = internal; -} - -declare module "tty" { - import * as net from "net"; - - export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - isTTY: boolean; - } - export interface WriteStream extends net.Socket { - columns: number; - rows: number; - isTTY: boolean; - } -} - -declare module "domain" { - import * as events from "events"; - - export class Domain extends events.EventEmitter implements NodeJS.Domain { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - } - - export function create(): Domain; -} - -declare module "constants" { - export var E2BIG: number; - export var EACCES: number; - export var EADDRINUSE: number; - export var EADDRNOTAVAIL: number; - export var EAFNOSUPPORT: number; - export var EAGAIN: number; - export var EALREADY: number; - export var EBADF: number; - export var EBADMSG: number; - export var EBUSY: number; - export var ECANCELED: number; - export var ECHILD: number; - export var ECONNABORTED: number; - export var ECONNREFUSED: number; - export var ECONNRESET: number; - export var EDEADLK: number; - export var EDESTADDRREQ: number; - export var EDOM: number; - export var EEXIST: number; - export var EFAULT: number; - export var EFBIG: number; - export var EHOSTUNREACH: number; - export var EIDRM: number; - export var EILSEQ: number; - export var EINPROGRESS: number; - export var EINTR: number; - export var EINVAL: number; - export var EIO: number; - export var EISCONN: number; - export var EISDIR: number; - export var ELOOP: number; - export var EMFILE: number; - export var EMLINK: number; - export var EMSGSIZE: number; - export var ENAMETOOLONG: number; - export var ENETDOWN: number; - export var ENETRESET: number; - export var ENETUNREACH: number; - export var ENFILE: number; - export var ENOBUFS: number; - export var ENODATA: number; - export var ENODEV: number; - export var ENOENT: number; - export var ENOEXEC: number; - export var ENOLCK: number; - export var ENOLINK: number; - export var ENOMEM: number; - export var ENOMSG: number; - export var ENOPROTOOPT: number; - export var ENOSPC: number; - export var ENOSR: number; - export var ENOSTR: number; - export var ENOSYS: number; - export var ENOTCONN: number; - export var ENOTDIR: number; - export var ENOTEMPTY: number; - export var ENOTSOCK: number; - export var ENOTSUP: number; - export var ENOTTY: number; - export var ENXIO: number; - export var EOPNOTSUPP: number; - export var EOVERFLOW: number; - export var EPERM: number; - export var EPIPE: number; - export var EPROTO: number; - export var EPROTONOSUPPORT: number; - export var EPROTOTYPE: number; - export var ERANGE: number; - export var EROFS: number; - export var ESPIPE: number; - export var ESRCH: number; - export var ETIME: number; - export var ETIMEDOUT: number; - export var ETXTBSY: number; - export var EWOULDBLOCK: number; - export var EXDEV: number; - export var WSAEINTR: number; - export var WSAEBADF: number; - export var WSAEACCES: number; - export var WSAEFAULT: number; - export var WSAEINVAL: number; - export var WSAEMFILE: number; - export var WSAEWOULDBLOCK: number; - export var WSAEINPROGRESS: number; - export var WSAEALREADY: number; - export var WSAENOTSOCK: number; - export var WSAEDESTADDRREQ: number; - export var WSAEMSGSIZE: number; - export var WSAEPROTOTYPE: number; - export var WSAENOPROTOOPT: number; - export var WSAEPROTONOSUPPORT: number; - export var WSAESOCKTNOSUPPORT: number; - export var WSAEOPNOTSUPP: number; - export var WSAEPFNOSUPPORT: number; - export var WSAEAFNOSUPPORT: number; - export var WSAEADDRINUSE: number; - export var WSAEADDRNOTAVAIL: number; - export var WSAENETDOWN: number; - export var WSAENETUNREACH: number; - export var WSAENETRESET: number; - export var WSAECONNABORTED: number; - export var WSAECONNRESET: number; - export var WSAENOBUFS: number; - export var WSAEISCONN: number; - export var WSAENOTCONN: number; - export var WSAESHUTDOWN: number; - export var WSAETOOMANYREFS: number; - export var WSAETIMEDOUT: number; - export var WSAECONNREFUSED: number; - export var WSAELOOP: number; - export var WSAENAMETOOLONG: number; - export var WSAEHOSTDOWN: number; - export var WSAEHOSTUNREACH: number; - export var WSAENOTEMPTY: number; - export var WSAEPROCLIM: number; - export var WSAEUSERS: number; - export var WSAEDQUOT: number; - export var WSAESTALE: number; - export var WSAEREMOTE: number; - export var WSASYSNOTREADY: number; - export var WSAVERNOTSUPPORTED: number; - export var WSANOTINITIALISED: number; - export var WSAEDISCON: number; - export var WSAENOMORE: number; - export var WSAECANCELLED: number; - export var WSAEINVALIDPROCTABLE: number; - export var WSAEINVALIDPROVIDER: number; - export var WSAEPROVIDERFAILEDINIT: number; - export var WSASYSCALLFAILURE: number; - export var WSASERVICE_NOT_FOUND: number; - export var WSATYPE_NOT_FOUND: number; - export var WSA_E_NO_MORE: number; - export var WSA_E_CANCELLED: number; - export var WSAEREFUSED: number; - export var SIGHUP: number; - export var SIGINT: number; - export var SIGILL: number; - export var SIGABRT: number; - export var SIGFPE: number; - export var SIGKILL: number; - export var SIGSEGV: number; - export var SIGTERM: number; - export var SIGBREAK: number; - export var SIGWINCH: number; - export var SSL_OP_ALL: number; - export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; - export var SSL_OP_CISCO_ANYCONNECT: number; - export var SSL_OP_COOKIE_EXCHANGE: number; - export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - export var SSL_OP_EPHEMERAL_RSA: number; - export var SSL_OP_LEGACY_SERVER_CONNECT: number; - export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; - export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - export var SSL_OP_NETSCAPE_CA_DN_BUG: number; - export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NO_COMPRESSION: number; - export var SSL_OP_NO_QUERY_MTU: number; - export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - export var SSL_OP_NO_SSLv2: number; - export var SSL_OP_NO_SSLv3: number; - export var SSL_OP_NO_TICKET: number; - export var SSL_OP_NO_TLSv1: number; - export var SSL_OP_NO_TLSv1_1: number; - export var SSL_OP_NO_TLSv1_2: number; - export var SSL_OP_PKCS1_CHECK_1: number; - export var SSL_OP_PKCS1_CHECK_2: number; - export var SSL_OP_SINGLE_DH_USE: number; - export var SSL_OP_SINGLE_ECDH_USE: number; - export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; - export var SSL_OP_TLS_D5_BUG: number; - export var SSL_OP_TLS_ROLLBACK_BUG: number; - export var ENGINE_METHOD_DSA: number; - export var ENGINE_METHOD_DH: number; - export var ENGINE_METHOD_RAND: number; - export var ENGINE_METHOD_ECDH: number; - export var ENGINE_METHOD_ECDSA: number; - export var ENGINE_METHOD_CIPHERS: number; - export var ENGINE_METHOD_DIGESTS: number; - export var ENGINE_METHOD_STORE: number; - export var ENGINE_METHOD_PKEY_METHS: number; - export var ENGINE_METHOD_PKEY_ASN1_METHS: number; - export var ENGINE_METHOD_ALL: number; - export var ENGINE_METHOD_NONE: number; - export var DH_CHECK_P_NOT_SAFE_PRIME: number; - export var DH_CHECK_P_NOT_PRIME: number; - export var DH_UNABLE_TO_CHECK_GENERATOR: number; - export var DH_NOT_SUITABLE_GENERATOR: number; - export var NPN_ENABLED: number; - export var RSA_PKCS1_PADDING: number; - export var RSA_SSLV23_PADDING: number; - export var RSA_NO_PADDING: number; - export var RSA_PKCS1_OAEP_PADDING: number; - export var RSA_X931_PADDING: number; - export var RSA_PKCS1_PSS_PADDING: number; - export var POINT_CONVERSION_COMPRESSED: number; - export var POINT_CONVERSION_UNCOMPRESSED: number; - export var POINT_CONVERSION_HYBRID: number; - export var O_RDONLY: number; - export var O_WRONLY: number; - export var O_RDWR: number; - export var S_IFMT: number; - export var S_IFREG: number; - export var S_IFDIR: number; - export var S_IFCHR: number; - export var S_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: number; - export var O_TRUNC: number; - export var O_APPEND: number; - export var F_OK: number; - export var R_OK: number; - export var W_OK: number; - export var X_OK: number; - export var UV_UDP_REUSEADDR: number; -} \ No newline at end of file diff --git a/typings/globals/node/typings.json b/typings/globals/node/typings.json deleted file mode 100644 index b9cf7106b..000000000 --- a/typings/globals/node/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/9081e075b730c9948b643a6c38d6deb18cb0ebdd/node/node.d.ts", - "raw": "registry:dt/node#6.0.0+20160524002506", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/9081e075b730c9948b643a6c38d6deb18cb0ebdd/node/node.d.ts" - } -} diff --git a/typings/globals/serve-static/index.d.ts b/typings/globals/serve-static/index.d.ts deleted file mode 100644 index 60b2cc05a..000000000 --- a/typings/globals/serve-static/index.d.ts +++ /dev/null @@ -1,79 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/DefinitelyTyped/DefinitelyTyped/25fde56c8d1ba7aa5fb700e928f5413e047561f3/serve-static/serve-static.d.ts -declare module "serve-static" { - import * as express from "express-serve-static-core"; - - /** - * Create a new middleware function to serve files from within a given root directory. - * The file to serve will be determined by combining req.url with the provided root directory. - * When a file is not found, instead of sending a 404 response, this module will instead call next() to move on to the next middleware, allowing for stacking and fall-backs. - */ - function serveStatic(root: string, options?: { - /** - * Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). - * Note this check is done on the path itself without checking if the path actually exists on the disk. - * If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny"). - * The default value is 'ignore'. - * 'allow' No special treatment for dotfiles - * 'deny' Send a 403 for any request for a dotfile - * 'ignore' Pretend like the dotfile does not exist and call next() - */ - dotfiles?: string; - - /** - * Enable or disable etag generation, defaults to true. - */ - etag?: boolean; - - /** - * Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. - * The first that exists will be served. Example: ['html', 'htm']. - * The default value is false. - */ - extensions?: string[]; - - /** - * Let client errors fall-through as unhandled requests, otherwise forward a client error. - * The default value is false. - */ - fallthrough?: boolean; - - /** - * By default this module will send "index.html" files in response to a request on a directory. - * To disable this set false or to supply a new index pass a string or an array in preferred order. - */ - index?: boolean|string|string[]; - - /** - * Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value. - */ - lastModified?: boolean; - - /** - * Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module. - */ - maxAge?: number|string; - - /** - * Redirect to trailing "/" when the pathname is a dir. Defaults to true. - */ - redirect?: boolean; - - /** - * Function to set custom headers on response. Alterations to the headers need to occur synchronously. - * The function is called as fn(res, path, stat), where the arguments are: - * res the response object - * path the file path that is being sent - * stat the stat object of the file that is being sent - */ - setHeaders?: (res: express.Response, path: string, stat: any) => any; - }): express.Handler; - - import * as m from "mime"; - - namespace serveStatic { - var mime: typeof m; - } - - export = serveStatic; -} \ No newline at end of file diff --git a/typings/globals/serve-static/typings.json b/typings/globals/serve-static/typings.json deleted file mode 100644 index 723959cc8..000000000 --- a/typings/globals/serve-static/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/25fde56c8d1ba7aa5fb700e928f5413e047561f3/serve-static/serve-static.d.ts", - "raw": "registry:dt/serve-static#0.0.0+20160501131543", - "typings": "https://github.com/raw/DefinitelyTyped/DefinitelyTyped/25fde56c8d1ba7aa5fb700e928f5413e047561f3/serve-static/serve-static.d.ts" - } -} diff --git a/typings/index.d.ts b/typings/index.d.ts deleted file mode 100644 index cc848b34b..000000000 --- a/typings/index.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/typings/modules/chai/index.d.ts b/typings/modules/chai/index.d.ts deleted file mode 100644 index 0d262aee2..000000000 --- a/typings/modules/chai/index.d.ts +++ /dev/null @@ -1,547 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-assertion-error/105841317bd2bdd5d110bfb763e49e482a77230d/main.d.ts -declare module '~chai~assertion-error/main' { -// Type definitions for assertion-error 1.0.0 -// Project: https://github.com/chaijs/assertion-error -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -export class AssertionError implements Error { - constructor(message: string, props?: any, ssf?: Function); - public name: string; - public message: string; - public showDiff: boolean; - public stack: string; - - /** - * Allow errors to be converted to JSON for static transfer. - * - * @param {Boolean} include stack (default: `true`) - * @return {Object} object that can be `JSON.stringify` - */ - public toJSON(stack: boolean): Object; -} -} -declare module '~chai~assertion-error' { -import alias = require('~chai~assertion-error/main'); -export = alias; -} - -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Assert.d.ts -declare module '~chai/lib/Assert' { -export interface AssertStatic extends Assert { -} - -export interface Assert { - /** - * @param expression Expression to test for truthiness. - * @param message Message to display on error. - */ - (expression: any, message?: string): void; - (expression: any, messageCallback: () => string): void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string): void; - - ok(val: any, msg?: string): void; - isOk(val: any, msg?: string): void; - notOk(val: any, msg?: string): void; - isNotOk(val: any, msg?: string): void; - - equal(act: any, exp: any, msg?: string): void; - notEqual(act: any, exp: any, msg?: string): void; - - strictEqual(act: any, exp: any, msg?: string): void; - notStrictEqual(act: any, exp: any, msg?: string): void; - - deepEqual(act: any, exp: any, msg?: string): void; - notDeepEqual(act: any, exp: any, msg?: string): void; - - isTrue(val: any, msg?: string): void; - isFalse(val: any, msg?: string): void; - - isNotTrue(val: any, msg?: string): void; - isNotFalse(val: any, msg?: string): void; - - isNull(val: any, msg?: string): void; - isNotNull(val: any, msg?: string): void; - - isUndefined(val: any, msg?: string): void; - isDefined(val: any, msg?: string): void; - - isNaN(val: any, msg?: string): void; - isNotNaN(val: any, msg?: string): void; - - isAbove(val: number, abv: number, msg?: string): void; - isBelow(val: number, blw: number, msg?: string): void; - - isAtLeast(val: number, atlst: number, msg?: string): void; - isAtMost(val: number, atmst: number, msg?: string): void; - - isFunction(val: any, msg?: string): void; - isNotFunction(val: any, msg?: string): void; - - isObject(val: any, msg?: string): void; - isNotObject(val: any, msg?: string): void; - - isArray(val: any, msg?: string): void; - isNotArray(val: any, msg?: string): void; - - isString(val: any, msg?: string): void; - isNotString(val: any, msg?: string): void; - - isNumber(val: any, msg?: string): void; - isNotNumber(val: any, msg?: string): void; - - isBoolean(val: any, msg?: string): void; - isNotBoolean(val: any, msg?: string): void; - - typeOf(val: any, type: string, msg?: string): void; - notTypeOf(val: any, type: string, msg?: string): void; - - instanceOf(val: any, type: Function, msg?: string): void; - notInstanceOf(val: any, type: Function, msg?: string): void; - - include(exp: string, inc: any, msg?: string): void; - include(exp: any[], inc: any, msg?: string): void; - include(exp: Object, inc: Object, msg?: string): void; - - notInclude(exp: string, inc: any, msg?: string): void; - notInclude(exp: any[], inc: any, msg?: string): void; - - match(exp: any, re: RegExp, msg?: string): void; - notMatch(exp: any, re: RegExp, msg?: string): void; - - property(obj: Object, prop: string, msg?: string): void; - notProperty(obj: Object, prop: string, msg?: string): void; - deepProperty(obj: Object, prop: string, msg?: string): void; - notDeepProperty(obj: Object, prop: string, msg?: string): void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string): void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - lengthOf(exp: any, len: number, msg?: string): void; - - throw(fn: Function, msg?: string): void; - throw(fn: Function, regExp: RegExp): void; - throw(fn: Function, errType: Function, msg?: string): void; - throw(fn: Function, errType: Function, regExp: RegExp): void; - - throws(fn: Function, msg?: string): void; - throws(fn: Function, regExp: RegExp): void; - throws(fn: Function, errType: Function, msg?: string): void; - throws(fn: Function, errType: Function, regExp: RegExp): void; - - Throw(fn: Function, msg?: string): void; - Throw(fn: Function, regExp: RegExp): void; - Throw(fn: Function, errType: Function, msg?: string): void; - Throw(fn: Function, errType: Function, regExp: RegExp): void; - - doesNotThrow(fn: Function, msg?: string): void; - doesNotThrow(fn: Function, regExp: RegExp): void; - doesNotThrow(fn: Function, errType: Function, msg?: string): void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; - - operator(val: any, operator: string, val2: any, msg?: string): void; - closeTo(act: number, exp: number, delta: number, msg?: string): void; - approximately(act: number, exp: number, delta: number, msg?: string): void; - - sameMembers(set1: any[], set2: any[], msg?: string): void; - sameDeepMembers(set1: any[], set2: any[], msg?: string): void; - includeMembers(superset: any[], subset: any[], msg?: string): void; - includeDeepMembers(superset: any[], subset: any[], msg?: string): void; - - ifError(val: any, msg?: string): void; - - isExtensible(obj: {}, msg?: string): void; - extensible(obj: {}, msg?: string): void; - isNotExtensible(obj: {}, msg?: string): void; - notExtensible(obj: {}, msg?: string): void; - - isSealed(obj: {}, msg?: string): void; - sealed(obj: {}, msg?: string): void; - isNotSealed(obj: {}, msg?: string): void; - notSealed(obj: {}, msg?: string): void; - - isFrozen(obj: Object, msg?: string): void; - frozen(obj: Object, msg?: string): void; - isNotFrozen(obj: Object, msg?: string): void; - notFrozen(obj: Object, msg?: string): void; - - oneOf(inList: any, list: any[], msg?: string): void; - - changes(fn: Function, obj: {}, property: string): void; - doesNotChange(fn: Function, obj: {}, property: string): void; - increases(fn: Function, obj: {}, property: string): void; - doesNotIncrease(fn: Function, obj: {}, property: string): void; - - decreases(fn: Function, obj: {}, property: string): void; - doesNotDecrease(fn: Function, obj: {}, property: string): void; - } -} -declare module 'chai/lib/Assert' { -import alias = require('~chai/lib/Assert'); -export = alias; -} - -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Assertion.d.ts -declare module '~chai/lib/Assertion' { -export interface AssertionStatic { - (target?: any, message?: string, stack?: Function): Assertion; - new (target?: any, message?: string, stack?: Function): Assertion; -} - -export interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - not: Assertion; - deep: Deep; - any: KeyFilter; - all: KeyFilter; - a: TypeComparison; - an: TypeComparison; - include: Include; - includes: Include; - contain: Include; - contains: Include; - ok: Assertion; - true: Assertion; - false: Assertion; - null: Assertion; - undefined: Assertion; - NaN: Assertion; - exist: Assertion; - empty: Assertion; - arguments: Assertion; - Arguments: Assertion; - equal: Equal; - equals: Equal; - eq: Equal; - eql: Equal; - eqls: Equal; - property: Property; - ownProperty: OwnProperty; - haveOwnProperty: OwnProperty; - ownPropertyDescriptor: OwnPropertyDescriptor; - haveOwnPropertyDescriptor: OwnPropertyDescriptor; - length: Length; - lengthOf: Length; - match: Match; - matches: Match; - string(str: string, message?: string): Assertion; - keys: Keys; - key(str: string): Assertion; - throw: Throw; - throws: Throw; - Throw: Throw; - respondTo: RespondTo; - respondsTo: RespondTo; - itself: Assertion; - satisfy: Satisfy; - satisfies: Satisfy; - closeTo: CloseTo; - approximately: CloseTo; - members: Members; - increase: PropertyChange; - increases: PropertyChange; - decrease: PropertyChange; - decreases: PropertyChange; - change: PropertyChange; - changes: PropertyChange; - extensible: Assertion; - sealed: Assertion; - frozen: Assertion; - oneOf(list: any[], message?: string): Assertion; -} - -export interface LanguageChains { - to: Assertion; - be: Assertion; - been: Assertion; - is: Assertion; - that: Assertion; - which: Assertion; - and: Assertion; - has: Assertion; - have: Assertion; - with: Assertion; - at: Assertion; - of: Assertion; - same: Assertion; -} - -export interface NumericComparison { - above: NumberComparer; - gt: NumberComparer; - greaterThan: NumberComparer; - least: NumberComparer; - gte: NumberComparer; - below: NumberComparer; - lt: NumberComparer; - lessThan: NumberComparer; - most: NumberComparer; - lte: NumberComparer; - within(start: number, finish: number, message?: string): Assertion; -} - -export interface NumberComparer { - (value: number, message?: string): Assertion; -} - -export interface TypeComparison { - (type: string, message?: string): Assertion; - instanceof: InstanceOf; - instanceOf: InstanceOf; -} - -export interface InstanceOf { - (constructor: Object, message?: string): Assertion; -} - -export interface CloseTo { - (expected: number, delta: number, message?: string): Assertion; -} - -export interface Deep { - equal: Equal; - equals: Equal; - eq: Equal; - include: Include; - property: Property; - members: Members; -} - -export interface KeyFilter { - keys: Keys; -} - -export interface Equal { - (value: any, message?: string): Assertion; -} - -export interface Property { - (name: string, value?: any, message?: string): Assertion; -} - -export interface OwnProperty { - (name: string, message?: string): Assertion; -} - -export interface OwnPropertyDescriptor { - (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; - (name: string, message?: string): Assertion; -} - -export interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Assertion; -} - -export interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; - string(value: string, message?: string): Assertion; - keys: Keys; - members: Members; - any: KeyFilter; - all: KeyFilter; -} - -export interface Match { - (regexp: RegExp | string, message?: string): Assertion; -} - -export interface Keys { - (...keys: any[]): Assertion; - (keys: any[]): Assertion; - (keys: Object): Assertion; -} - -export interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; -} - -export interface RespondTo { - (method: string, message?: string): Assertion; -} - -export interface Satisfy { - (matcher: Function, message?: string): Assertion; -} - -export interface Members { - (set: any[], message?: string): Assertion; -} - -export interface PropertyChange { - (object: Object, prop: string, msg?: string): Assertion; -} -} -declare module 'chai/lib/Assertion' { -import alias = require('~chai/lib/Assertion'); -export = alias; -} - -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Expect.d.ts -declare module '~chai/lib/Expect' { -import {AssertionStatic} from '~chai/lib/Assertion'; - -export interface ExpectStatic extends AssertionStatic { - fail(actual?: any, expected?: any, message?: string, operator?: string): void; -} -} -declare module 'chai/lib/Expect' { -import alias = require('~chai/lib/Expect'); -export = alias; -} - -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Should.d.ts -declare module '~chai/lib/Should' { -export interface Should extends ShouldAssertion { - not: ShouldAssertion; - fail(actual: any, expected: any, message?: string, operator?: string): void; -} - -export interface ShouldAssertion { - Throw: ShouldThrow; - throw: ShouldThrow; - equal(value1: any, value2: any, message?: string): void; - exist(value: any, message?: string): void; -} - -export interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string | RegExp, message?: string): void; - (actual: Function, constructor: Error | Function, expected?: string | RegExp, message?: string): void; -} -} -declare module 'chai/lib/Should' { -import alias = require('~chai/lib/Should'); -export = alias; -} - -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Config.d.ts -declare module '~chai/lib/Config' { -export interface Config { - includeStack: boolean; - showDiff: boolean; - truncateThreshold: number; -} -} -declare module 'chai/lib/Config' { -import alias = require('~chai/lib/Config'); -export = alias; -} - -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Utils.d.ts -declare module '~chai/lib/Utils' { -import {Assertion} from '~chai/lib/Assertion'; - -export interface PathInfo { - parent: any; - name: number|string; - value: any; - exists: boolean; -} - -export interface Utils { - addChainableMethod(ctx: any, name: string, chainingBehavior: (value: any) => void): void; - addMethod(ctx: any, name: string, method: (value: any) => void): void; - addProperty(ctx: any, name: string, getter: () => void): void; - expectTypes(obj: Object, types: string[]): void; - flag(obj: Object, key: string, value?: any): any; - getActual(obj: Object, actual?: any): any; - getEnumerableProperties(obj: Object): string[]; - getMessage(obj: Object, params: any[]): string; - getMessage(obj: Object, message: string, negateMessage: string): string; - getName(func: Function): string; - getPathInfo(path: string, obj: Object): PathInfo; - getPathValue(path: string, obj: Object): any; - getProperties(obj: Object): string[]; - hasProperty(obj: Object, name: string): boolean; - transferFlags(assertion: Assertion | any, obj: Object, includeAll?: boolean): void; - inspect(obj: any): any; -} -} -declare module 'chai/lib/Utils' { -import alias = require('~chai/lib/Utils'); -export = alias; -} - -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Chai.d.ts -declare module '~chai/lib/Chai' { -import * as AE from '~chai~assertion-error'; - -import * as Assert from '~chai/lib/Assert'; -import * as A from '~chai/lib/Assertion'; -import * as Expect from '~chai/lib/Expect'; -import * as Should from '~chai/lib/Should'; -import * as Config from '~chai/lib/Config'; -import * as Utils from '~chai/lib/Utils'; - -namespace chai { - export interface AssertionStatic extends A.AssertionStatic {} - export class AssertionError extends AE.AssertionError {} - export var Assertion: A.AssertionStatic; - export var expect: Expect.ExpectStatic; - export var assert: Assert.AssertStatic; - export var config: Config.Config; - export var util: Utils.Utils; - export function should(): Should.Should; - export function Should(): Should.Should; - /** - * Provides a way to extend the internals of Chai - */ - export function use(fn: (chai: any, utils: Utils.Utils) => void): typeof chai; -} - -export = chai; - -/* tslint:disable:no-internal-module */ -global { - interface Object { - should: A.Assertion; - } -} -} -declare module 'chai/lib/Chai' { -import alias = require('~chai/lib/Chai'); -export = alias; -} - -// Generated by typings -// Source: https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/index.d.ts -declare module '~chai/index' { -// Type definitions for chai 3.4.0 -// Project: http://chaijs.com/ -// Original Definitions by: Jed Mao , -// Bart van der Schoor , -// Andrew Brown , -// Olivier Chevet , -// Matt Wistrand - -import chai = require('~chai/lib/Chai'); - -export = chai; -} -declare module 'chai/index' { -import alias = require('~chai/index'); -export = alias; -} -declare module 'chai' { -import alias = require('~chai/index'); -export = alias; -} diff --git a/typings/modules/chai/typings.json b/typings/modules/chai/typings.json deleted file mode 100644 index f81ca6bf1..000000000 --- a/typings/modules/chai/typings.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/typings.json", - "raw": "registry:npm/chai#3.5.0+20160415060238", - "main": "index.d.ts", - "global": false, - "dependencies": { - "assertion-error": { - "src": "https://github.com/raw/typed-typings/npm-assertion-error/105841317bd2bdd5d110bfb763e49e482a77230d/typings.json", - "raw": "github:typed-typings/npm-assertion-error#105841317bd2bdd5d110bfb763e49e482a77230d", - "main": "main.d.ts", - "global": false, - "name": "assertion-error", - "type": "typings" - } - }, - "name": "chai", - "type": "typings" - } -} diff --git a/typings/modules/graphql/index.d.ts b/typings/modules/graphql/index.d.ts deleted file mode 100644 index e17e5d932..000000000 --- a/typings/modules/graphql/index.d.ts +++ /dev/null @@ -1,957 +0,0 @@ -// Generated by typings -// Source: https://github.com/raw/nitintutlani/typed-graphql/master/graphql.d.ts -declare module '~graphql/graphql' { - -// graphql.js - -export function graphql( - schema: GraphQLSchema, - requestString: string, - rootValue?: any, - contextValue?: any, - variableValues?: { [key: string]: any }, - operationName?: string -): Promise; - -interface GraphQLResult { - data?: any; - errors?: Array; -} - -// error/*.js - -class GraphQLError extends Error { - constructor( - message: string, - nodes?: Array, - stack?: string, - source?: Source, - positions?: Array - ); -} - -export function formatError(error: GraphQLError): GraphQLFormattedError; - -interface GraphQLFormattedError { - message: string, - locations: Array -} - -interface GraphQLErrorLocation { - line: number, - column: number -} - -function locatedError(originalError: Error, nodes: Array): GraphQLError; - -function syntaxError(source: Source, position: number, description: string): GraphQLError; - -// execution/*.js - -interface ExecutionContext { - schema: GraphQLSchema; - fragments: {[key: string]: FragmentDefinition}; - rootValue: any; - operation: OperationDefinition; - variableValues: {[key: string]: any}; - errors: Array; -} - -interface ExecutionResult { - data: any; - errors?: Array; -} - -function execute( - schema: GraphQLSchema, - documentAST: Document, - rootValue?: any, - contextValue?: any, - variableValues?: {[key: string]: any}, - operationName?: string -): Promise; - -function getVariableValues( - schema: GraphQLSchema, - definitionASTs: Array, - inputs: { [key: string]: any } -): { [key: string]: any }; - -function getArgumentValues( - argDefs: Array, - argASTs: Array, - variableValues: { [key: string]: any } -): { [key: string]: any }; - -// validation/*.js - -function validate( - schema: GraphQLSchema, - ast: Document, - rules?: Array -): Array; - -// jsutils/*.js - -function find(list: Array, predicate: (item: T) => boolean): T; -function invariant(condition: any, message: string): void; -function isNullish(value: any): boolean; -function keyMap( - list: Array, - keyFn: (item: T) => string -): {[key: string]: T}; -function keyValMap( - list: Array, - keyFn: (item: T) => string, - valFn: (item: T) => V -): {[key: string]: V} - -// language/ast.js -interface Location { - start: number; - end: number; - source?: Source -} - -type Node = Name - | Document - | OperationDefinition - | VariableDefinition - | Variable - | SelectionSet - | Field - | Argument - | FragmentSpread - | InlineFragment - | FragmentDefinition - | IntValue - | FloatValue - | StringValue - | BooleanValue - | EnumValue - | ListValue - | ObjectValue - | ObjectField - | Directive - | ListType - | NonNullType - | ObjectTypeDefinition - | FieldDefinition - | InputValueDefinition - | InterfaceTypeDefinition - | UnionTypeDefinition - | ScalarTypeDefinition - | EnumTypeDefinition - | EnumValueDefinition - | InputObjectTypeDefinition - | TypeExtensionDefinition; - -interface Name { - kind: string; - loc?: Location; - value: string; -} - -interface Document { - kind: string; - loc?: Location; - definitions: Array; -} - -type Definition = OperationDefinition - | FragmentDefinition - | TypeDefinition; - -interface OperationDefinition { - kind: string; - loc?: Location; - // Note: subscription is an experimental non-spec addition. - operation: string; - name?: Name; - variableDefinitions?: Array; - directives?: Array; - selectionSet: SelectionSet; -} - -interface VariableDefinition { - kind: string; - loc?: Location; - variable: Variable; - type: Type; - defaultValue?: Value; -} - -interface Variable { - kind: string; - loc?: Location; - name: Name; -} - -interface SelectionSet { - kind: string; - loc?: Location; - selections: Array; -} - -type Selection = Field - | FragmentSpread - | InlineFragment; - -interface Field { - kind: string; - loc?: Location; - alias?: Name; - name: Name; - arguments?: Array; - directives?: Array; - selectionSet?: SelectionSet; -} - -interface Argument { - kind: string; - loc?: Location; - name: Name; - value: Value; -} - - -// Fragments - -interface FragmentSpread { - kind: string; - loc?: Location; - name: Name; - directives?: Array; -} - -interface InlineFragment { - kind: string; - loc?: Location; - typeCondition?: NamedType; - directives?: Array; - selectionSet: SelectionSet; -} - -interface FragmentDefinition { - kind: string; - loc?: Location; - name: Name; - typeCondition: NamedType; - directives?: Array; - selectionSet: SelectionSet; -} - - -// Values - -type Value = Variable - | IntValue - | FloatValue - | StringValue - | BooleanValue - | EnumValue - | ListValue - | ObjectValue; - -interface IntValue { - kind: string; - loc?: Location; - value: string; -} - -interface FloatValue { - kind: string; - loc?: Location; - value: string; -} - -interface StringValue { - kind: string; - loc?: Location; - value: string; -} - -interface BooleanValue { -kind: string; -loc?: Location; -value: boolean; -} - -interface EnumValue { - kind: string; - loc?: Location; - value: string; -} - -interface ListValue { - kind: string; - loc?: Location; - values: Array; -} - -interface ObjectValue { - kind: string; - loc?: Location; - fields: Array; -} - -interface ObjectField { - kind: string; - loc?: Location; - name: Name; - value: Value; -} - - -// Directives - -interface Directive { - kind: string; - loc?: Location; - name: Name; - arguments?: Array; -} - - -// Type Reference - -type Type = NamedType - | ListType - | NonNullType; - -interface NamedType { - kind: string; - loc?: Location; - name: Name; -} - -interface ListType { - kind: string; - loc?: Location; - type: Type; -} - -interface NonNullType { - kind: string; - loc?: Location; - type: NamedType | ListType; -} - -// Type Definition - -type TypeDefinition = ObjectTypeDefinition - | InterfaceTypeDefinition - | UnionTypeDefinition - | ScalarTypeDefinition - | EnumTypeDefinition - | InputObjectTypeDefinition - | TypeExtensionDefinition; - -interface ObjectTypeDefinition { - kind: string; - loc?: Location; - name: Name; - interfaces?: Array; - fields: Array; -} - -interface FieldDefinition { - kind: string; - loc?: Location; - name: Name; - arguments: Array; - type: Type; -} - -interface InputValueDefinition { - kind: string; - loc?: Location; - name: Name; - type: Type; - defaultValue?: Value; -} - -interface InterfaceTypeDefinition { - kind: string; - loc?: Location; - name: Name; - fields: Array; -} - -interface UnionTypeDefinition { - kind: string; - loc?: Location; - name: Name; - types: Array; -} - -interface ScalarTypeDefinition { - kind: string; - loc?: Location; - name: Name; -} - -interface EnumTypeDefinition { - kind: string; - loc?: Location; - name: Name; - values: Array; -} - -interface EnumValueDefinition { - kind: string; - loc?: Location; - name: Name; -} - -interface InputObjectTypeDefinition { - kind: string; - loc?: Location; - name: Name; - fields: Array; -} - -interface TypeExtensionDefinition { - kind: string; - loc?: Location; - definition: ObjectTypeDefinition; -} - -// language/kinds.js - -const NAME: string; - -// Document - -const DOCUMENT: string; -const OPERATION_DEFINITION: string; -const VARIABLE_DEFINITION: string; -const VARIABLE: string; -const SELECTION_SET: string; -const FIELD: string; -const ARGUMENT: string; - -// Fragments - -const FRAGMENT_SPREAD: string; -const INLINE_FRAGMENT: string; -const FRAGMENT_DEFINITION: string; - -// Values - -const INT: string; -const FLOAT: string; -const STRING: string; -const BOOLEAN: string; -const ENUM: string; -const LIST: string; -const OBJECT: string; -const OBJECT_FIELD: string; - -// Directives - -const DIRECTIVE: string; - -// Types - -const NAMED_TYPE: string; -const LIST_TYPE: string; -const NON_NULL_TYPE: string; - -// Type Definitions - -const OBJECT_TYPE_DEFINITION: string; -const FIELD_DEFINITION: string; -const INPUT_VALUE_DEFINITION: string; -const INTERFACE_TYPE_DEFINITION: string; -const UNION_TYPE_DEFINITION: string; -const SCALAR_TYPE_DEFINITION: string; -const ENUM_TYPE_DEFINITION: string; -const ENUM_VALUE_DEFINITION: string; -const INPUT_OBJECT_TYPE_DEFINITION: string; -const TYPE_EXTENSION_DEFINITION: string; - -// language/lexer.js - -interface Token { - kind: number; - start: number; - end: number; - value: string; -} - -type Lexer = (resetPosition?: number) => Token; - -function lex(source: Source): Lexer; - -type TokenKind = {[key: string]: number}; - -function getTokenDesc(token: Token): string; -function getTokenKindDesc(kind: number): string; - -// language/location.js - -interface SourceLocation { - line: number; - column: number; -} - -function getLocation(source: Source, position: number): SourceLocation; - -// language/parser.js - -interface ParseOptions { - noLocation?: boolean, - noSource?: boolean, -} - -function parse( - source: Source | string, - options?: ParseOptions -): Document; - -function parseValue( - source: Source | string, - options?: ParseOptions -): Value; - -function parseConstValue(parser: any): Value; - -function parseType(parser: any): Type; - -function parseNamedType(parser: any): NamedType; - -// language/printer.js - -function print(ast: any): string; - -// language/source.js - -class Source { - body: string; - name: string; - constructor(body: string, name?: string); -} - -// language/visitor.js - -interface QueryDocumentKeys { - Name: any[]; - Document: string[]; - OperationDefinition: string[]; - VariableDefinition: string[]; - Variable: string[]; - SelectionSet: string[]; - Field: string[]; - Argument: string[]; - - FragmentSpread: string[]; - InlineFragment: string[]; - FragmentDefinition: string[]; - - IntValue: number[]; - FloatValue: number[]; - StringValue: string[]; - BooleanValue: boolean[]; - EnumValue: any[]; - ListValue: string[]; - ObjectValue: string[]; - ObjectField: string[]; - - Directive: string[]; - - NamedType: string[]; - ListType: string[]; - NonNullType: string[]; - - ObjectTypeDefinition: string[]; - FieldDefinition: string[]; - InputValueDefinition: string[]; - InterfaceTypeDefinition: string[]; - UnionTypeDefinition: string[]; - ScalarTypeDefinition: string[]; - EnumTypeDefinition: string[]; - EnumValueDefinition: string[]; - InputObjectTypeDefinition: string[]; - TypeExtensionDefinition: string[]; -} - -const BREAK: Object; - -function visit(root: any, visitor: any, keyMap: any): any; - -function visitInParallel(visitors: any): any; - -function visitWithTypeInfo(typeInfo: any, visitor: any): any; - -// type/definition.js - -type GraphQLType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList | - GraphQLNonNull; - -function isType(type: any): boolean; - -type GraphQLInputType = - GraphQLScalarType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList | - GraphQLNonNull; - -function isInputType(type: GraphQLType): boolean; - -type GraphQLOutputType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLList | - GraphQLNonNull; - -function isOutputType(type: GraphQLType): boolean; - -type GraphQLLeafType = - GraphQLScalarType | - GraphQLEnumType; - -function isLeafType(type: GraphQLType): boolean; - -type GraphQLCompositeType = - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType; - -function isCompositeType(type: GraphQLType): boolean; - -type GraphQLAbstractType = - GraphQLInterfaceType | - GraphQLUnionType; - -function isAbstractType(type: GraphQLType): boolean; - -type GraphQLNullableType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList; - -function getNullableType(type: GraphQLType): GraphQLNullableType; - -type GraphQLNamedType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType; - -function getNamedType(type: GraphQLType): GraphQLNamedType; - -export class GraphQLScalarType { - constructor(config: GraphQLScalarTypeConfig); - serialize(value: any): any; - parseValue(value: any): any; - parseLiteral(valueAST: Value): any; - toString(): string; -} - -interface GraphQLScalarTypeConfig { - name: string; - description?: string; - serialize: (value: any) => any; - parseValue?: (value: any) => any; - parseLiteral?: (valueAST: Value) => any; -} - -export class GraphQLObjectType { - constructor(config: GraphQLObjectTypeConfig); - getFields(): GraphQLFieldDefinitionMap; - getInterfaces(): Array; - toString(): string; -} - -interface GraphQLObjectTypeConfig { - name: string; - interfaces?: GraphQLInterfacesThunk | Array; - fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap; - isTypeOf?: (value: any, info?: GraphQLResolveInfo) => boolean; - description?: string -} - -type GraphQLInterfacesThunk = () => Array; - -type GraphQLFieldConfigMapThunk = () => GraphQLFieldConfigMap; - -type GraphQLFieldResolveFn = ( - source?: any, - args?: { [argName: string]: any }, - context?: any, - info?: GraphQLResolveInfo -) => any; - -interface GraphQLResolveInfo { - fieldName: string, - fieldASTs: Array, - returnType: GraphQLOutputType, - parentType: GraphQLCompositeType, - schema: GraphQLSchema, - fragments: { [fragmentName: string]: FragmentDefinition }, - rootValue: any, - operation: OperationDefinition, - variableValues: { [variableName: string]: any }, -} - -interface GraphQLFieldConfig { - type: GraphQLOutputType; - args?: GraphQLFieldConfigArgumentMap; - resolve?: GraphQLFieldResolveFn; - deprecationReason?: string; - description?: string; -} - -interface GraphQLFieldConfigArgumentMap { - [argName: string]: GraphQLArgumentConfig; -} - -interface GraphQLArgumentConfig { - type: GraphQLInputType; - defaultValue?: any; - description?: string; -} - -interface GraphQLFieldConfigMap { - [fieldName: string]: GraphQLFieldConfig; -} - -interface GraphQLFieldDefinition { - name: string; - description: string; - type: GraphQLOutputType; - args: Array; - resolve?: GraphQLFieldResolveFn; - deprecationReason?: string; -} - -interface GraphQLArgument { - name: string; - type: GraphQLInputType; - defaultValue?: any; - description?: string; -} - -interface GraphQLFieldDefinitionMap { - [fieldName: string]: GraphQLFieldDefinition; -} - -export class GraphQLInterfaceType { - name: string; - description: string; - resolveType: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType; - constructor(config: GraphQLInterfaceTypeConfig); - getFields(): GraphQLFieldDefinitionMap; - getPossibleTypes(): Array; - isPossibleType(type: GraphQLObjectType): boolean; - getObjectType(value: any, info: GraphQLResolveInfo): GraphQLObjectType; - toString(): string; -} - -interface GraphQLInterfaceTypeConfig { - name: string; - fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap; - resolveType?: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType; - description?: string; -} - -export class GraphQLUnionType { - name: string; - description: string; - resolveType: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType; - constructor(config: GraphQLUnionTypeConfig); - getPossibleTypes(): Array; - isPossibleType(type: GraphQLObjectType): boolean; - getObjectType(value: any, info: GraphQLResolveInfo): GraphQLObjectType; - toString(): string; -} - - -interface GraphQLUnionTypeConfig { - name: string, - types: Array, - /** - * Optionally provide a custom type resolver function. If one is not provided, - * the default implementation will call `isTypeOf` on each implementing - * Object type. - */ - resolveType?: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType; - description?: string; -} - -export class GraphQLEnumType { - name: string; - description: string; - constructor(config: GraphQLEnumTypeConfig); - getValues(): Array; - serialize(value: any): string; - parseValue(value: any): any; - parseLiteral(valueAST: Value): any; - toString(): string; -} - -interface GraphQLEnumTypeConfig { - name: string; - values: GraphQLEnumValueConfigMap; - description?: string; -} - -interface GraphQLEnumValueConfigMap { - [valueName: string]: GraphQLEnumValueConfig; -} - -interface GraphQLEnumValueConfig { - value?: any; - deprecationReason?: string; - description?: string; -} - -interface GraphQLEnumValueDefinition { - name: string; - description: string; - deprecationReason: string; - value: any; -} - -export class GraphQLInputObjectType { - name: string; - description: string; - constructor(config: InputObjectConfig); - getFields(): InputObjectFieldMap; - toString(): string; -} - -interface InputObjectConfig { - name: string; - fields: InputObjectConfigFieldMapThunk | InputObjectConfigFieldMap; - description?: string; -} - -type InputObjectConfigFieldMapThunk = () => InputObjectConfigFieldMap; - -interface InputObjectFieldConfig { - type: GraphQLInputType; - defaultValue?: any; - description?: string; -} - -interface InputObjectConfigFieldMap { - [fieldName: string]: InputObjectFieldConfig; -} - -interface InputObjectField { - name: string; - type: GraphQLInputType; - defaultValue?: any; - description?: string; -} - -interface InputObjectFieldMap { - [fieldName: string]: InputObjectField; -} - -export class GraphQLList { - ofType: GraphQLType; - constructor(type: GraphQLType); - toString(): string; -} - -export class GraphQLNonNull { - ofType: GraphQLNullableType; - constructor(type: GraphQLNullableType); - toString(): string; -} - -// type/directives.js - -class GraphQLDirective { - name: string; - description: string; - args: Array; - onOperation: boolean; - onFragment: boolean; - onField: boolean; - constructor(config: GraphQLDirectiveConfig); -} - -interface GraphQLDirectiveConfig { - name: string; - description?: string; - args?: Array; - onOperation?: boolean; - onFragment?: boolean; - onField?: boolean; -} - -export var GraphQLIncludeDirective: GraphQLDirective; - -export var GraphQLSkipDirective: GraphQLDirective; - -// type/introspection.js - -var __Schema: GraphQLObjectType; - -type TypeKind = {[key: string]: string}; - -var SchemaMetaFieldDef: GraphQLFieldDefinition; - -var TypeMetaFieldDef: GraphQLFieldDefinition; - -var TypeNameMetaFieldDef: GraphQLFieldDefinition; - -// type/scalars.js - -export var GraphQLInt: GraphQLScalarType; -export var GraphQLFloat: GraphQLScalarType; -export var GraphQLString: GraphQLScalarType; -export var GraphQLBoolean: GraphQLScalarType; -export var GraphQLID: GraphQLScalarType; - -// type/schema.js - -export class GraphQLSchema { - constructor(config: GraphQLSchemaConfig); - getQueryType(): GraphQLObjectType; - getMutationType(): GraphQLObjectType; - getSubscriptionType(): GraphQLObjectType; - getTypeMap(): TypeMap; - getType(name: string): GraphQLType; - getDirectives(): Array; - getDirective(name: string): GraphQLDirective; -} - -type TypeMap = { [typeName: string]: GraphQLType }; - -interface GraphQLSchemaConfig { - query: GraphQLObjectType; - mutation?: GraphQLObjectType; - subscription?: GraphQLObjectType; - directives?: Array; -} -} -declare module 'graphql/graphql' { -import alias = require('~graphql/graphql'); -export = alias; -} -declare module 'graphql' { -import alias = require('~graphql/graphql'); -export = alias; -} diff --git a/typings/modules/graphql/typings.json b/typings/modules/graphql/typings.json deleted file mode 100644 index 33d53d367..000000000 --- a/typings/modules/graphql/typings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://github.com/raw/nitintutlani/typed-graphql/master/typings.json", - "raw": "github:nitintutlani/typed-graphql", - "main": "graphql.d.ts", - "global": false, - "name": "graphql", - "type": "typings" - } -} From 849b762bd2ec87c450384fc1619893f5a061fb6c Mon Sep 17 00:00:00 2001 From: nnance Date: Sun, 12 Jun 2016 22:41:46 -0700 Subject: [PATCH 2/8] initial express bindings commit --- package.json | 1 + src/bindings/expressApollo.test.ts | 43 ++++++++++++++++++++++++++++++ src/bindings/expressApollo.ts | 28 +++++++++++++++++++ src/test/tests.ts | 1 + 4 files changed, 73 insertions(+) create mode 100644 src/bindings/expressApollo.test.ts create mode 100644 src/bindings/expressApollo.ts diff --git a/package.json b/package.json index 6c26a4908..bc25cae61 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "homepage": "https://github.com/apollostack/apollo-proxy#readme", "dependencies": { "es6-promise": "^3.2.1", + "express": "^4.13.4", "graphql": "^0.6.0", "source-map-support": "^0.4.0" }, diff --git a/src/bindings/expressApollo.test.ts b/src/bindings/expressApollo.test.ts new file mode 100644 index 000000000..3d0ffcab1 --- /dev/null +++ b/src/bindings/expressApollo.test.ts @@ -0,0 +1,43 @@ +import { + assert, +} from 'chai'; + +// XXX can be removed after tests are actually writen +/* tslint:disable:no-unused-variable */ +import { + GraphQLSchema, + GraphQLObjectType, + GraphQLString, +} from 'graphql'; + +import expressApollo from './expressApollo'; + +const QueryType = new GraphQLObjectType({ + name: 'QueryType', + fields: { + testString: { + type: GraphQLString, + resolve() { + return 'it works'; + }, + }, + }, +}); + +const Schema = new GraphQLSchema({ + query: QueryType, +}); +// XXX can be removed after tests are actually writen +/* tslint:enable:no-unused-variable */ + +describe('expressApollo', () => { + it('returns express middleware', () => { + // XXX can be removed after tests are actually writen + // tslint:disable-next-line:no-unused-variable + const query = `{ testString }`; + const middleware = expressApollo({ + schema: Schema, + }); + assert(typeof middleware === 'function'); + }); +}); diff --git a/src/bindings/expressApollo.ts b/src/bindings/expressApollo.ts new file mode 100644 index 000000000..199b9b557 --- /dev/null +++ b/src/bindings/expressApollo.ts @@ -0,0 +1,28 @@ +import * as express from 'express'; +import * as graphql from 'graphql'; +// TODO: can be removed after tests are actually writen +/* tslint:disable:no-unused-variable */ +import runQuery from '../core/runQuery'; + +export interface ExpressBindings { + schema: graphql.GraphQLSchema; +} + +export default function(options: ExpressBindings) { + if (!options) { + throw new Error('GraphQL middleware requires options.'); + } + if (arguments.length > 1) { + throw new Error(`apolloServer expects exactly one argument, got ${arguments.length + 1}`); + } + return (req: express.Request, res: express.Response, next) => { + // const gqlResponse = runQuery(options.schema) + // + // res.set('Content-Type', 'application/json'); + // if (gqlResponse.errors) { + // res.send(gqlResponse.errorCode, { errors: gqlResponse.errors }) + // } else { + // res.send({ data: gqlResponse.data }) + // } + }; +} diff --git a/src/test/tests.ts b/src/test/tests.ts index fbf6335e4..67b62cc9f 100644 --- a/src/test/tests.ts +++ b/src/test/tests.ts @@ -8,3 +8,4 @@ declare function require(name: string); require('source-map-support').install(); import '../core/runQuery.test'; +import '../bindings/express/expressApollo.test'; From 1ee3119e400ebbe496b716bafcfd8ba3718a2faa Mon Sep 17 00:00:00 2001 From: Nick Nance Date: Tue, 14 Jun 2016 12:03:53 -0700 Subject: [PATCH 3/8] basic working express middleware and export it --- src/bindings/expressApollo.ts | 25 +++++++++++++------------ src/index.ts | 3 +++ 2 files changed, 16 insertions(+), 12 deletions(-) create mode 100644 src/index.ts diff --git a/src/bindings/expressApollo.ts b/src/bindings/expressApollo.ts index 199b9b557..c08a35f60 100644 --- a/src/bindings/expressApollo.ts +++ b/src/bindings/expressApollo.ts @@ -1,8 +1,6 @@ import * as express from 'express'; import * as graphql from 'graphql'; -// TODO: can be removed after tests are actually writen -/* tslint:disable:no-unused-variable */ -import runQuery from '../core/runQuery'; +import { runQuery } from '../core/runQuery'; export interface ExpressBindings { schema: graphql.GraphQLSchema; @@ -12,17 +10,20 @@ export default function(options: ExpressBindings) { if (!options) { throw new Error('GraphQL middleware requires options.'); } + if (arguments.length > 1) { throw new Error(`apolloServer expects exactly one argument, got ${arguments.length + 1}`); } + return (req: express.Request, res: express.Response, next) => { - // const gqlResponse = runQuery(options.schema) - // - // res.set('Content-Type', 'application/json'); - // if (gqlResponse.errors) { - // res.send(gqlResponse.errorCode, { errors: gqlResponse.errors }) - // } else { - // res.send({ data: gqlResponse.data }) - // } - }; + runQuery({ + schema: options.schema, + query: req.body, + }).then(gqlResponse => { + res.set('Content-Type', 'application/json'); + res.send({ data: gqlResponse.data }); + }).catch(gqlResponse => { + res.send(gqlResponse.errorCode, { errors: gqlResponse.errors }); + }); + }; } diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 000000000..0fc1cf422 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,3 @@ +import expressApollo from './bindings/expressApollo'; + +export { expressApollo }; From 4e9bf5cc613e6129e2a7ce62f90ca21a6649f081 Mon Sep 17 00:00:00 2001 From: Nick Nance Date: Tue, 14 Jun 2016 12:04:28 -0700 Subject: [PATCH 4/8] update tsc build to use es5 --- package.json | 4 ++++ src/core/runQuery.ts | 2 ++ tsconfig.json | 2 +- typings.json | 1 + 4 files changed, 8 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index d8486ec4a..a82cc3f21 100644 --- a/package.json +++ b/package.json @@ -57,5 +57,9 @@ }, "peerDependencies": { "graphql": "^0.6.0" + }, + "typings": "dist/index.d.ts", + "typescript": { + "definition": "dist/index.d.ts" } } diff --git a/src/core/runQuery.ts b/src/core/runQuery.ts index 9afca710f..ad68c06e5 100644 --- a/src/core/runQuery.ts +++ b/src/core/runQuery.ts @@ -7,6 +7,8 @@ import { execute, } from 'graphql'; +import { Promise } from 'es6-promise'; + export interface GqlResponse { data?: Object; errors?: Array; diff --git a/tsconfig.json b/tsconfig.json index 877ec8b84..14595d651 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "target": "es6", + "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, diff --git a/typings.json b/typings.json index ced971d43..ab304d641 100644 --- a/typings.json +++ b/typings.json @@ -4,6 +4,7 @@ "graphql": "github:nitintutlani/typed-graphql" }, "globalDependencies": { + "es6-promise": "registry:dt/es6-promise#0.0.0+20160317120654", "body-parser": "registry:dt/body-parser#0.0.0+20160317120654", "express": "registry:dt/express#4.0.0+20160317120654", "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", From a39970250c377018c50a39ed0aad998c47e36d2e Mon Sep 17 00:00:00 2001 From: Nick Nance Date: Tue, 14 Jun 2016 12:07:56 -0700 Subject: [PATCH 5/8] create basic documentation --- src/bindings/README.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/bindings/README.md diff --git a/src/bindings/README.md b/src/bindings/README.md new file mode 100644 index 000000000..745286138 --- /dev/null +++ b/src/bindings/README.md @@ -0,0 +1,31 @@ +# expressApollo + +An Express Middleware for the Apollo Server + +## Example Usage + +```js +import * as express from "express"; +import * as bodyParser from "body-parser"; +import { expressApollo } from "apollo-server"; +import schema from "./data/schema"; +import * as graphql from 'graphql' + +const port = 3000; +const app = express(); +const schema = new graphql.GraphQLSchema({ + query: new graphql.GraphQLObjectType({ + name: 'Query', + fields: { + testString: { type: graphql.GraphQLString } + } + }) +}); + +app.use(bodyParser.text()); +app.use("/", expressApollo({schema})); + +app.listen(port, () => { + console.log(`Server is listen on ${port}`); +}); +``` From d6e41e0fdf14d06880c42ed3d5c9f6460ca58f67 Mon Sep 17 00:00:00 2001 From: Nick Nance Date: Tue, 14 Jun 2016 12:18:22 -0700 Subject: [PATCH 6/8] fix tests --- src/test/tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/tests.ts b/src/test/tests.ts index 67b62cc9f..d8b668dac 100644 --- a/src/test/tests.ts +++ b/src/test/tests.ts @@ -8,4 +8,4 @@ declare function require(name: string); require('source-map-support').install(); import '../core/runQuery.test'; -import '../bindings/express/expressApollo.test'; +import '../bindings/expressApollo.test'; From fab2c844cf7a018b31275bd71cf2a7790b18824d Mon Sep 17 00:00:00 2001 From: Nick Nance Date: Tue, 14 Jun 2016 12:20:14 -0700 Subject: [PATCH 7/8] fix linting --- src/bindings/README.md => integrations.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/bindings/README.md => integrations.md (100%) diff --git a/src/bindings/README.md b/integrations.md similarity index 100% rename from src/bindings/README.md rename to integrations.md From fcf1376added4898c03d55ad573f77e49101e01d Mon Sep 17 00:00:00 2001 From: Nick Nance Date: Tue, 14 Jun 2016 12:21:44 -0700 Subject: [PATCH 8/8] use integrations now --- src/index.ts | 2 +- src/{bindings => integrations}/expressApollo.test.ts | 0 src/{bindings => integrations}/expressApollo.ts | 0 src/test/tests.ts | 2 +- 4 files changed, 2 insertions(+), 2 deletions(-) rename src/{bindings => integrations}/expressApollo.test.ts (100%) rename src/{bindings => integrations}/expressApollo.ts (100%) diff --git a/src/index.ts b/src/index.ts index 0fc1cf422..e83a2f956 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,3 @@ -import expressApollo from './bindings/expressApollo'; +import expressApollo from './integrations/expressApollo'; export { expressApollo }; diff --git a/src/bindings/expressApollo.test.ts b/src/integrations/expressApollo.test.ts similarity index 100% rename from src/bindings/expressApollo.test.ts rename to src/integrations/expressApollo.test.ts diff --git a/src/bindings/expressApollo.ts b/src/integrations/expressApollo.ts similarity index 100% rename from src/bindings/expressApollo.ts rename to src/integrations/expressApollo.ts diff --git a/src/test/tests.ts b/src/test/tests.ts index d8b668dac..a133ba2de 100644 --- a/src/test/tests.ts +++ b/src/test/tests.ts @@ -8,4 +8,4 @@ declare function require(name: string); require('source-map-support').install(); import '../core/runQuery.test'; -import '../bindings/expressApollo.test'; +import '../integrations/expressApollo.test';