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 - * - `root` root directory for relative filenames - * - * 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.'); - * } - * }); - * }); - */ - sendfile(path: string): void; - - sendfile(path: string, options: any): void; - - sendfile(path: string, fn: Errback): void; - - 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; - - /** - * 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; - } - - export interface RequestFunction { - (req: Request, res: Response, next: Function): any; - } - - export interface Application extends IRouterviews: ' + sess.views + '
'); - * res.write('expires in: ' + (sess.cookie.maxAge / 1000) + 's
'); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param options - */ - export function session(options?: any): Handler; + * Regenerate this request's session. + */ + regenerate(fn: Function): Session; + + user: any; + + error: string; + + success: string; + + views: any; + + count: number; + } + + export interface Request { + + session: Session; /** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param sess - */ - export function hash(sess: string): string; + * 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: string[]; /** - * Static: - * - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect() - * .use(connect.static(__dirname + '/public')) - * - * connect() - * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true - * - * @param root - * @param options - */ - export function static(root: string, options?: any): Handler; + * 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; /** - * Basic Auth: - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param callback or username - * @param realm - */ - export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; - - export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; - - export function basicAuth(user: string, pass: string, realm?: string): Handler; + * Check if the given `charset` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param charset + */ + acceptsCharset(charset: string): boolean; /** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param options - */ - export function compress(options?: any): Handler; + * Check if the given `lang` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param lang + */ + acceptsLanguage(lang: string): boolean; /** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * @param options - */ - export function cookieSession(options?: any): Handler; + * 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[]; /** - * Anti CSRF: - * - * CSRF protection middleware. - * - * This middleware adds a `req.csrfToken()` function to make a token - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's session. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param options - */ - export function csrf(options?: {value?: Function}): Handler; + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; /** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param root - * @param options - */ - export function directory(root: string, options?: any): Handler; + * Return an array of Accepted languages + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Language: en;q=.5, en-us + * ['en-us', 'en'] + */ + acceptedLanguages: any[]; /** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico)) - * - * @param path - * @param options - */ - export function favicon(path?: string, options?: any): Handler; + * Return an array of Accepted charsets + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 + * ['unicode-1-1', 'iso-8859-5'] + */ + acceptedCharsets: any[]; /** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit disabled by default - * - * @param options - */ - export function json(options?: any): Handler; + * 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; /** - * Limit: - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - */ - export function limit(bytes: number): Handler; - - export function limit(bytes: string): Handler; + * 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; /** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - */ - export function logger(options: string): Handler; - - export function logger(options: Function): Handler; - - export function logger(options?: any): Handler; + * 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; /** - * Compile `fmt` into a function. - * - * @param fmt - */ - export function compile(fmt: string): Handler; + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; /** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param name - * @param fn - */ - export function token(name: string, fn: Function): any; + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; /** - * Define a `fmt` with the given `name`. - */ - export function format(name: string, str: string): any; - - export function format(name: string, str: Function): any; + * 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[]; /** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - */ - export function query(options: any): Handler; + * Return basic auth credentials. + * + * Examples: + * + * // http://tobi:hello@example.com + * req.auth + * // => { username: 'tobi', password: 'hello' } + */ + auth: any; /** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - */ - export function responseTime(): Handler; + * 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[]; /** - * Static cache: - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - */ - export function staticCache(options: any): Handler; + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; /** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 408`. - */ - export function timeout(ms: number): Handler; + * Parse the "Host" header field hostname. + */ + host: string; /** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param hostname - * @param server - */ - export function vhost(hostname: string, server: any): Handler; + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; - export function urlencoded(): any; + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; - export function multipart(): any; + /** + * 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; + + /** + * Used to generate an anti-CSRF token. + * Placed by the CSRF protection middleware. + */ + csrfToken(): string; + + method: string; + + params: any; + + user: any; + + authenticatedUser: any; + + files: any; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + query: any; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + } + + export interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; + } + + export interface Send { + (status: number, body?: any): Response; + (body: any): Response; + } + + export interface Response extends NodeJs.Http.ServerResponse { + /** + * Set status `code`. + * + * @param code + */ + status(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 + * - `root` root directory for relative filenames + * + * 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.'); + * } + * }); + * }); + */ + sendfile(path: string): void; + + sendfile(path: string, options: any): void; + + sendfile(path: string, fn: Errback): void; + + 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; + + /** + * 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; + } + + export interface RequestFunction { + (req: Request, res: Response, next: Function): any; + } + + export interface Application extends IRouterviews: ' + sess.views + '
'); + * res.write('expires in: ' + (sess.cookie.maxAge / 1000) + 's
'); + * res.end(); + * sess.views++; + * } else { + * sess.views = 1; + * res.end('welcome to the session demo. refresh!'); + * } + * } + * )).listen(3000); + * + * ## Session#regenerate() + * + * To regenerate the session simply invoke the method, once complete + * a new SID and `Session` instance will be initialized at `req.session`. + * + * req.session.regenerate(function(err){ + * // will have a new session here + * }); + * + * ## Session#destroy() + * + * Destroys the session, removing `req.session`, will be re-generated next request. + * + * req.session.destroy(function(err){ + * // cannot access session here + * }); + * + * ## Session#reload() + * + * Reloads the session data. + * + * req.session.reload(function(err){ + * // session updated + * }); + * + * ## Session#save() + * + * Save the session. + * + * req.session.save(function(err){ + * // session saved + * }); + * + * ## Session#touch() + * + * Updates the `.maxAge` property. Typically this is + * not necessary to call, as the session middleware does this for you. + * + * ## Session#cookie + * + * Each session has a unique cookie object accompany it. This allows + * you to alter the session cookie per visitor. For example we can + * set `req.session.cookie.expires` to `false` to enable the cookie + * to remain for only the duration of the user-agent. + * + * ## Session#maxAge + * + * Alternatively `req.session.cookie.maxAge` will return the time + * remaining in milliseconds, which we may also re-assign a new value + * to adjust the `.expires` property appropriately. The following + * are essentially equivalent + * + * var hour = 3600000; + * req.session.cookie.expires = new Date(Date.now() + hour); + * req.session.cookie.maxAge = hour; + * + * For example when `maxAge` is set to `60000` (one minute), and 30 seconds + * has elapsed it will return `30000` until the current request has completed, + * at which time `req.session.touch()` is called to reset `req.session.maxAge` + * to its original value. + * + * req.session.cookie.maxAge; + * // => 30000 + * + * Session Store Implementation: + * + * Every session store _must_ implement the following methods + * + * - `.get(sid, callback)` + * - `.set(sid, session, callback)` + * - `.destroy(sid, callback)` + * + * Recommended methods include, but are not limited to: + * + * - `.length(callback)` + * - `.clear(callback)` + * + * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. + * + * @param options + */ + session(options?: any): Express.Handler; + + /** + * Hash the given `sess` object omitting changes + * to `.cookie`. + * + * @param sess + */ + hash(sess: string): string; + + /** + * Static: + * + * Static file server with the given `root` path. + * + * Examples: + * + * var oneDay = 86400000; + * + * connect() + * .use(connect.static(__dirname + '/public')) + * + * connect() + * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) + * + * Options: + * + * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 + * - `hidden` Allow transfer of hidden files. defaults to false + * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true + * + * @param root + * @param options + */ + static(root: string, options?: any): Express.Handler; + + /** + * Basic Auth: + * + * Enfore basic authentication by providing a `callback(user, pass)`, + * which must return `true` in order to gain access. Alternatively an async + * method is provided as well, invoking `callback(user, pass, callback)`. Populates + * `req.user`. The final alternative is simply passing username / password + * strings. + * + * Simple username and password + * + * connect(connect.basicAuth('username', 'password')); + * + * Callback verification + * + * connect() + * .use(connect.basicAuth(function(user, pass){ + * return 'tj' == user & 'wahoo' == pass; + * })) + * + * Async callback verification, accepting `fn(err, user)`. + * + * connect() + * .use(connect.basicAuth(function(user, pass, fn){ + * User.authenticate({ user: user, pass: pass }, fn); + * })) + * + * @param callback or username + * @param realm + */ + basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Express.Handler; + + basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Express.Handler; + + basicAuth(user: string, pass: string, realm?: string): Express.Handler; + + /** + * Compress: + * + * Compress response data with gzip/deflate. + * + * Filter: + * + * A `filter` callback function may be passed to + * replace the default logic of: + * + * exports.filter = function(req, res){ + * return /json|text|javascript/.test(res.getHeader('Content-Type')); + * }; + * + * Options: + * + * All remaining options are passed to the gzip/deflate + * creation functions. Consult node's docs for additional details. + * + * - `chunkSize` (default: 16*1024) + * - `windowBits` + * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression + * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more + * - `strategy`: compression strategy + * + * @param options + */ + compress(options?: any): Express.Handler; + + /** + * Cookie Session: + * + * Cookie session middleware. + * + * var app = connect(); + * app.use(connect.cookieParser()); + * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); + * + * Options: + * + * - `key` cookie name defaulting to `connect.sess` + * - `secret` prevents cookie tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Clearing sessions: + * + * To clear the session simply set its value to `null`, + * `cookieSession()` will then respond with a 1970 Set-Cookie. + * + * req.session = null; + * + * @param options + */ + cookieSession(options?: any): Express.Handler; + + /** + * Anti CSRF: + * + * CSRF protection middleware. + * + * This middleware adds a `req.csrfToken()` function to make a token + * which should be added to requests which mutate + * state, within a hidden form field, query-string etc. This + * token is validated against the visitor's session. + * + * The default `value` function checks `req.body` generated + * by the `bodyParser()` middleware, `req.query` generated + * by `query()`, and the "X-CSRF-Token" header field. + * + * This middleware requires session support, thus should be added + * somewhere _below_ `session()` and `cookieParser()`. + * + * Options: + * + * - `value` a function accepting the request, returning the token + * + * @param options + */ + csrf(options?: {value?: Function}): Express.Handler; + + /** + * Directory: + * + * Serve directory listings with the given `root` path. + * + * Options: + * + * - `hidden` display hidden (dot) files. Defaults to false. + * - `icons` display icons. Defaults to false. + * - `filter` Apply this filter function to files. Defaults to false. + * + * @param root + * @param options + */ + directory(root: string, options?: any): Express.Handler; + + /** + * Favicon: + * + * By default serves the connect favicon, or the favicon + * located by the given `path`. + * + * Options: + * + * - `maxAge` cache-control max-age directive, defaulting to 1 day + * + * Examples: + * + * Serve default favicon: + * + * connect() + * .use(connect.favicon()) + * + * Serve favicon before logging for brevity: + * + * connect() + * .use(connect.favicon()) + * .use(connect.logger('dev')) + * + * Serve custom favicon: + * + * connect() + * .use(connect.favicon('public/favicon.ico)) + * + * @param path + * @param options + */ + favicon(path?: string, options?: any): Express.Handler; + + /** + * JSON: + * + * Parse JSON request bodies, providing the + * parsed object as `req.body`. + * + * Options: + * + * - `strict` when `false` anything `JSON.parse()` accepts will be parsed + * - `reviver` used as the second "reviver" argument for JSON.parse + * - `limit` byte limit disabled by default + * + * @param options + */ + json(options?: any): Express.Handler; + + /** + * Limit: + * + * Limit request bodies to the given size in `bytes`. + * + * A string representation of the bytesize may also be passed, + * for example "5mb", "200kb", "1gb", etc. + * + * connect() + * .use(connect.limit('5.5mb')) + * .use(handleImageUpload) + */ + limit(bytes: number): Express.Handler; + + limit(bytes: string): Express.Handler; + + /** + * Logger: + * + * Log requests with the given `options` or a `format` string. + * + * Options: + * + * - `format` Format string, see below for tokens + * - `stream` Output stream, defaults to _stdout_ + * - `buffer` Buffer duration, defaults to 1000ms when _true_ + * - `immediate` Write log line on request instead of response (for response times) + * + * Tokens: + * + * - `:req[header]` ex: `:req[Accept]` + * - `:res[header]` ex: `:res[Content-Length]` + * - `:http-version` + * - `:response-time` + * - `:remote-addr` + * - `:date` + * - `:method` + * - `:url` + * - `:referrer` + * - `:user-agent` + * - `:status` + * + * Formats: + * + * Pre-defined formats that ship with connect: + * + * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' + * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' + * - `tiny` ':method :url :status :res[content-length] - :response-time ms' + * - `dev` concise output colored by response status for development use + * + * Examples: + * + * connect.logger() // default + * connect.logger('short') + * connect.logger('tiny') + * connect.logger({ immediate: true, format: 'dev' }) + * connect.logger(':method :url - :referrer') + * connect.logger(':req[content-type] -> :res[content-type]') + * connect.logger(function(tokens, req, res){ return 'some format string' }) + * + * Defining Tokens: + * + * To define a token, simply invoke `connect.logger.token()` with the + * name and a callback function. The value returned is then available + * as ":type" in this case. + * + * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) + * + * Defining Formats: + * + * All default formats are defined this way, however it's public API as well: + * + * connect.logger.format('name', 'string or function') + */ + logger(options: string): Express.Handler; + + logger(options: Function): Express.Handler; + + logger(options?: any): Express.Handler; + + /** + * Compile `fmt` into a function. + * + * @param fmt + */ + compile(fmt: string): Express.Handler; + + /** + * Define a token function with the given `name`, + * and callback `fn(req, res)`. + * + * @param name + * @param fn + */ + token(name: string, fn: Function): any; + + /** + * Define a `fmt` with the given `name`. + */ + format(name: string, str: string): any; + + format(name: string, str: Function): any; + + /** + * Query: + * + * Automatically parse the query-string when available, + * populating the `req.query` object. + * + * Examples: + * + * connect() + * .use(connect.query()) + * .use(function(req, res){ + * res.end(JSON.stringify(req.query)); + * }); + * + * The `options` passed are provided to qs.parse function. + */ + query(options: any): Express.Handler; + + /** + * Reponse time: + * + * Adds the `X-Response-Time` header displaying the response + * duration in milliseconds. + */ + responseTime(): Express.Handler; + + /** + * Static cache: + * + * Enables a memory cache layer on top of + * the `static()` middleware, serving popular + * static files. + * + * By default a maximum of 128 objects are + * held in cache, with a max of 256k each, + * totalling ~32mb. + * + * A Least-Recently-Used (LRU) cache algo + * is implemented through the `Cache` object, + * simply rotating cache objects as they are + * hit. This means that increasingly popular + * objects maintain their positions while + * others get shoved out of the stack and + * garbage collected. + * + * Benchmarks: + * + * static(): 2700 rps + * node-static: 5300 rps + * static() + staticCache(): 7500 rps + * + * Options: + * + * - `maxObjects` max cache objects [128] + * - `maxLength` max cache object length 256kb + */ + staticCache(options: any): Express.Handler; + + /** + * Timeout: + * + * Times out the request in `ms`, defaulting to `5000`. The + * method `req.clearTimeout()` is added to revert this behaviour + * programmatically within your application's middleware, routes, etc. + * + * The timeout error is passed to `next()` so that you may customize + * the response behaviour. This error has the `.timeout` property as + * well as `.status == 408`. + */ + timeout(ms: number): Express.Handler; + + /** + * Vhost: + * + * Setup vhost for the given `hostname` and `server`. + * + * connect() + * .use(connect.vhost('foo.com', fooApp)) + * .use(connect.vhost('bar.com', barApp)) + * .use(connect.vhost('*.com', mainApp)) + * + * The `server` may be a Connect server or + * a regular Node `http.Server`. + * + * @param hostname + * @param server + */ + vhost(hostname: string, server: any): Express.Handler; + + urlencoded(): any; + + multipart(): any; +} diff --git a/node/node.d.ts b/node/node.d.ts index 25e6c45f2..bb70b7d01 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -219,38 +219,106 @@ interface NodeTimer { unref() : void; } + /************************************************ * * * MODULES - EXTERNAL * * * ************************************************/ -declare module "querystring" { import _ = NodeJs.QueryString; export = _; } -declare module "events" { import _ = NodeJs.Events; export = _; } -declare module "http" { import _ = NodeJs.Http; export = _; } -declare module "cluster" { import _ = NodeJs.Cluster; export = _; } -declare module "zlib" { import _ = NodeJs.Zlib; export = _; } -declare module "os" { import _ = NodeJs.Os; export = _; } -declare module "https" { import _ = NodeJs.Https; export = _; } -declare module "punycode" { import _ = NodeJs.PunyCode; export = _; } -declare module "repl" { import _ = NodeJs.Repl; export = _; } -declare module "readline" { import _ = NodeJs.ReadLine; export = _; } -declare module "vm" { import _ = NodeJs.Vm; export = _; } -declare module "child_process" { import _ = NodeJs.ChildProcess; export = _; } -declare module "url" { import _ = NodeJs.Url; export = _; } -declare module "dns" { import _ = NodeJs.Dns; export = _; } -declare module "net" { import _ = NodeJs.Net; export = _; } -declare module "dgram" { import _ = NodeJs.Dgram; export = _; } -declare module "fs" { import _ = NodeJs.Fs; export = _; } -declare module "path" { import _ = NodeJs.Path; export = _; } -declare module "string_decoder" { import _ = NodeJs.StringDecoder; export = _; } -declare module "tls" { import _ = NodeJs.Tls; export = _; } -declare module "crypto" { import _ = NodeJs.Crypto; export = _; } -declare module "stream" { import _ = NodeJs.Stream; export = _; } -declare module "util" { import _ = NodeJs.Util; export = _; } -declare module "assert" { import _ = NodeJs.Assert; export = _; } -declare module "tty" { import _ = NodeJs.Tty; export = _; } -declare module "domain" { import _ = NodeJs.Domain; export = _; } +declare module "events" { import M = _ExternalShim_._NodeJs_.Events; export = M; } +declare module "http" { import M = _ExternalShim_._NodeJs_.Http; export = M; } +declare module "url" { import M = _ExternalShim_._NodeJs_.Url; export = M; } +declare module "net" { import M = _ExternalShim_._NodeJs_.Net; export = M; } +declare module "querystring" { var M: NodeJs.QueryString; export = M; } +declare module "cluster" { var M: NodeJs.Cluster; export = M; } +declare module "zlib" { var M: NodeJs.Zlib; export = M; } +declare module "os" { var M: NodeJs.Os; export = M; } +declare module "https" { var M: NodeJs.Https; export = M; } +declare module "punycode" { var M: NodeJs.PunyCode; export = M; } +declare module "repl" { var M: NodeJs.Repl; export = M; } +declare module "readline" { var M: NodeJs.ReadLine; export = M; } +declare module "vm" { var M: NodeJs.Vm; export = M; } +declare module "child_process" { var M: NodeJs.ChildProcess; export = M; } +declare module "dns" { var M: NodeJs.Dns; export = M; } +declare module "dgram" { var M: NodeJs.Dgram; export = M; } +declare module "fs" { var M: NodeJs.Fs; export = M; } +declare module "path" { var M: NodeJs.Path; export = M; } +declare module "string_decoder" { var M: NodeJs.StringDecoder; export = M; } +declare module "tls" { var M: NodeJs.Tls; export = M; } +declare module "crypto" { var M: NodeJs.Crypto; export = M; } +declare module "stream" { var M: NodeJs.Stream; export = M; } +declare module "util" { var M: NodeJs.Util; export = M; } +declare module "assert" { var M: NodeJs.Assert; export = M; } +declare module "tty" { var M: NodeJs.Tty; export = M; } +declare module "domain" { var M: NodeJs.Domain; export = M; } + + +/************************************************ +* * +* EXTERNAL - INTERNAL SHIM * +* * +************************************************/ + +// NB: This module exists so that 'pure' (ie non-instantiated) internal modules may +// be declared in parallel with external modules, without breaking code that relies +// on certain behaviours of external modules. It's a shim to support type definitions +// that are already out there which use the pattern exemplified below: +// +// declare module "mymodule" { +// import http = require('http'); +// ... +// server?: http.Server; +// +// Note that the type 'Server' is accessed via the variable 'http', meaning that +// Server must be not just a type, but also a property on 'http'. The 'pure' typings +// declared in the NodeJs module below don't support this usage. With the _ExternalTypes_ +// shim, the above code will continue working unchanged. New type definitions should +// prefer something like: +// +// declare module "mymodule" { +// ... +// server?: NodeJs.Http.Server; +// +// If all typings switch to using the pure internal types in NodeJs, this shim can be removed. + +declare module _ExternalShim_ { + export module _NodeJs_ { + export module Events { + export class EventEmitter implements NodeEventEmitter { + static listenerCount(emitter: EventEmitter, event: string): number; + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } + } + export var Http: NodeJs.Http; + export module Http { + export interface Server extends NodeJs.Http.Server { } + export interface ServerRequest extends NodeJs.Http.ServerRequest { } + export interface ServerResponse extends NodeJs.Http.ServerResponse { } + export interface ClientRequest extends NodeJs.Http.ClientRequest { } + export interface ClientResponse extends NodeJs.Http.ClientResponse { } + export interface Agent extends NodeJs.Http.Agent { } + } + export var Net: NodeJs.Net; + export module Net { + export interface Socket extends NodeJs.Net.Socket { } + export interface Server extends NodeJs.Net.Server { } + } + export var Url: NodeJs.Url; + export module Url { + export interface Url extends NodeJs.Url.Url { } + export interface UrlOptions extends NodeJs.Url.UrlOptions { } + } + } +} + /************************************************ * * @@ -259,17 +327,6 @@ declare module "domain" { import _ = NodeJs.Domain; export = _; ************************************************/ declare module NodeJs { - // NB: All typings in this namespace are exposed in dual declaration spaces - // (i.e. as 'types' and as 'members' - see TypeScript Language Spec section 2.3) - // so that type information is available in both of the following scenarios: - // - // // Normal import: - // import http = require('http'); - // http.createServer((req, res) => {...}) - // - // // Typed variable: - // var http: NodeJs.Http = someExpr() // a wrapped, mocked or otherwise obtained ref - // http.createServer((req, res) => {...}) // ---------- "querystring" module ---------- @@ -279,7 +336,6 @@ declare module NodeJs { escape(): any; unescape(): any; } - export var QueryString: QueryString; // ---------- "events" module ---------- @@ -290,8 +346,7 @@ declare module NodeJs { } } export module Events { - export class EventEmitter implements NodeEventEmitter { - static listenerCount(emitter: EventEmitter, event: string): number; + export interface EventEmitter extends NodeEventEmitter { addListener(event: string, listener: Function): EventEmitter; on(event: string, listener: Function): EventEmitter; once(event: string, listener: Function): EventEmitter; @@ -313,7 +368,6 @@ declare module NodeJs { get(options: any, callback?: Function): Http.ClientRequest; globalAgent: Http.Agent; } - export var Http: Http; export module Http { export interface Server extends NodeEventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; @@ -422,31 +476,12 @@ declare module NodeJs { } } export module Cluster { - export var settings: Cluster.ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: Cluster.ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var worker: Worker; - export var workers: Worker[]; - - // Event emitter - export function addListener(event: string, listener: Function): 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; - export interface ClusterSettings { exec?: string; args?: string[]; silent?: boolean; } - export class Worker extends Events.EventEmitter { + export interface Worker extends Events.EventEmitter { id: string; process: ChildProcess.ChildProcess; suicide: boolean; @@ -509,7 +544,6 @@ declare module NodeJs { Z_DEFLATED: number; Z_NULL: number; } - export var Zlib: Zlib; export module Zlib { export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends ReadWriteStream { } @@ -538,7 +572,6 @@ declare module NodeJs { networkInterfaces(): any; EOL: string; } - export var Os: Os; // ---------- "https" module ---------- @@ -550,7 +583,6 @@ declare module NodeJs { get(options: Https.RequestOptions, callback?: (res: NodeEventEmitter) => void): Http.ClientRequest; globalAgent: Https.Agent; } - export var Https: Https; export module Https { export interface ServerOptions { pfx?: any; @@ -604,14 +636,12 @@ declare module NodeJs { } version: any; } - export var PunyCode: PunyCode; // ---------- "repl" module ---------- export interface Repl { start(options: Repl.ReplOptions): NodeEventEmitter; } - export var Repl: Repl; export module Repl { export interface ReplOptions { prompt?: string; @@ -631,7 +661,6 @@ declare module NodeJs { export interface ReadLine { createInterface(options: ReadLine.ReadLineOptions): ReadLine.ReadLine; } - export var ReadLine: ReadLine; export module ReadLine { export interface ReadLine extends NodeEventEmitter { setPrompt(prompt: string, length: number): void; @@ -659,7 +688,6 @@ declare module NodeJs { createContext(initSandbox?: Vm.Context): Vm.Context; createScript(code: string, filename?: string): Vm.Script; } - export var Vm: Vm; export module Vm { export interface Context { } export interface Script { @@ -705,7 +733,6 @@ declare module NodeJs { encoding?: string; }): ChildProcess.ChildProcess; } - export var ChildProcess: ChildProcess; export module ChildProcess { export interface ChildProcess extends NodeEventEmitter { stdin: WritableStream; @@ -725,7 +752,6 @@ declare module NodeJs { format(url: Url.UrlOptions): string; resolve(from: string, to: string): string; } - export var Url: Url; export module Url { export interface Url { href: string; @@ -767,7 +793,6 @@ declare module NodeJs { resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; } - export var Dns: Dns; // ---------- "net" module ---------- @@ -786,7 +811,6 @@ declare module NodeJs { isIPv4(input: string): boolean; isIPv6(input: string): boolean; } - export var Net: Net; export module Net { export interface Socket extends ReadWriteStream { @@ -837,7 +861,6 @@ declare module NodeJs { export interface Dgram { createSocket(type: string, callback?: Function): Dgram.Socket; } - export var Dgram: Dgram; export module Dgram { interface Socket extends NodeEventEmitter { send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; @@ -968,7 +991,6 @@ declare module NodeJs { string?: string; }): Fs.WriteStream; } - export var Fs: Fs; export module Fs { export interface Stats { isFile(): boolean; @@ -1011,14 +1033,12 @@ declare module NodeJs { extname(p: string): string; sep: string; } - export var Path: Path; // ---------- "string_decoder" module ---------- export interface StringDecoder { StringDecoder: new(encoding: string) => StringDecoder.StringDecoder; } - export var StringDecoder: StringDecoder; export module StringDecoder { export interface StringDecoder { write(buffer: NodeBuffer): string; @@ -1037,7 +1057,6 @@ declare module NodeJs { connect(port: number, options?: Tls.ConnectionOptions, secureConnectListener?: () =>void ): Tls.ClearTextStream; createSecurePair(credentials?: Crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): Tls.SecurePair; } - export var Tls: Tls; export module Tls { export interface TlsOptions { pfx?: any; //string or buffer @@ -1124,7 +1143,6 @@ declare module NodeJs { pseudoRandomBytes(size: number): NodeBuffer; pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; } - export var Crypto: Crypto; export module Crypto { export interface CredentialDetails { pfx: string; @@ -1190,8 +1208,7 @@ declare module NodeJs { encoding?: string; objectMode?: boolean; } - export class Readable extends Events.EventEmitter implements ReadableStream { - constructor(opts?: ReadableOptions); + export interface Readable extends Events.EventEmitter, ReadableStream { readable: boolean; _read(size: number): void; read(size?: number): any; @@ -1209,8 +1226,7 @@ declare module NodeJs { highWaterMark?: number; decodeStrings?: boolean; } - export class Writable extends Events.EventEmitter implements WritableStream { - constructor(opts?: WritableOptions); + export interface Writable extends Events.EventEmitter, WritableStream { writable: boolean; _write(data: NodeBuffer, encoding: string, callback: Function): void; _write(data: string, encoding: string, callback: Function): void; @@ -1227,8 +1243,7 @@ declare module NodeJs { } // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements ReadWriteStream { - constructor(opts?: DuplexOptions); + export interface Duplex extends Readable, ReadWriteStream { writable: boolean; _write(data: NodeBuffer, encoding: string, callback: Function): void; _write(data: string, encoding: string, callback: Function): void; @@ -1243,8 +1258,7 @@ declare module NodeJs { export interface TransformOptions extends ReadableOptions, WritableOptions {} // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends Events.EventEmitter implements ReadWriteStream { - constructor(opts?: TransformOptions); + export interface Transform extends Events.EventEmitter, ReadWriteStream { readable: boolean; writable: boolean; _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; @@ -1268,7 +1282,7 @@ declare module NodeJs { end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } - export class PassThrough extends Transform {} + export interface PassThrough extends Transform {} } @@ -1288,7 +1302,6 @@ declare module NodeJs { isError(object: any): boolean; inherits(constructor: any, superConstructor: any): void; } - export var Util: Util; export module Util { export interface InspectOptions { showHidden?: boolean; @@ -1326,30 +1339,7 @@ declare module NodeJs { } ifError(value: any): void; } - export function Assert(value: any, message?: string): void; export module Assert { - 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 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 interface AssertionErrorOptions { message?: string; actual?: any; @@ -1357,8 +1347,7 @@ declare module NodeJs { operator?: string; stackStartFunction?: Function } - export class AssertionError implements Error { - constructor(options?: AssertionErrorOptions); + export interface AssertionError extends Error { name: string; message: string; actual: any; @@ -1375,7 +1364,6 @@ declare module NodeJs { WriteStream: new() => Tty.WriteStream; isatty(fd: number): boolean; } - export var Tty: Tty; export module Tty { export interface ReadStream extends Net.Socket { isRaw: boolean; @@ -1394,7 +1382,7 @@ declare module NodeJs { create(): Domain.Domain; } export module Domain { - export class Domain extends Events.EventEmitter { + export interface Domain extends Events.EventEmitter { run(fn: Function): void; add(emitter: NodeEventEmitter): void; remove(emitter: NodeEventEmitter): void;