From 0690841c6b5d33bfcbf91be3b02f13e63c990ed1 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Mon, 10 Feb 2014 17:40:59 +0000 Subject: [PATCH 001/167] Update angular.d.ts The listener may take a single event argument. --- angularjs/angular.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index a8c1d991d..10dec18ae 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -227,6 +227,7 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 045537ef49c478296abc3becf0ea5d27be326823 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Tue, 25 Feb 2014 17:32:17 +0000 Subject: [PATCH 002/167] Update angular-ui-router.d.ts --- angular-ui/angular-ui-router.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index da3d92e5e..285149a0d 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -84,6 +84,7 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; + $current: IState; params: IStateParamsService; } From 17e72ca4827f7d9f3e92b3322f0021771301b8cb Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Tue, 25 Feb 2014 17:37:58 +0000 Subject: [PATCH 003/167] Revert "Update angular.d.ts" This reverts commit 0690841c6b5d33bfcbf91be3b02f13e63c990ed1. --- angularjs/angular.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 10dec18ae..a8c1d991d 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -227,7 +227,6 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 57a3b6e1b8c3ba05db9dcb2f1110d39ef8c94b0e Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Tue, 3 Jun 2014 13:22:50 +0100 Subject: [PATCH 004/167] Add basic type definitions for express 4.x --- body-parser/body-parser.d.ts | 12 + compression/compression-tests.ts | 10 + compression/compression.d.ts | 20 + cookie-parser/cookie-parser-tests.ts | 7 + cookie-parser/cookie-parser.d.ts | 12 + errorhandler/errorhandler-tests.ts | 7 + errorhandler/errorhandler.d.ts | 12 + express/express-3.1.0-tests.ts | 1498 ++++++++++++++++++ express/express-3.1.0-tests.ts.tscparams | 1 + express/express-3.1.0.d.ts | 1832 ++++++++++++++++++++++ express/express-tests.ts | 1493 +----------------- express/express.d.ts | 903 +---------- method-override/method-override-tests.ts | 15 + method-override/method-override.d.ts | 24 + 14 files changed, 3514 insertions(+), 2332 deletions(-) create mode 100644 body-parser/body-parser.d.ts create mode 100644 compression/compression-tests.ts create mode 100644 compression/compression.d.ts create mode 100644 cookie-parser/cookie-parser-tests.ts create mode 100644 cookie-parser/cookie-parser.d.ts create mode 100644 errorhandler/errorhandler-tests.ts create mode 100644 errorhandler/errorhandler.d.ts create mode 100644 express/express-3.1.0-tests.ts create mode 100644 express/express-3.1.0-tests.ts.tscparams create mode 100644 express/express-3.1.0.d.ts create mode 100644 method-override/method-override-tests.ts create mode 100644 method-override/method-override.d.ts diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts new file mode 100644 index 000000000..f16b2eefb --- /dev/null +++ b/body-parser/body-parser.d.ts @@ -0,0 +1,12 @@ +// Type definitions for body-parser +// Project: http://expressjs.com +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "body-parser" { + import express = require('express'); + function e(options?: any): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/compression/compression-tests.ts b/compression/compression-tests.ts new file mode 100644 index 000000000..ecfcab432 --- /dev/null +++ b/compression/compression-tests.ts @@ -0,0 +1,10 @@ +/// + +import express = require('express'); +import compress = require('compression'); + +var app = express(); +app.use(compress()); +app.use(compress({ + threshold: 512 +})); diff --git a/compression/compression.d.ts b/compression/compression.d.ts new file mode 100644 index 000000000..9ef3a8cb7 --- /dev/null +++ b/compression/compression.d.ts @@ -0,0 +1,20 @@ +// Type definitions for compression +// Project: https://github.com/expressjs/compression +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "compression" { + import express = require('express'); + + module e { + interface CompressionOptions { + threshold?: number; + filter?: Function; + } + } + + function e(options?: e.CompressionOptions): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/cookie-parser/cookie-parser-tests.ts b/cookie-parser/cookie-parser-tests.ts new file mode 100644 index 000000000..94e8a9fdb --- /dev/null +++ b/cookie-parser/cookie-parser-tests.ts @@ -0,0 +1,7 @@ +/// + +import express = require('express'); +import cookieParser = require('cookie-parser'); + +var app = express(); +app.use(cookieParser('optional secret string')); diff --git a/cookie-parser/cookie-parser.d.ts b/cookie-parser/cookie-parser.d.ts new file mode 100644 index 000000000..f43553b7c --- /dev/null +++ b/cookie-parser/cookie-parser.d.ts @@ -0,0 +1,12 @@ +// Type definitions for cookie-parser +// Project: https://github.com/expressjs/cookie-parser +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "cookie-parser" { + import express = require('express'); + function e(secret?: string, options?: any): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/errorhandler/errorhandler-tests.ts b/errorhandler/errorhandler-tests.ts new file mode 100644 index 000000000..02f788790 --- /dev/null +++ b/errorhandler/errorhandler-tests.ts @@ -0,0 +1,7 @@ +/// + +import express = require('express'); +import errorhandler = require('errorhandler'); +var app = express(); + +app.use(errorhandler()); diff --git a/errorhandler/errorhandler.d.ts b/errorhandler/errorhandler.d.ts new file mode 100644 index 000000000..e6c3011a5 --- /dev/null +++ b/errorhandler/errorhandler.d.ts @@ -0,0 +1,12 @@ +// Type definitions for errorhandler +// Project: https://github.com/expressjs/errorhandler +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "errorhandler" { + import express = require('express'); + function e(): express.ErrorRequestHandler; + export = e; +} \ No newline at end of file diff --git a/express/express-3.1.0-tests.ts b/express/express-3.1.0-tests.ts new file mode 100644 index 000000000..904f64511 --- /dev/null +++ b/express/express-3.1.0-tests.ts @@ -0,0 +1,1498 @@ +/// + +import express = require('express'); +var app = express(); + +////////////////////////// + +var hash: any; + +// config + +app.set('view engine', 'ejs'); +app.set('views', __dirname + '/views'); + +// middleware + +app.use(express.bodyParser()); +app.use(express.cookieParser('shhhh, very secret')); +app.use(express.session()); + +// Session-persisted message middleware + +app.use((req: express.Request, res: express.Response, next) => { + var err = req.session.error + , msg = req.session.success; + delete req.session.error; + delete req.session.success; + res.locals.message = ''; + if (err) res.locals.message = '

' + err + '

'; + if (msg) res.locals.message = '

' + msg + '

'; + next(); +}); + +// dummy database + +var users = { + tj: { name: 'tj' } +}; + +// when you create a user, generate a salt +// and hash the password ('foobar' is the pass here) + +hash('foobar', (err, salt, hash) => { + if (err) throw err; + // store the salt & hash in the "db" + users.tj.salt = salt; + users.tj.hash = hash; +}); + + +// Authenticate using our plain-object database of doom! + +function authenticate(name, pass, fn) { + if (!module.parent) console.log('authenticating %s:%s', name, pass); + var user = users[name]; + // query the db for the given username + if (!user) return fn(new Error('cannot find user')); + // apply the same algorithm to the POSTed password, applying + // the hash against the pass / salt, if there is a match we + // found the user + hash(pass, user.salt, (err, hash) => { + if (err) return fn(err); + if (hash == user.hash) return fn(null, user); + fn(new Error('invalid password')); + }); +} + +function restrict(req: express.Request, res: express.Response, next?: Function) { + if (req.session.user) { + next(); + } else { + req.session.error = 'Access denied!'; + res.redirect('/login'); + } +} + +app.get('/', (req: express.Request, res: express.Response) => { + res.redirect('login'); +}); + +app.get('/restricted', restrict, (req: express.Request, res: express.Response) => { + res.send('Wahoo! restricted area, click to logout'); +}); + +app.get('/logout', (req: express.Request, res: express.Response) => { + // destroy the user's session to log them out + // will be re-created next request + req.session.destroy(() => { + res.redirect('/'); + }); +}); + +app.get('/login', (req: express.Request, res: express.Response) => { + res.render('login'); +}); + +app.post('/login', (req: express.Request, res: express.Response) => { + authenticate(req.body.username, req.body.password, (err, user) => { + if (user) { + // Regenerate session when signing in + // to prevent fixation + req.session.regenerate(() => { + // Store the user's primary key + // in the session store to be retrieved, + // or in this case the entire user object + req.session.user = user; + req.session.success = 'Authenticated as ' + user.name + + ' click to logout. ' + + ' You may now access /restricted.'; + res.redirect('back'); + }); + } else { + req.session.error = 'Authentication failed, please check your ' + + ' username and password.' + + ' (use "tj" and "foobar")'; + res.redirect('login'); + } + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////// + +app.set('views', __dirname); +app.set('view engine', 'jade'); + +var pets = []; + +var n = 1000; +while (n--) { + pets.push({ name: 'Tobi', age: 2, species: 'ferret' }); + pets.push({ name: 'Loki', age: 1, species: 'ferret' }); + pets.push({ name: 'Jane', age: 6, species: 'ferret' }); +} + +app.use(express.logger('dev')); + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('pets', { pets: pets }); +}); + +app.listen(3000); +console.log('Express listening on port 3000'); + +///////////// + +app.get('/', (req: express.Request, res: express.Response) => { + res.format({ + html: () => { + res.send('
    ' + users.map(user => { + return '
  • ' + user.name + '
  • '; + }).join('') + '
'); + }, + + text: () => { + res.send(users.map(user => { + return ' - ' + user.name + '\n'; + }).join('')); + }, + + json: () => { + res.json(users); + } + }); +}); + +// or you could write a tiny middleware like +// this to abstract make things a bit more declarative: + +function format(mod) { + var obj = require(mod); + return (req: express.Request, res: express.Response) => { + res.format(obj); + }; +} + +app.get('/users', format('./users')); + +if (!module.parent) { + app.listen(3000); + console.log('listening on port 3000'); +} + +///////////////////////// + +// add favicon() before logger() so +// GET /favicon.ico requests are not +// logged, because this middleware +// reponds to /favicon.ico and does not +// call next() +app.use(express.favicon()); + +// custom log format +if ('test' != process.env.NODE_ENV) + app.use(express.logger(':method :url')); + +// parses request cookies, populating +// req.cookies and req.signedCookies +// when the secret is passed, used +// for signing the cookies. +app.use(express.cookieParser('my secret here')); + +// parses json, x-www-form-urlencoded, and multipart/form-data +app.use(express.bodyParser()); + +app.get('/', (req: express.Request, res: express.Response) => { + if (req.cookies.remember) { + res.send('Remembered :). Click to forget!.'); + } else { + res.send('

Check to ' + + '.

'); + } +}); + +app.get('/forget', (req: express.Request, res: express.Response) => { + res.clearCookie('remember'); + res.redirect('back'); +}); + +app.post('/', (req: express.Request, res: express.Response) => { + var minute = 60000; + if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); + res.redirect('back'); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////// + +// ignore GET /favicon.ico +app.use(express.favicon()); + +// pass a secret to cookieParser() for signed cookies +app.use(express.cookieParser('manny is cool')); + +// add req.session cookie support +app.use(express.cookieSession()); + +// do something with the session +app.use(count); + +// custom middleware +function count(req: express.Request, res: express.Response) { + req.session.count = req.session.count || 0; + var n = req.session.count++; + res.send('viewed ' + n + ' times\n'); +} + +if (!module.parent) { + app.listen(3000); + console.log('Express server listening on port 3000'); +} + +/////////////// + +var api = app; + +app.use(express.static(__dirname + '/public')); + +// api middleware + +api.use(express.logger('dev')); +api.use(express.bodyParser()); + +/** + * CORS support. + */ + +api.all('*', (req: express.Request, res: express.Response, next) => { + if (!req.get('Origin')) return next(); + // use "*" here to accept any origin + res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); + res.set('Access-Control-Allow-Methods', 'GET, POST'); + res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'); + // res.set('Access-Control-Allow-Max-Age', 3600); + if ('OPTIONS' == req.method) return res.send(200); + next(); +}); + +/** + * POST a user. + */ + +api.post('/user', (req: express.Request, res: express.Response) => { + console.log(req.body); + res.send(201); +}); + +app.listen(3000); +api.listen(3001); + +console.log('app listening on 3000'); +console.log('api listening on 3001'); + +//////////////////// + +app.get('/', (req: express.Request, res: express.Response) => { + res.send(''); +}); + +// /files/* is accessed via req.params[0] +// but here we name it :file +app.get('/files/:file(*)', (req: express.Request, res: express.Response) => { + var file = req.params.file + , path = __dirname + '/files/' + file; + + res.download(path); +}); + +// error handling middleware. Because it's +// below our routes, you will be able to +// "intercept" errors, otherwise Connect +// will respond with 500 "Internal Server Error". +app.use((err, req, res: express.Response, next) => { + // special-case 404s, + // remember you could + // render a 404 template here + if (404 == err.status) { + res.statusCode = 404; + res.send('Cant find that file, sorry!'); + } else { + next(err); + } +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////// + +// Register ejs as .html. If we did +// not call this, we would need to +// name our views foo.ejs instead +// of foo.html. The __express method +// is simply a function that engines +// use to hook into the Express view +// system by default, so if we want +// to change "foo.ejs" to "foo.html" +// we simply pass _any_ function, in this +// case `ejs.__express`. + +app.engine('.html', require('ejs').__express); + +// Optional since express defaults to CWD/views + +app.set('views', __dirname + '/views'); + +// Without this you would need to +// supply the extension to res.render() +// ex: res.render('users.html'). +app.set('view engine', 'html'); + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('users', { + users: users, + title: "EJS example", + header: "Some users" + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express app started on port 3000'); +} + +//////////////////// + +var test: any; + +if (!test) app.use(express.logger('dev')); +app.use(app.router); + +// the error handler is strategically +// placed *below* the app.router; if it +// were above it would not receive errors +// from app.get() etc +app.use(error); + +// error handling middleware have an arity of 4 +// instead of the typical (req: express.Request, res: express.Response, next), +// otherwise they behave exactly like regular +// middleware, you may have several of them, +// in different orders etc. + +function error(err, req, res: express.Response, next) { + // log it + if (!test) console.error(err.stack); + + // respond with 500 "Internal Server Error". + res.send(500); +} + +app.get('/', () => { + // Caught and passed down to the errorHandler middleware + throw new Error('something broke!'); +}); + +app.get('/next', (req: express.Request, res: express.Response, next) => { + // We can also pass exceptions to next() + process.nextTick(() => { + next(new Error('oh no!')); + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +///////////////////// + +var silent: any; + +// general config +app.set('views', __dirname + '/views'); +app.set('view engine', 'jade'); + +// our custom "verbose errors" setting +// which we can use in the templates +// via settings['verbose errors'] +app.enable('verbose errors'); + +// disable them in production +// use $ NODE_ENV=production node examples/error-pages +if ('production' == app.settings.env) { + app.disable('verbose errors'); +} + +app.use(express.favicon()); + +silent || app.use(express.logger('dev')); + +// "app.router" positions our routes +// above the middleware defined below, +// this means that Express will attempt +// to match & call routes _before_ continuing +// on, at which point we assume it's a 404 because +// no route has handled the request. + +app.use(app.router); + +// Since this is the last non-error-handling +// middleware use()d, we assume 404, as nothing else +// responded. + +// $ curl http://localhost:3000/notfound +// $ curl http://localhost:3000/notfound -H "Accept: application/json" +// $ curl http://localhost:3000/notfound -H "Accept: text/plain" + +app.use((req: express.Request, res: express.Response) => { + res.status(404); + + // respond with html page + if (req.accepts('html')) { + res.render('404', { url: req.url }); + return; + } + + // respond with json + if (req.accepts('json')) { + res.send({ error: 'Not found' }); + return; + } + + // default to plain-text. send() + res.type('txt').send('Not found'); +}); + +// error-handling middleware, take the same form +// as regular middleware, however they require an +// arity of 4, aka the signature (err, req, res: express.Response, next). +// when connect has an error, it will invoke ONLY error-handling +// middleware. + +// If we were to next() here any remaining non-error-handling +// middleware would then be executed, or if we next(err) to +// continue passing the error, only error-handling middleware +// would remain being executed, however here +// we simply respond with an error page. + +app.use((err, req, res: express.Response) => { + // we may use properties of the error object + // here and next(err) appropriately, or if + // we possibly recovered from the error, simply next(). + res.status(err.status || 500); + res.render('500', { error: err }); +}); + +// Routes + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('index.jade'); +}); + +app.get('/404', (req: express.Request, res: express.Response, next) => { + // trigger a 404 since no other middleware + // will match /404 after this one, and we're not + // responding here + next(); +}); + +app.get('/403', (req: express.Request, res: express.Response, next) => { + // trigger a 403 error + var err = new Error('not allowed!'); + err.status = 403; + next(err); +}); + +app.get('/500', (req: express.Request, res: express.Response, next) => { + // trigger a generic (500) error + next(new Error('keyboard cat!')); +}); + +if (!module.parent) { + app.listen(3000); + //silent ||  console.log('Express started on port 3000'); +} + +/////////////// + +var fs: any; +var md: any; + +app.set('view engine', 'jade'); +app.set('views', __dirname + '/views'); + +function User(name) { + this.private = 'heyyyy'; + this.secret = 'something'; + this.name = name; + this.id = 123; +} + +// You'll probably want to do +// something like this so you +// dont expose "secret" data. + +User.prototype.toJSON = function () { + return { + id: this.id, + name: this.name + }; +}; + +app.use(express.logger('dev')); + +// earlier on expose an object +// that we can tack properties on. +// all res.locals props are exposed +// to the templates, so "expose" will +// be present. + +app.use((req: express.Request, res: express.Response, next) => { + res.locals.expose = {}; + // you could alias this as req or res.expose + // to make it shorter and less annoying + next(); +}); + +// pretend we loaded a user + +app.use((req: express.Request, res: express.Response, next) => { + req.user = new User('Tobi'); + next(); +}); + +app.get('/', (req: express.Request, res: express.Response) => { + res.redirect('/user'); +}); + +app.get('/user', (req: express.Request, res: express.Response) => { + // we only want to expose the user + // to the client for this route: + res.locals.expose.user = req.user; + res.render('page'); +}); + +app.listen(3000); +console.log('app listening on port 3000'); + +/////////////////////// + +app.get('/', (req: express.Request, res: express.Response) => { + res.send('Hello World'); +}); + +app.listen(3000); +console.log('Express started on port 3000'); + +//////////////////// + +// register .md as an engine in express view system + +app.engine('md', (path, options, fn) => { + fs.readFile(path, 'utf8', (err, str) => { + if (err) return fn(err); + try { + var html = md(str); + html = html.replace(/\{([^}]+)\}/g, (_, name) => { + return options[name] || ''; + }); + fn(null, html); + } catch (err) { + fn(err); + } + }); +}); + +app.set('views', __dirname + '/views'); + +// make it the default so we dont need .md +app.set('view engine', 'md'); + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('index', { title: 'Markdown Example' }); +}); + +app.get('/fail', (req: express.Request, res: express.Response) => { + res.render('missing', { title: 'Markdown Example' }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////////// + +var mformat: any; + +// bodyParser in connect 2.x uses node-formidable to parse +// the multipart form data. +app.use(express.bodyParser()); + +app.get('/', (req: express.Request, res: express.Response) => { + res.send('
' + + '

Title:

' + + '

Image:

' + + '

' + + '
'); +}); + +app.post('/', (req: express.Request, res: express.Response) => { + // the uploaded file can be found as `req.files.image` and the + // title field as `req.body.title` + res.send(mformat('\nuploaded %s (%d Kb) to %s as %s' + , req.files.image.name + , req.files.image.size / 1024 | 0 + , req.files.image.path + , req.body.title)); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////////// + + +// first: +// $ npm install redis online +// $ redis-server + +/** + * Module dependencies. + */ + +var online: any; +var db: any; + +// online + +online = online(db); + +// activity tracking, in this case using +// the UA string, you would use req.user.id etc + +app.use((req: express.Request, res: express.Response, next) => { + // fire-and-forget + online.add(req.headers['user-agent']); + next(); +}); + +/** + * List helper. + */ + +function list(ids) { + return '
    ' + ids.map(id => { + return '
  • ' + id + '
  • '; + }).join('') + '
'; +} + +/** + * GET users online. + */ + +app.get('/', (req: express.Request, res: express.Response, next) => { + online.last(5, (err, ids) => { + if (err) return next(err); + res.send('

Users online: ' + ids.length + '

' + list(ids)); + }); +}); + +app.listen(3000); +console.log('listening on port 3000'); + +/////////////////// + +// Convert :to and :from to integers + +app.param(['to', 'from'], (req: express.Request, res: express.Response, next, num, name) => { + req.params[name] = num = parseInt(num, 10); + if (isNaN(num)) { + next(new Error('failed to parseInt ' + num)); + } else { + next(); + } +}); + +// Load user by id + +app.param('user', (req: express.Request, res: express.Response, next, id) => { + if (req.user = users[id]) { + next(); + } else { + next(new Error('failed to find user')); + } +}); + +/** + * GET index. + */ + +app.get('/', (req: express.Request, res: express.Response) => { + res.send('Visit /user/0 or /users/0-2'); +}); + +/** + * GET :user. + */ + +app.get('/user/:user', (req: express.Request, res: express.Response) => { + res.send('user ' + req.user.name); +}); + +/** + * GET users :from - :to. + */ + +app.get('/users/:from-:to', (req: express.Request, res: express.Response) => { + var from = req.params.from + , to = req.params.to + , names = users.map(user => { return user.name; }); + res.send('users ' + names.slice(from, to).join(', ')); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////////// + +// Ad-hoc example resource method + +app.resource = function (path, obj) { + this.get(path, obj.index); + this.get(path + '/:a..:b.:format?', (req: express.Request, res: express.Response) => { + var a = parseInt(req.params.a, 10) + , b = parseInt(req.params.b, 10) + , format = req.params.format; + obj.range(req, res, a, b, format); + }); + this.get(path + '/:id', obj.show); + this.del(path + '/:id', obj.destroy); +}; + +// Fake controller. + +var FUser = { + index: (req: express.Request, res: express.Response) => { + res.send(users); + }, + show: (req: express.Request, res: express.Response) => { + res.send(users[req.params.id] || { error: 'Cannot find user' }); + }, + destroy: (req: express.Request, res: express.Response) => { + var id = req.params.id; + var destroyed = id in users; + delete users[id]; + res.send(destroyed ? 'destroyed' : 'Cannot find user'); + }, + range: (req: express.Request, res: express.Response, a, b, format) => { + var range = users.slice(a, b + 1); + switch (format) { + case 'json': + res.send(range); + break; + case 'html': + default: + var html = '
    ' + range.map(user => { + return '
  • ' + user.name + '
  • '; + }).join('\n') + '
'; + res.send(html); + break; + } + } +}; + +// curl http://localhost:3000/users -- responds with all users +// curl http://localhost:3000/users/1 -- responds with user 1 +// curl http://localhost:3000/users/4 -- responds with error +// curl http://localhost:3000/users/1..3 -- responds with several users +// curl -X DELETE http://localhost:3000/users/1 -- deletes the user + +app.resource('/users', FUser); + +app.get('/', (req: express.Request, res: express.Response) => { + res.send([ + '

Examples:

    ' + , '
  • GET /users
  • ' + , '
  • GET /users/1
  • ' + , '
  • GET /users/3
  • ' + , '
  • GET /users/1..3
  • ' + , '
  • GET /users/1..3.json
  • ' + , '
  • DELETE /users/4
  • ' + , '
' + ].join('\n')); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +///////////////////// + + +var verbose: any; + +app.map = (a, route) => { + route = route || ''; + for (var key in a) { + switch (typeof a[key]) { + // { '/path': { ... }} + case 'object': + app.map(a[key], route + key); + break; + // get: function(){ ... } + case 'function': + if (verbose) console.log('%s %s', key, route); + app[key](route, a[key]); + break; + } + } +}; + +var users2 = { + list: (req: express.Request, res: express.Response) => { + res.send('user list'); + }, + + get: (req: express.Request, res: express.Response) => { + res.send('user ' + req.params.uid); + }, + + del: (req: express.Request, res: express.Response) => { + res.send('delete users'); + } +}; + +var pets2 = { + list: (req: express.Request, res: express.Response) => { + res.send('user ' + req.params.uid + '\'s pets'); + }, + + del: (req: express.Request, res: express.Response) => { + res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid); + } +}; + +app.map({ + '/users': { + get: users2.list, + del: users2.del, + '/:uid': { + get: users.get , + '/pets': { + get: pets2.list, + '/:pid': { + del: pets2.del + } + } + } + } +}); + +app.listen(3000); + +/////////////////////////// + +// Example requests: +// curl http://localhost:3000/user/0 +// curl http://localhost:3000/user/0/edit +// curl http://localhost:3000/user/1 +// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) +// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) + +function loadUser(req: express.Request, res: express.Response, next) { + // You would fetch your user from the db + var user = users[req.params.id]; + if (user) { + req.user = user; + next(); + } else { + next(new Error('Failed to load user ' + req.params.id)); + } +} + +function andRestrictToSelf(req: express.Request, res: express.Response, next) { + // If our authenticated user is the user we are viewing + // then everything is fine :) + if (req.authenticatedUser.id == req.user.id) { + next(); + } else { + // You may want to implement specific exceptions + // such as UnauthorizedError or similar so that you + // can handle these can be special-cased in an error handler + // (view ./examples/pages for this) + next(new Error('Unauthorized')); + } +} + +function andRestrictTo(role) { + return (req: express.Request, res: express.Response, next) => { + if (req.authenticatedUser.role == role) { + next(); + } else { + next(new Error('Unauthorized')); + } + }; +} + +// Middleware for faux authentication +// you would of course implement something real, +// but this illustrates how an authenticated user +// may interact with middleware + +app.use((req: express.Request, res: express.Response, next) => { + req.authenticatedUser = users[0]; + next(); +}); + +app.get('/', (req: express.Request, res: express.Response) => { + res.redirect('/user/0'); +}); + +app.get('/user/:id', loadUser, (req: express.Request, res: express.Response) => { + res.send('Viewing user ' + req.user.name); +}); + +app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req: express.Request, res: express.Response) => { + res.send('Editing user ' + req.user.name); +}); + +app.del('/user/:id', loadUser, andRestrictTo('admin'), (req: express.Request, res: express.Response) => { + res.send('Deleted user ' + req.user.name); +}); + +app.listen(3000); +console.log('Express app started on port 3000'); + +///////////////////////// + +app.set('view engine', 'jade'); +app.set('views', __dirname); + +// populate search + +db.sadd('ferret', 'tobi'); +db.sadd('ferret', 'loki'); +db.sadd('ferret', 'jane'); +db.sadd('cat', 'manny'); +db.sadd('cat', 'luna'); + +/** + * GET the search page. + */ + +app.get('/', (req: express.Request, res: express.Response) => { + res.render('search'); +}); + +/** + * GET search for :query. + */ + +app.get('/search/:query?', (req: express.Request, res: express.Response) => { + var query = req.params.query; + db.smembers(query, (err, vals) => { + if (err) return res.send(500); + res.send(vals); + }); +}); + +/** + * GET client javascript. Here we use sendfile() + * because serving __dirname with the static() middleware + * would also mean serving our server "index.js" and the "search.jade" + * template. + */ + +app.get('/client.js', (req: express.Request, res: express.Response) => { + res.sendfile(__dirname + '/client.js'); +}); + +app.listen(3000); +console.log('app listening on port 3000'); + +/////////////////// + +app.use(express.logger('dev')); + +// Required by session() middleware +// pass the secret for signed cookies +// (required by session()) +app.use(express.cookieParser('keyboard cat')); + +// Populates req.session +app.use(express.session()); + +app.get('/', (req: express.Request, res: express.Response) => { + var body = ''; + if (req.session.views) { + ++req.session.views; + } else { + req.session.views = 1; + body += '

First time visiting? view this page in several browsers :)

'; + } + res.send(body + '

viewed ' + req.session.views + ' times.

'); +}); + +app.listen(3000); +console.log('Express app started on port 3000'); + +//////////////////////// + +// log requests +app.use(express.logger('dev')); + +// express on its own has no notion +// of a "file". The express.static() +// middleware checks for a file matching +// the `req.path` within the directory +// that you pass it. In this case "GET /js/app.js" +// will look for "./public/js/app.js". + +app.use(express.static(__dirname + '/public')); + +// if you wanted to "prefix" you may use +// the mounting feature of Connect, for example +// "GET /static/js/app.js" instead of "GET /js/app.js". +// The mount-path "/static" is simply removed before +// passing control to the express.static() middleware, +// thus it serves the file correctly by ignoring "/static" +app.use('/static', express.static(__dirname + '/public')); + +// if for some reason you want to serve files from +// several directories, you can use express.static() +// multiple times! Here we're passing "./public/css", +// this will allow "GET /style.css" instead of "GET /css/style.css": +app.use(express.static(__dirname + '/public/css')); + +// this examples does not have any routes, however +// you may `app.use(app.router)` before or after these +// static() middleware. If placed before them your routes +// will be matched BEFORE file serving takes place. If placed +// after as shown here then file serving is performed BEFORE +// any routes are hit: +app.use(app.router); + +app.listen(3000); +console.log('listening on port 3000'); +console.log('try:'); +console.log(' GET /hello.txt'); +console.log(' GET /js/app.js'); +console.log(' GET /css/style.css'); + +////////////////// + +/* +edit /etc/vhosts: + +127.0.0.1 foo.example.com +127.0.0.1 bar.example.com +127.0.0.1 example.com +*/ + +// Main app + +var main = express(); + +main.use(express.logger('dev')); + +main.get('/', (req: express.Request, res: express.Response) => { + res.send('Hello from main app!'); +}); + +main.get('/:sub', (req: express.Request, res: express.Response) => { + res.send('requsted ' + req.params.sub); +}); + +// Redirect app + +var redirect = express(); + +redirect.all('*', (req: express.Request, res: express.Response) => { + console.log(req.subdomains); + res.redirect('http://example.com:3000/' + req.subdomains[0]); +}); + +app.use(express.vhost('*.example.com', redirect)); +app.use(express.vhost('example.com', main)); + +app.listen(3000); +console.log('Express app started on port 3000'); + +//////////////////// + +// create an error with .status. we +// can then use the property in our +// custom error handler (Connect repects this prop as well) + +function merror(status, msg) { + var err = new Error(msg); + err.status = status; + return err; +} + +// if we wanted to supply more than JSON, we could +// use something similar to the content-negotiation +// example. + +// here we validate the API key, +// by mounting this middleware to /api +// meaning only paths prefixed with "/api" +// will cause this middleware to be invoked + +app.use('/api', (req, res: express.Response, next) => { + var key = req.query['api-key']; + + // key isnt present + if (!key) return next(merror(400, 'api key required')); + + // key is invalid + if (!~apiKeys.indexOf(key)) return next(merror(401, 'invalid api key')); + + // all good, store req.key for route access + req.key = key; + next(); +}); + +// position our routes above the error handling middleware, +// and below our API middleware, since we want the API validation +// to take place BEFORE our routes +app.use(app.router); + +// middleware with an arity of 4 are considered +// error handling middleware. When you next(err) +// it will be passed through the defined middleware +// in order, but ONLY those with an arity of 4, ignoring +// regular middleware. +app.use((err, req, res: express.Response) => { + // whatever you want here, feel free to populate + // properties on `err` to treat it differently in here. + res.send(err.status || 500, { error: err.message }); +}); + +// our custom JSON 404 middleware. Since it's placed last +// it will be the last middleware called, if all others +// invoke next() and do not respond. +app.use((req: express.Request, res: express.Response) => { + res.send(404, { error: "Lame, can't find that" }); +}); + +// map of valid api keys, typically mapped to +// account info with some sort of database like redis. +// api keys do _not_ serve as authentication, merely to +// track API usage or help prevent malicious behavior etc. + +var apiKeys = ['foo', 'bar', 'baz']; + +// these two objects will serve as our faux database + +var repos = [ + { name: 'express', url: 'http://github.com/visionmedia/express' } + , { name: 'stylus', url: 'http://github.com/learnboost/stylus' } + , { name: 'cluster', url: 'http://github.com/learnboost/cluster' } +]; + +var userRepos = { + tobi: [repos[0], repos[1]] + , loki: [repos[1]] + , jane: [repos[2]] +}; + +// we now can assume the api key is valid, +// and simply expose the data + +app.get('/api/users', (req: express.Request, res: express.Response) => { + res.send(users); +}); + +app.get('/api/repos', (req: express.Request, res: express.Response) => { + res.send(repos); +}); + +app.get('/api/user/:name/repos', (req: express.Request, res: express.Response, next) => { + var name = req.params.name + , user = userRepos[name]; + + if (user) res.send(user); + else next(); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express server listening on port 3000'); +} + +////// + +var router = new express.Router(); + +router.get('/', function (req, resp, next?) { + resp.send('response from router'); + resp.end(); + if (next) { + next(); + } +}); + +function test_general() { + + app.use((err, req, res: express.Response) => { + console.error(err.stack); + res.send(500, 'Something broke!'); + }); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); + app.use(() => {}); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); + + app.get('/', (req: express.Request, res: express.Response) => { + res.send('hello world'); + }); + + app.listen(3000); + + app.set('title', 'My Site'); + app.get('title'); + + app.enable('trust proxy'); + app.get('trust proxy'); + + app.disable('trust proxy'); + app.get('trust proxy'); + + app.enabled('trust proxy'); + + app.configure(() => { + app.set('title', 'My Application'); + }); + + app.configure('development', () => { + app.set('db uri', 'localhost/dev'); + }); + + app.configure('stage', 'production', () => {}); + + app.configure('1', '2', '3', () => {}); + + app.use((req: express.Request, res: express.Response) => { + res.send('Hello World'); + }); + + app.engine('jade', require('jade').__express); + + var User; + app.param('user', (req: express.Request, res: express.Response, next, id) => { + User.find(id, (err, user) =>{ + if (err) { + next(err); + } else if (user) { + req.user = user; + next(); + } else { + next(new Error('failed to load user')); + } + }); + }); + + app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req: express.Request, res: express.Response) => { + var from = req.params[0]; + var to = req.params[1] || 'HEAD'; + res.send('commit range ' + from + '..' + to); + }); + + app.locals.title = 'My App'; + app.locals.strftime = require('strftime'); + + var requireAuthentication; + var loadUser = () => {}; + app.all('*', requireAuthentication, loadUser); + app.all('*', loadUser); + app.all('*', loadUser, loadUser, loadUser); + + app.locals.title = 'My App'; + app.locals.strftime = require('strftime'); + app.locals({ + title: 'My App', + phone: '1-250-858-9990', + email: 'me@myapp.com' + }); + app.render('email', () => {}); + + app.render('email', { name: 'Tobi' }, () => {}); +} + +function test_request() { + var req: express.Request; + req.params.name; + req.params[0]; + req.query.q; + req.body.user.name; + app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })); + req.param('name'); + req.route; + req.cookies.name; + req.signedCookies; + req.get('Content-Type'); + req.accepts('html'); + req.accepts(['html', 'json']); + req.is('html'); + req.ip; + req.path; + req.host; + req.fresh; + req.stale; + req.xhr; + req.protocol; + req.subdomains; + req.originalUrl; + req.acceptedLanguages; + req.acceptedCharsets; + var charset; + req.acceptsCharset(charset); + var lang; + req.acceptsLanguage(lang); + req.session = null; +} + +function test_response() { + var res: express.Response; + res.status(404).sendfile('path/to/404.png'); + res.set('Content-Type', 'text/plain'); + res.set({ + 'Content-Type': 'text/plain', + 'Content-Length': '123', + 'ETag': '12345' + }); + res.get('Content-Type'); + res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); + res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }); + res.cookie('cart', { items: [1, 2, 3] }); + res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });; + res.cookie('name', 'tobi', { signed: true }); + res.cookie('name', 'tobi', { path: '/admin' }); + res.clearCookie('name', { path: '/admin' }); + res.redirect('/foo/bar'); + res.redirect('http://example.com'); + res.redirect(301, 'http://example.com'); + res.charset = 'value'; + res.send('some html'); + res.send(new Buffer('whoop')); + res.send({ some: 'json' }); + res.send('some html'); + res.send(404, 'Sorry, we cannot find that!'); + res.send(500, { error: 'something blew up' }); + res.send(200); + res.set('Content-Type', 'text/html'); + res.send(new Buffer('some html')); + res.send('some html'); + res.send({ user: 'tobi' }); + res.send([1, 2, 3]); + res.json(null); + res.json({ user: 'tobi' }); + res.json(500, { error: 'message' }); + res.jsonp(null); + res.jsonp({ user: 'tobi' }); + res.jsonp(500, { error: 'message' }); + res.jsonp({ user: 'tobi' }); + res.type('application/json'); + + res.format({ + 'text/plain': () => { + res.send('hey'); + }, + 'text/html': () => { + res.send('hey'); + }, + 'application/json': () => { + res.send({ message: 'hey' }); + } + }); + + res.attachment(); + res.attachment('path/to/logo.png'); + app.get('/user/:uid/photos/:file', (req: express.Request, res: express.Response) => { + var uid = req.params.uid + , file = req.params.file; + + req.user.mayViewFilesFrom(uid, yes => { + if (yes) { + res.sendfile('/uploads/' + uid + '/' + file); + } else { + res.send(403, 'Sorry! you cant see that.'); + } + }); + }); + + res.download('/report-12345.pdf'); + res.download('/report-12345.pdf', 'report.pdf'); + res.download('/report-12345.pdf', 'report.pdf', err => { + if (err) { } else { } + }); + + res.links({ + next: 'http://api.example.com/users?page=2', + last: 'http://api.example.com/users?page=5' + }); + + app.use((req: express.Request, res: express.Response, next) => { + res.locals.user = req.user; + res.locals.authenticated = !req.user.anonymous; + next(); + }); + res.render('index', () => {}); + res.render('user', { name: 'Tobi' }, () => {}); + +} + +function test_middleware() { + app.use(express.basicAuth('username', 'password')); + app.use(express.basicAuth((user, pass) => { + return 'tj' == user && 'wahoo' == pass; + })); + app.use(express.bodyParser()); + app.use(express.json()); + app.use(express.urlencoded()); + app.use(express.multipart()); + app.use(express.logger()); + app.use(express.compress()); + app.use(express.methodOverride()); + app.use(express.bodyParser()); + app.use(express.cookieParser()); + app.use(express.cookieParser('some secret')); + app.use(express.cookieSession()); + app.use(express.directory('public')); + app.use(express.static('public')); + app.use(router.middleware); +} + +//////////////////// + +// make sure server can be shut down +var testShutdownServer = app.listen(0); +console.log('listening on port ' + testShutdownServer.address().port); +testShutdownServer.close(); diff --git a/express/express-3.1.0-tests.ts.tscparams b/express/express-3.1.0-tests.ts.tscparams new file mode 100644 index 000000000..e16c76dff --- /dev/null +++ b/express/express-3.1.0-tests.ts.tscparams @@ -0,0 +1 @@ +"" diff --git a/express/express-3.1.0.d.ts b/express/express-3.1.0.d.ts new file mode 100644 index 000000000..d5865f418 --- /dev/null +++ b/express/express-3.1.0.d.ts @@ -0,0 +1,1832 @@ +// Type definitions for Express 3.1 +// Project: http://expressjs.com +// Definitions by: Boris Yankov +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/* =================== USAGE =================== + + import express = require('express'); + var app = express(); + + =============================================== */ + +/// + + +declare module Express { + + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example passport.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/passport/passport.d.ts) + export interface Request { } + export interface Response { } + export interface Application { } +} + + +declare module "express" { + import http = require('http'); + + // Merged declaration, e is both a callable function and a namespace + function e(): e.Express; + + module e { + interface IRoute { + path: string; + + method: string; + + callbacks: Function[]; + + regexp: any; + + /** + * Check if this route matches `path`, if so + * populate `.params`. + */ + match(path: string): boolean; + } + + class Route implements IRoute { + path: string; + + method: string; + + callbacks: Function[]; + + regexp: any; + match(path: string): boolean; + + /** + * Initialize `Route` with the given HTTP `method`, `path`, + * and an array of `callbacks` and `options`. + * + * Options: + * + * - `sensitive` enable case-sensitive routes + * - `strict` enable strict matching for trailing slashes + * + * @param method + * @param path + * @param callbacks + * @param options + */ + new (method: string, path: string, callbacks: Function[], options: any): Route; + } + + interface IRouter { + /** + * 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, fn: Function): T; + + param(name: string[], fn: Function): T; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; + + all(path: string, ...callbacks: Function[]): void; + + get(name: string, ...handlers: RequestFunction[]): T; + + get(name: RegExp, ...handlers: RequestFunction[]): T; + + post(name: string, ...handlers: RequestFunction[]): T; + + post(name: RegExp, ...handlers: RequestFunction[]): T; + + put(name: string, ...handlers: RequestFunction[]): T; + + put(name: RegExp, ...handlers: RequestFunction[]): T; + + del(name: string, ...handlers: RequestFunction[]): T; + + del(name: RegExp, ...handlers: RequestFunction[]): T; + + patch(name: string, ...handlers: RequestFunction[]): T; + + patch(name: RegExp, ...handlers: RequestFunction[]): T; + } + + export class Router implements IRouter { + new (options?: any): Router; + + middleware (): any; + + param(name: string, fn: Function): Router; + + param(name: any[], fn: Function): Router; + + all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; + + all(path: string, ...callbacks: Function[]): void; + + get(name: string, ...handlers: RequestFunction[]): Router; + + get(name: RegExp, ...handlers: RequestFunction[]): Router; + + post(name: string, ...handlers: RequestFunction[]): Router; + + post(name: RegExp, ...handlers: RequestFunction[]): Router; + + put(name: string, ...handlers: RequestFunction[]): Router; + + put(name: RegExp, ...handlers: RequestFunction[]): Router; + + del(name: string, ...handlers: RequestFunction[]): Router; + + del(name: RegExp, ...handlers: RequestFunction[]): Router; + + patch(name: string, ...handlers: RequestFunction[]): Router; + + patch(name: RegExp, ...handlers: RequestFunction[]): Router; + } + + interface Handler { + (req: Request, res: Response, next?: Function): void; + } + + interface CookieOptions { + maxAge?: number; + signed?: boolean; + expires?: Date; + httpOnly?: boolean; + path?: string; + domain?: string; + secure?: boolean; + } + + interface Errback { (err: Error): void; } + + interface Session { + /** + * Update reset `.cookie.maxAge` to prevent + * the cookie from expiring when the + * session is still active. + * + * @return {Session} for chaining + * @api public + */ + touch(): Session; + + /** + * Reset `.maxAge` to `.originalMaxAge`. + */ + resetMaxAge(): Session; + + /** + * Save the session data with optional callback `fn(err)`. + */ + save(fn: Function): Session; + + /** + * Re-loads the session data _without_ altering + * the maxAge properties. Invokes the callback `fn(err)`, + * after which time if no exception has occurred the + * `req.session` property will be a new `Session` object, + * although representing the same session. + */ + reload(fn: Function): Session; + + /** + * Destroy `this` session. + */ + destroy(fn: Function): Session; + + /** + * Regenerate this request's session. + */ + regenerate(fn: Function): Session; + + user: any; + + error: string; + + success: string; + + views: any; + + count: number; + } + + interface Request extends http.ServerRequest, Express.Request { + + session: Session; + + /** + * 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; + + /** + * Check if the given `charset` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param charset + */ + acceptsCharset(charset: string): boolean; + + /** + * Check if the given `lang` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param lang + */ + acceptsLanguage(lang: string): boolean; + + /** + * 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 an array of Accepted languages + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Language: en;q=.5, en-us + * ['en-us', 'en'] + */ + acceptedLanguages: any[]; + + /** + * 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[]; + + /** + * 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 basic auth credentials. + * + * Examples: + * + * // http://tobi:hello@example.com + * req.auth + * // => { username: 'tobi', password: 'hello' } + */ + auth: any; + + /** + * 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. + */ + 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; + + /** + * 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; + } + + 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 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; + } + + interface RequestFunction { + (req: Request, res: Response, next: Function): 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; + + /** + * Proxy `connect#use()` to apply settings to + * mounted applications. + **/ + use(route: string, callback?: Function): Application; + + use(route: string, server: Application): Application; + + use(callback: Function): Application; + + use(server: Application): Application; + + /** + * 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; + + param(name: string, fn: Function): Application; + + param(name: string[], fn: Function): Application; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set (setting: string, val: string): Application; + + get(name: string): string; + + get(name: string, ...handlers: RequestFunction[]): Application; + + get(name: RegExp, ...handlers: RequestFunction[]): 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(env: 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; + + configure(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: 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; + } + + /** + * Body parser: + * + * Parse request bodies, supports _application/json_, + * _application/x-www-form-urlencoded_, and _multipart/form-data_. + * + * This is equivalent to: + * + * app.use(connect.json()); + * app.use(connect.urlencoded()); + * app.use(connect.multipart()); + * + * Examples: + * + * connect() + * .use(connect.bodyParser()) + * .use(function(req, res) { + * res.end('viewing user ' + req.body.user.name); + * }); + * + * $ curl -d 'user[name]=tj' http://local/ + * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ + * + * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. + * + * @param options + */ + function bodyParser(options?: any): Handler; + + /** + * Error handler: + * + * Development error handler, providing stack traces + * and error message responses for requests accepting text, html, + * or json. + * + * Text: + * + * By default, and when _text/plain_ is accepted a simple stack trace + * or error message will be returned. + * + * JSON: + * + * When _application/json_ is accepted, connect will respond with + * an object in the form of `{ "error": error }`. + * + * HTML: + * + * When accepted connect will output a nice html stack trace. + */ + function errorHandler(opts?: any): Handler; + + /** + * Method Override: + * + * Provides faux HTTP method support. + * + * Pass an optional `key` to use when checking for + * a method override, othewise defaults to _\_method_. + * The original method is available via `req.originalMethod`. + * + * @param key + */ + function methodOverride(key?: string): Handler; + + /** + * Cookie parser: + * + * Parse _Cookie_ header and populate `req.cookies` + * with an object keyed by the cookie names. Optionally + * you may enabled signed cookie support by passing + * a `secret` string, which assigns `req.secret` so + * it may be used by other middleware. + * + * Examples: + * + * connect() + * .use(connect.cookieParser('optional secret string')) + * .use(function(req, res, next){ + * res.end(JSON.stringify(req.cookies)); + * }) + * + * @param secret + */ + function cookieParser(secret?: string): Handler; + + /** + * Session: + * + * Setup session store with the given `options`. + * + * Session data is _not_ saved in the cookie itself, however + * cookies are used, so we must use the [cookieParser()](cookieParser.html) + * middleware _before_ `session()`. + * + * Examples: + * + * connect() + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) + * + * Options: + * + * - `key` cookie name defaulting to `connect.sid` + * - `store` session store instance + * - `secret` session cookie is signed with this secret to prevent 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") + * + * Cookie option: + * + * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set + * so the cookie becomes a browser-session cookie. When the user closes the + * browser the cookie (and session) will be removed. + * + * ## req.session + * + * To store or access session data, simply use the request property `req.session`, + * which is (generally) serialized as JSON by the store, so nested objects + * are typically fine. For example below is a user-specific view counter: + * + * connect() + * .use(connect.favicon()) + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) + * .use(function(req, res, next){ + * var sess = req.session; + * if (sess.views) { + * res.setHeader('Content-Type', 'text/html'); + * res.write('

views: ' + 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 + */ + function session(options?: any): Handler; + + /** + * Hash the given `sess` object omitting changes + * to `.cookie`. + * + * @param sess + */ + function 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 + */ + function static(root: string, options?: any): 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 + */ + 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; + + /** + * 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 + */ + function compress(options?: any): 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 + */ + function cookieSession(options?: any): 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 + */ + export function csrf(options?: {value?: Function}): 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 + */ + function directory(root: string, options?: any): 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 + */ + export function favicon(path?: string, options?: any): 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 + */ + function json(options?: any): 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) + */ + function limit(bytes: number): Handler; + + function limit(bytes: string): 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') + */ + function logger(options: string): Handler; + + function logger(options: Function): Handler; + + function logger(options?: any): Handler; + + /** + * Compile `fmt` into a function. + * + * @param fmt + */ + function compile(fmt: string): Handler; + + /** + * Define a token function with the given `name`, + * and callback `fn(req, res)`. + * + * @param name + * @param fn + */ + function token(name: string, fn: Function): any; + + /** + * Define a `fmt` with the given `name`. + */ + function format(name: string, str: string): any; + + function 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. + */ + function query(options: any): Handler; + + /** + * Reponse time: + * + * Adds the `X-Response-Time` header displaying the response + * duration in milliseconds. + */ + function responseTime(): 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 + */ + function staticCache(options: any): 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`. + */ + function timeout(ms: number): 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 + */ + function vhost(hostname: string, server: any): Handler; + + function urlencoded(): any; + + function multipart(): any; + + } + + export = e; +} + diff --git a/express/express-tests.ts b/express/express-tests.ts index 57d1d638c..cda1e3e2e 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -3,1496 +3,19 @@ import express = require('express'); var app = express(); -////////////////////////// +app.engine('jade', require('jade').__express); +app.engine('html', require('ejs').renderFile); -var hash: any; - -// config - -app.set('view engine', 'ejs'); -app.set('views', __dirname + '/views'); - -// middleware - -app.use(express.bodyParser()); -app.use(express.cookieParser('shhhh, very secret')); -app.use(express.session()); - -// Session-persisted message middleware - -app.use((req: express.Request, res: express.Response, next) => { - var err = req.session.error - , msg = req.session.success; - delete req.session.error; - delete req.session.success; - res.locals.message = ''; - if (err) res.locals.message = '

' + err + '

'; - if (msg) res.locals.message = '

' + msg + '

'; - next(); -}); - -// dummy database - -var users = { - tj: { name: 'tj' } -}; - -// when you create a user, generate a salt -// and hash the password ('foobar' is the pass here) - -hash('foobar', (err, salt, hash) => { - if (err) throw err; - // store the salt & hash in the "db" - users.tj.salt = salt; - users.tj.hash = hash; -}); - - -// Authenticate using our plain-object database of doom! - -function authenticate(name, pass, fn) { - if (!module.parent) console.log('authenticating %s:%s', name, pass); - var user = users[name]; - // query the db for the given username - if (!user) return fn(new Error('cannot find user')); - // apply the same algorithm to the POSTed password, applying - // the hash against the pass / salt, if there is a match we - // found the user - hash(pass, user.salt, (err, hash) => { - if (err) return fn(err); - if (hash == user.hash) return fn(null, user); - fn(new Error('invalid password')); - }); -} - -function restrict(req: express.Request, res: express.Response, next?: Function) { - if (req.session.user) { - next(); - } else { - req.session.error = 'Access denied!'; - res.redirect('/login'); - } -} - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('login'); -}); - -app.get('/restricted', restrict, (req: express.Request, res: express.Response) => { - res.send('Wahoo! restricted area, click to logout'); -}); - -app.get('/logout', (req: express.Request, res: express.Response) => { - // destroy the user's session to log them out - // will be re-created next request - req.session.destroy(() => { - res.redirect('/'); - }); -}); - -app.get('/login', (req: express.Request, res: express.Response) => { - res.render('login'); -}); - -app.post('/login', (req: express.Request, res: express.Response) => { - authenticate(req.body.username, req.body.password, (err, user) => { - if (user) { - // Regenerate session when signing in - // to prevent fixation - req.session.regenerate(() => { - // Store the user's primary key - // in the session store to be retrieved, - // or in this case the entire user object - req.session.user = user; - req.session.success = 'Authenticated as ' + user.name - + ' click to logout. ' - + ' You may now access /restricted.'; - res.redirect('back'); - }); - } else { - req.session.error = 'Authentication failed, please check your ' - + ' username and password.' - + ' (use "tj" and "foobar")'; - res.redirect('login'); - } - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////// - -app.set('views', __dirname); -app.set('view engine', 'jade'); - -var pets = []; - -var n = 1000; -while (n--) { - pets.push({ name: 'Tobi', age: 2, species: 'ferret' }); - pets.push({ name: 'Loki', age: 1, species: 'ferret' }); - pets.push({ name: 'Jane', age: 6, species: 'ferret' }); -} - -app.use(express.logger('dev')); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('pets', { pets: pets }); -}); - -app.listen(3000); -console.log('Express listening on port 3000'); - -///////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.format({ - html: () => { - res.send('
    ' + users.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('') + '
'); - }, - - text: () => { - res.send(users.map(user => { - return ' - ' + user.name + '\n'; - }).join('')); - }, - - json: () => { - res.json(users); - } - }); -}); - -// or you could write a tiny middleware like -// this to abstract make things a bit more declarative: - -function format(mod) { - var obj = require(mod); - return (req: express.Request, res: express.Response) => { - res.format(obj); - }; -} - -app.get('/users', format('./users')); - -if (!module.parent) { - app.listen(3000); - console.log('listening on port 3000'); -} - -///////////////////////// - -// add favicon() before logger() so -// GET /favicon.ico requests are not -// logged, because this middleware -// reponds to /favicon.ico and does not -// call next() -app.use(express.favicon()); - -// custom log format -if ('test' != process.env.NODE_ENV) - app.use(express.logger(':method :url')); - -// parses request cookies, populating -// req.cookies and req.signedCookies -// when the secret is passed, used -// for signing the cookies. -app.use(express.cookieParser('my secret here')); - -// parses json, x-www-form-urlencoded, and multipart/form-data -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - if (req.cookies.remember) { - res.send('Remembered :). Click to forget!.'); - } else { - res.send('

Check to ' - + '.

'); - } -}); - -app.get('/forget', (req: express.Request, res: express.Response) => { - res.clearCookie('remember'); - res.redirect('back'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - var minute = 60000; - if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); - res.redirect('back'); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// ignore GET /favicon.ico -app.use(express.favicon()); - -// pass a secret to cookieParser() for signed cookies -app.use(express.cookieParser('manny is cool')); - -// add req.session cookie support -app.use(express.cookieSession()); - -// do something with the session -app.use(count); - -// custom middleware -function count(req: express.Request, res: express.Response) { - req.session.count = req.session.count || 0; - var n = req.session.count++; - res.send('viewed ' + n + ' times\n'); -} - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -/////////////// - -var api = app; - -app.use(express.static(__dirname + '/public')); - -// api middleware - -api.use(express.logger('dev')); -api.use(express.bodyParser()); - -/** - * CORS support. - */ - -api.all('*', (req: express.Request, res: express.Response, next) => { - if (!req.get('Origin')) return next(); - // use "*" here to accept any origin - res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); - res.set('Access-Control-Allow-Methods', 'GET, POST'); - res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'); - // res.set('Access-Control-Allow-Max-Age', 3600); - if ('OPTIONS' == req.method) return res.send(200); - next(); -}); - -/** - * POST a user. - */ - -api.post('/user', (req: express.Request, res: express.Response) => { - console.log(req.body); - res.send(201); -}); - -app.listen(3000); -api.listen(3001); - -console.log('app listening on 3000'); -console.log('api listening on 3001'); - -//////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send(''); -}); - -// /files/* is accessed via req.params[0] -// but here we name it :file -app.get('/files/:file(*)', (req: express.Request, res: express.Response) => { - var file = req.params.file - , path = __dirname + '/files/' + file; - - res.download(path); -}); - -// error handling middleware. Because it's -// below our routes, you will be able to -// "intercept" errors, otherwise Connect -// will respond with 500 "Internal Server Error". -app.use((err, req, res: express.Response, next) => { - // special-case 404s, - // remember you could - // render a 404 template here - if (404 == err.status) { - res.statusCode = 404; - res.send('Cant find that file, sorry!'); - } else { - next(err); - } -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// Register ejs as .html. If we did -// not call this, we would need to -// name our views foo.ejs instead -// of foo.html. The __express method -// is simply a function that engines -// use to hook into the Express view -// system by default, so if we want -// to change "foo.ejs" to "foo.html" -// we simply pass _any_ function, in this -// case `ejs.__express`. - -app.engine('.html', require('ejs').__express); - -// Optional since express defaults to CWD/views - -app.set('views', __dirname + '/views'); - -// Without this you would need to -// supply the extension to res.render() -// ex: res.render('users.html'). -app.set('view engine', 'html'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('users', { - users: users, - title: "EJS example", - header: "Some users" - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express app started on port 3000'); -} - -//////////////////// - -var test: any; - -if (!test) app.use(express.logger('dev')); -app.use(app.router); - -// the error handler is strategically -// placed *below* the app.router; if it -// were above it would not receive errors -// from app.get() etc -app.use(error); - -// error handling middleware have an arity of 4 -// instead of the typical (req: express.Request, res: express.Response, next), -// otherwise they behave exactly like regular -// middleware, you may have several of them, -// in different orders etc. - -function error(err, req, res: express.Response, next) { - // log it - if (!test) console.error(err.stack); - - // respond with 500 "Internal Server Error". - res.send(500); -} - -app.get('/', () => { - // Caught and passed down to the errorHandler middleware - throw new Error('something broke!'); -}); - -app.get('/next', (req: express.Request, res: express.Response, next) => { - // We can also pass exceptions to next() - process.nextTick(() => { - next(new Error('oh no!')); - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - -var silent: any; - -// general config -app.set('views', __dirname + '/views'); -app.set('view engine', 'jade'); - -// our custom "verbose errors" setting -// which we can use in the templates -// via settings['verbose errors'] -app.enable('verbose errors'); - -// disable them in production -// use $ NODE_ENV=production node examples/error-pages -if ('production' == app.settings.env) { - app.disable('verbose errors'); -} - -app.use(express.favicon()); - -silent || app.use(express.logger('dev')); - -// "app.router" positions our routes -// above the middleware defined below, -// this means that Express will attempt -// to match & call routes _before_ continuing -// on, at which point we assume it's a 404 because -// no route has handled the request. - -app.use(app.router); - -// Since this is the last non-error-handling -// middleware use()d, we assume 404, as nothing else -// responded. - -// $ curl http://localhost:3000/notfound -// $ curl http://localhost:3000/notfound -H "Accept: application/json" -// $ curl http://localhost:3000/notfound -H "Accept: text/plain" - -app.use((req: express.Request, res: express.Response) => { - res.status(404); - - // respond with html page - if (req.accepts('html')) { - res.render('404', { url: req.url }); - return; - } - - // respond with json - if (req.accepts('json')) { - res.send({ error: 'Not found' }); - return; - } - - // default to plain-text. send() - res.type('txt').send('Not found'); -}); - -// error-handling middleware, take the same form -// as regular middleware, however they require an -// arity of 4, aka the signature (err, req, res: express.Response, next). -// when connect has an error, it will invoke ONLY error-handling -// middleware. - -// If we were to next() here any remaining non-error-handling -// middleware would then be executed, or if we next(err) to -// continue passing the error, only error-handling middleware -// would remain being executed, however here -// we simply respond with an error page. - -app.use((err, req, res: express.Response) => { - // we may use properties of the error object - // here and next(err) appropriately, or if - // we possibly recovered from the error, simply next(). - res.status(err.status || 500); - res.render('500', { error: err }); -}); - -// Routes - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index.jade'); -}); - -app.get('/404', (req: express.Request, res: express.Response, next) => { - // trigger a 404 since no other middleware - // will match /404 after this one, and we're not - // responding here - next(); -}); - -app.get('/403', (req: express.Request, res: express.Response, next) => { - // trigger a 403 error - var err = new Error('not allowed!'); - err.status = 403; - next(err); -}); - -app.get('/500', (req: express.Request, res: express.Response, next) => { - // trigger a generic (500) error - next(new Error('keyboard cat!')); -}); - -if (!module.parent) { - app.listen(3000); - //silent ||  console.log('Express started on port 3000'); -} - -/////////////// - -var fs: any; -var md: any; - -app.set('view engine', 'jade'); -app.set('views', __dirname + '/views'); - -function User(name) { - this.private = 'heyyyy'; - this.secret = 'something'; - this.name = name; - this.id = 123; -} - -// You'll probably want to do -// something like this so you -// dont expose "secret" data. - -User.prototype.toJSON = function () { - return { - id: this.id, - name: this.name - }; -}; - -app.use(express.logger('dev')); - -// earlier on expose an object -// that we can tack properties on. -// all res.locals props are exposed -// to the templates, so "expose" will -// be present. - -app.use((req: express.Request, res: express.Response, next) => { - res.locals.expose = {}; - // you could alias this as req or res.expose - // to make it shorter and less annoying - next(); -}); - -// pretend we loaded a user - -app.use((req: express.Request, res: express.Response, next) => { - req.user = new User('Tobi'); - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user'); -}); - -app.get('/user', (req: express.Request, res: express.Response) => { - // we only want to expose the user - // to the client for this route: - res.locals.expose.user = req.user; - res.render('page'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello World'); -}); - -app.listen(3000); -console.log('Express started on port 3000'); - -//////////////////// - -// register .md as an engine in express view system - -app.engine('md', (path, options, fn) => { - fs.readFile(path, 'utf8', (err, str) => { - if (err) return fn(err); - try { - var html = md(str); - html = html.replace(/\{([^}]+)\}/g, (_, name) => { - return options[name] || ''; - }); - fn(null, html); - } catch (err) { - fn(err); - } - }); -}); - -app.set('views', __dirname + '/views'); - -// make it the default so we dont need .md -app.set('view engine', 'md'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index', { title: 'Markdown Example' }); -}); - -app.get('/fail', (req: express.Request, res: express.Response) => { - res.render('missing', { title: 'Markdown Example' }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////////// - -var mformat: any; - -// bodyParser in connect 2.x uses node-formidable to parse -// the multipart form data. -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('
' - + '

Title:

' - + '

Image:

' - + '

' - + '
'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - // the uploaded file can be found as `req.files.image` and the - // title field as `req.body.title` - res.send(mformat('\nuploaded %s (%d Kb) to %s as %s' - , req.files.image.name - , req.files.image.size / 1024 | 0 - , req.files.image.path - , req.body.title)); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - - -// first: -// $ npm install redis online -// $ redis-server - -/** - * Module dependencies. - */ - -var online: any; -var db: any; - -// online - -online = online(db); - -// activity tracking, in this case using -// the UA string, you would use req.user.id etc - -app.use((req: express.Request, res: express.Response, next) => { - // fire-and-forget - online.add(req.headers['user-agent']); - next(); -}); - -/** - * List helper. - */ - -function list(ids) { - return '
    ' + ids.map(id => { - return '
  • ' + id + '
  • '; - }).join('') + '
'; -} - -/** - * GET users online. - */ - -app.get('/', (req: express.Request, res: express.Response, next) => { - online.last(5, (err, ids) => { - if (err) return next(err); - res.send('

Users online: ' + ids.length + '

' + list(ids)); - }); -}); - -app.listen(3000); -console.log('listening on port 3000'); - -/////////////////// - -// Convert :to and :from to integers - -app.param(['to', 'from'], (req: express.Request, res: express.Response, next, num, name) => { - req.params[name] = num = parseInt(num, 10); - if (isNaN(num)) { - next(new Error('failed to parseInt ' + num)); - } else { - next(); - } -}); - -// Load user by id - -app.param('user', (req: express.Request, res: express.Response, next, id) => { - if (req.user = users[id]) { - next(); - } else { - next(new Error('failed to find user')); - } -}); - -/** - * GET index. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Visit /user/0 or /users/0-2'); -}); - -/** - * GET :user. - */ - -app.get('/user/:user', (req: express.Request, res: express.Response) => { - res.send('user ' + req.user.name); -}); - -/** - * GET users :from - :to. - */ - -app.get('/users/:from-:to', (req: express.Request, res: express.Response) => { - var from = req.params.from - , to = req.params.to - , names = users.map(user => { return user.name; }); - res.send('users ' + names.slice(from, to).join(', ')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - -// Ad-hoc example resource method - -app.resource = function (path, obj) { - this.get(path, obj.index); - this.get(path + '/:a..:b.:format?', (req: express.Request, res: express.Response) => { - var a = parseInt(req.params.a, 10) - , b = parseInt(req.params.b, 10) - , format = req.params.format; - obj.range(req, res, a, b, format); - }); - this.get(path + '/:id', obj.show); - this.del(path + '/:id', obj.destroy); -}; - -// Fake controller. - -var FUser = { - index: (req: express.Request, res: express.Response) => { - res.send(users); - }, - show: (req: express.Request, res: express.Response) => { - res.send(users[req.params.id] || { error: 'Cannot find user' }); - }, - destroy: (req: express.Request, res: express.Response) => { - var id = req.params.id; - var destroyed = id in users; - delete users[id]; - res.send(destroyed ? 'destroyed' : 'Cannot find user'); - }, - range: (req: express.Request, res: express.Response, a, b, format) => { - var range = users.slice(a, b + 1); - switch (format) { - case 'json': - res.send(range); - break; - case 'html': - default: - var html = '
    ' + range.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('\n') + '
'; - res.send(html); - break; - } - } -}; - -// curl http://localhost:3000/users -- responds with all users -// curl http://localhost:3000/users/1 -- responds with user 1 -// curl http://localhost:3000/users/4 -- responds with error -// curl http://localhost:3000/users/1..3 -- responds with several users -// curl -X DELETE http://localhost:3000/users/1 -- deletes the user - -app.resource('/users', FUser); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send([ - '

Examples:

    ' - , '
  • GET /users
  • ' - , '
  • GET /users/1
  • ' - , '
  • GET /users/3
  • ' - , '
  • GET /users/1..3
  • ' - , '
  • GET /users/1..3.json
  • ' - , '
  • DELETE /users/4
  • ' - , '
' - ].join('\n')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - - -var verbose: any; - -app.map = (a, route) => { - route = route || ''; - for (var key in a) { - switch (typeof a[key]) { - // { '/path': { ... }} - case 'object': - app.map(a[key], route + key); - break; - // get: function(){ ... } - case 'function': - if (verbose) console.log('%s %s', key, route); - app[key](route, a[key]); - break; - } - } -}; - -var users2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user list'); - }, - - get: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete users'); - } -}; - -var pets2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid + '\'s pets'); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid); - } -}; - -app.map({ - '/users': { - get: users2.list, - del: users2.del, - '/:uid': { - get: users.get , - '/pets': { - get: pets2.list, - '/:pid': { - del: pets2.del - } - } - } - } -}); - -app.listen(3000); - -/////////////////////////// - -// Example requests: -// curl http://localhost:3000/user/0 -// curl http://localhost:3000/user/0/edit -// curl http://localhost:3000/user/1 -// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) -// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) - -function loadUser(req: express.Request, res: express.Response, next) { - // You would fetch your user from the db - var user = users[req.params.id]; - if (user) { - req.user = user; - next(); - } else { - next(new Error('Failed to load user ' + req.params.id)); - } -} - -function andRestrictToSelf(req: express.Request, res: express.Response, next) { - // If our authenticated user is the user we are viewing - // then everything is fine :) - if (req.authenticatedUser.id == req.user.id) { - next(); - } else { - // You may want to implement specific exceptions - // such as UnauthorizedError or similar so that you - // can handle these can be special-cased in an error handler - // (view ./examples/pages for this) - next(new Error('Unauthorized')); - } -} - -function andRestrictTo(role) { - return (req: express.Request, res: express.Response, next) => { - if (req.authenticatedUser.role == role) { - next(); - } else { - next(new Error('Unauthorized')); - } - }; -} - -// Middleware for faux authentication -// you would of course implement something real, -// but this illustrates how an authenticated user -// may interact with middleware - -app.use((req: express.Request, res: express.Response, next) => { - req.authenticatedUser = users[0]; - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user/0'); -}); - -app.get('/user/:id', loadUser, (req: express.Request, res: express.Response) => { - res.send('Viewing user ' + req.user.name); -}); - -app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req: express.Request, res: express.Response) => { - res.send('Editing user ' + req.user.name); -}); - -app.del('/user/:id', loadUser, andRestrictTo('admin'), (req: express.Request, res: express.Response) => { - res.send('Deleted user ' + req.user.name); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -///////////////////////// - -app.set('view engine', 'jade'); -app.set('views', __dirname); - -// populate search - -db.sadd('ferret', 'tobi'); -db.sadd('ferret', 'loki'); -db.sadd('ferret', 'jane'); -db.sadd('cat', 'manny'); -db.sadd('cat', 'luna'); - -/** - * GET the search page. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('search'); -}); - -/** - * GET search for :query. - */ - -app.get('/search/:query?', (req: express.Request, res: express.Response) => { - var query = req.params.query; - db.smembers(query, (err, vals) => { - if (err) return res.send(500); - res.send(vals); - }); -}); - -/** - * GET client javascript. Here we use sendfile() - * because serving __dirname with the static() middleware - * would also mean serving our server "index.js" and the "search.jade" - * template. - */ - -app.get('/client.js', (req: express.Request, res: express.Response) => { - res.sendfile(__dirname + '/client.js'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////// - -app.use(express.logger('dev')); - -// Required by session() middleware -// pass the secret for signed cookies -// (required by session()) -app.use(express.cookieParser('keyboard cat')); - -// Populates req.session -app.use(express.session()); - -app.get('/', (req: express.Request, res: express.Response) => { - var body = ''; - if (req.session.views) { - ++req.session.views; - } else { - req.session.views = 1; - body += '

First time visiting? view this page in several browsers :)

'; - } - res.send(body + '

viewed ' + req.session.views + ' times.

'); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////////// - -// log requests -app.use(express.logger('dev')); - -// express on its own has no notion -// of a "file". The express.static() -// middleware checks for a file matching -// the `req.path` within the directory -// that you pass it. In this case "GET /js/app.js" -// will look for "./public/js/app.js". - -app.use(express.static(__dirname + '/public')); - -// if you wanted to "prefix" you may use -// the mounting feature of Connect, for example -// "GET /static/js/app.js" instead of "GET /js/app.js". -// The mount-path "/static" is simply removed before -// passing control to the express.static() middleware, -// thus it serves the file correctly by ignoring "/static" app.use('/static', express.static(__dirname + '/public')); -// if for some reason you want to serve files from -// several directories, you can use express.static() -// multiple times! Here we're passing "./public/css", -// this will allow "GET /style.css" instead of "GET /css/style.css": -app.use(express.static(__dirname + '/public/css')); - -// this examples does not have any routes, however -// you may `app.use(app.router)` before or after these -// static() middleware. If placed before them your routes -// will be matched BEFORE file serving takes place. If placed -// after as shown here then file serving is performed BEFORE -// any routes are hit: -app.use(app.router); - -app.listen(3000); -console.log('listening on port 3000'); -console.log('try:'); -console.log(' GET /hello.txt'); -console.log(' GET /js/app.js'); -console.log(' GET /css/style.css'); - -////////////////// - -/* -edit /etc/vhosts: - -127.0.0.1 foo.example.com -127.0.0.1 bar.example.com -127.0.0.1 example.com -*/ - -// Main app - -var main = express(); - -main.use(express.logger('dev')); - -main.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello from main app!'); -}); - -main.get('/:sub', (req: express.Request, res: express.Response) => { - res.send('requsted ' + req.params.sub); -}); - -// Redirect app - -var redirect = express(); - -redirect.all('*', (req: express.Request, res: express.Response) => { - console.log(req.subdomains); - res.redirect('http://example.com:3000/' + req.subdomains[0]); -}); - -app.use(express.vhost('*.example.com', redirect)); -app.use(express.vhost('example.com', main)); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////// - -// create an error with .status. we -// can then use the property in our -// custom error handler (Connect repects this prop as well) - -function merror(status, msg) { - var err = new Error(msg); - err.status = status; - return err; -} - -// if we wanted to supply more than JSON, we could -// use something similar to the content-negotiation -// example. - -// here we validate the API key, -// by mounting this middleware to /api -// meaning only paths prefixed with "/api" -// will cause this middleware to be invoked - -app.use('/api', (req, res: express.Response, next) => { - var key = req.query['api-key']; - - // key isnt present - if (!key) return next(merror(400, 'api key required')); - - // key is invalid - if (!~apiKeys.indexOf(key)) return next(merror(401, 'invalid api key')); - - // all good, store req.key for route access - req.key = key; +// simple logger +app.use(function(req, res, next){ + console.log('%s %s', req.method, req.url); next(); }); -// position our routes above the error handling middleware, -// and below our API middleware, since we want the API validation -// to take place BEFORE our routes -app.use(app.router); - -// middleware with an arity of 4 are considered -// error handling middleware. When you next(err) -// it will be passed through the defined middleware -// in order, but ONLY those with an arity of 4, ignoring -// regular middleware. -app.use((err, req, res: express.Response) => { - // whatever you want here, feel free to populate - // properties on `err` to treat it differently in here. - res.send(err.status || 500, { error: err.message }); +app.get('/', function(req, res){ + res.send('hello world'); }); -// our custom JSON 404 middleware. Since it's placed last -// it will be the last middleware called, if all others -// invoke next() and do not respond. -app.use((req: express.Request, res: express.Response) => { - res.send(404, { error: "Lame, can't find that" }); -}); - -// map of valid api keys, typically mapped to -// account info with some sort of database like redis. -// api keys do _not_ serve as authentication, merely to -// track API usage or help prevent malicious behavior etc. - -var apiKeys = ['foo', 'bar', 'baz']; - -// these two objects will serve as our faux database - -var repos = [ - { name: 'express', url: 'http://github.com/visionmedia/express' } - , { name: 'stylus', url: 'http://github.com/learnboost/stylus' } - , { name: 'cluster', url: 'http://github.com/learnboost/cluster' } -]; - -var userRepos = { - tobi: [repos[0], repos[1]] - , loki: [repos[1]] - , jane: [repos[2]] -}; - -// we now can assume the api key is valid, -// and simply expose the data - -app.get('/api/users', (req: express.Request, res: express.Response) => { - res.send(users); -}); - -app.get('/api/repos', (req: express.Request, res: express.Response) => { - res.send(repos); -}); - -app.get('/api/user/:name/repos', (req: express.Request, res: express.Response, next) => { - var name = req.params.name - , user = userRepos[name]; - - if (user) res.send(user); - else next(); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -////// - -var router = new express.Router(); - -router.get('/', function (req, resp, next?) { - resp.send('response from router'); - resp.end(); - if (next) { - next(); - } -}); - -function test_general() { - - app.use((err, req, res: express.Response) => { - console.error(err.stack); - res.send(500, 'Something broke!'); - }); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - app.use(() => {}); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - - app.get('/', (req: express.Request, res: express.Response) => { - res.send('hello world'); - }); - - app.listen(3000); - - app.set('title', 'My Site'); - app.get('title'); - - app.enable('trust proxy'); - app.get('trust proxy'); - - app.disable('trust proxy'); - app.get('trust proxy'); - - app.enabled('trust proxy'); - - app.configure(() => { - app.set('title', 'My Application'); - }); - - app.configure('development', () => { - app.set('db uri', 'localhost/dev'); - }); - - app.configure('stage', 'production', () => {}); - - app.configure('1', '2', '3', () => {}); - - app.use((req: express.Request, res: express.Response) => { - res.send('Hello World'); - }); - - app.engine('jade', require('jade').__express); - - var User; - app.param('user', (req: express.Request, res: express.Response, next, id) => { - User.find(id, (err, user) =>{ - if (err) { - next(err); - } else if (user) { - req.user = user; - next(); - } else { - next(new Error('failed to load user')); - } - }); - }); - - app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req: express.Request, res: express.Response) => { - var from = req.params[0]; - var to = req.params[1] || 'HEAD'; - res.send('commit range ' + from + '..' + to); - }); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - - var requireAuthentication; - var loadUser = () => {}; - app.all('*', requireAuthentication, loadUser); - app.all('*', loadUser); - app.all('*', loadUser, loadUser, loadUser); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - app.locals({ - title: 'My App', - phone: '1-250-858-9990', - email: 'me@myapp.com' - }); - app.render('email', () => {}); - - app.render('email', { name: 'Tobi' }, () => {}); -} - -function test_request() { - var req: express.Request; - req.params.name; - req.params[0]; - req.query.q; - req.body.user.name; - app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })); - req.param('name'); - req.route; - req.cookies.name; - req.signedCookies; - req.get('Content-Type'); - req.accepts('html'); - req.accepts(['html', 'json']); - req.is('html'); - req.ip; - req.path; - req.host; - req.fresh; - req.stale; - req.xhr; - req.protocol; - req.subdomains; - req.originalUrl; - req.acceptedLanguages; - req.acceptedCharsets; - var charset; - req.acceptsCharset(charset); - var lang; - req.acceptsLanguage(lang); - req.session = null; -} - -function test_response() { - var res: express.Response; - res.status(404).sendfile('path/to/404.png'); - res.set('Content-Type', 'text/plain'); - res.set({ - 'Content-Type': 'text/plain', - 'Content-Length': '123', - 'ETag': '12345' - }); - res.get('Content-Type'); - res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); - res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }); - res.cookie('cart', { items: [1, 2, 3] }); - res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });; - res.cookie('name', 'tobi', { signed: true }); - res.cookie('name', 'tobi', { path: '/admin' }); - res.clearCookie('name', { path: '/admin' }); - res.redirect('/foo/bar'); - res.redirect('http://example.com'); - res.redirect(301, 'http://example.com'); - res.charset = 'value'; - res.send('some html'); - res.send(new Buffer('whoop')); - res.send({ some: 'json' }); - res.send('some html'); - res.send(404, 'Sorry, we cannot find that!'); - res.send(500, { error: 'something blew up' }); - res.send(200); - res.set('Content-Type', 'text/html'); - res.send(new Buffer('some html')); - res.send('some html'); - res.send({ user: 'tobi' }); - res.send([1, 2, 3]); - res.json(null); - res.json({ user: 'tobi' }); - res.json(500, { error: 'message' }); - res.jsonp(null); - res.jsonp({ user: 'tobi' }); - res.jsonp(500, { error: 'message' }); - res.jsonp({ user: 'tobi' }); - res.type('application/json'); - - res.format({ - 'text/plain': () => { - res.send('hey'); - }, - 'text/html': () => { - res.send('hey'); - }, - 'application/json': () => { - res.send({ message: 'hey' }); - } - }); - - res.attachment(); - res.attachment('path/to/logo.png'); - app.get('/user/:uid/photos/:file', (req: express.Request, res: express.Response) => { - var uid = req.params.uid - , file = req.params.file; - - req.user.mayViewFilesFrom(uid, yes => { - if (yes) { - res.sendfile('/uploads/' + uid + '/' + file); - } else { - res.send(403, 'Sorry! you cant see that.'); - } - }); - }); - - res.download('/report-12345.pdf'); - res.download('/report-12345.pdf', 'report.pdf'); - res.download('/report-12345.pdf', 'report.pdf', err => { - if (err) { } else { } - }); - - res.links({ - next: 'http://api.example.com/users?page=2', - last: 'http://api.example.com/users?page=5' - }); - - app.use((req: express.Request, res: express.Response, next) => { - res.locals.user = req.user; - res.locals.authenticated = !req.user.anonymous; - next(); - }); - res.render('index', () => {}); - res.render('user', { name: 'Tobi' }, () => {}); - -} - -function test_middleware() { - app.use(express.basicAuth('username', 'password')); - app.use(express.basicAuth((user, pass) => { - return 'tj' == user && 'wahoo' == pass; - })); - app.use(express.bodyParser()); - app.use(express.json()); - app.use(express.urlencoded()); - app.use(express.multipart()); - app.use(express.logger()); - app.use(express.compress()); - app.use(express.methodOverride()); - app.use(express.bodyParser()); - app.use(express.cookieParser()); - app.use(express.cookieParser('some secret')); - app.use(express.cookieSession()); - app.use(express.directory('public')); - app.use(express.static('public')); - app.use(router.middleware); -} - -//////////////////// - -// make sure server can be shut down -var testShutdownServer = app.listen(0); -console.log('listening on port ' + testShutdownServer.address().port); -testShutdownServer.close(); +app.listen(3000); diff --git a/express/express.d.ts b/express/express.d.ts index eafc4c596..052173c83 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -1,22 +1,14 @@ -// Type definitions for Express 3.1 +// Type definitions for Express 4.x // Project: http://expressjs.com // Definitions by: Boris Yankov // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped -/* =================== USAGE =================== - - import express = require('express'); - var app = express(); - - =============================================== */ - /// - declare module Express { // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example passport.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/passport/passport.d.ts) + // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) export interface Request { } export interface Response { } export interface Application { } @@ -26,51 +18,24 @@ declare module Express { declare module "express" { import http = require('http'); - // Merged declaration, e is both a callable function and a namespace function e(): e.Express; module e { interface IRoute { path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - - /** - * Check if this route matches `path`, if so - * populate `.params`. - */ - match(path: string): boolean; + 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; } - class Route implements IRoute { - path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - match(path: string): boolean; - - /** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: - * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param method - * @param path - * @param callbacks - * @param options - */ - new (method: string, path: string, callbacks: Function[], options: any): Route; + interface IRouterMatcher { + (name: string, ...handlers: RequestHandler[]): T; + (name: RegExp, ...handlers: RequestHandler[]): T; } interface IRouter { @@ -103,9 +68,9 @@ declare module "express" { * @param name * @param fn */ - param(name: string, fn: Function): T; - - param(name: string[], fn: Function): T; + param(name: string, handler: RequestParamHandler): T; + param(name: string, matcher: RegExp): T; + param(name: string, mapper: (param: any) => any): T; /** * Special-cased "all" method, applying the given route `path`, @@ -114,68 +79,27 @@ declare module "express" { * @param path * @param fn */ - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; - all(path: string, ...callbacks: Function[]): void; + route(path: string): IRoute; - get(name: string, ...handlers: RequestFunction[]): T; - - get(name: RegExp, ...handlers: RequestFunction[]): T; - - post(name: string, ...handlers: RequestFunction[]): T; - - post(name: RegExp, ...handlers: RequestFunction[]): T; - - put(name: string, ...handlers: RequestFunction[]): T; - - put(name: RegExp, ...handlers: RequestFunction[]): T; - - del(name: string, ...handlers: RequestFunction[]): T; - - del(name: RegExp, ...handlers: RequestFunction[]): T; - - patch(name: string, ...handlers: RequestFunction[]): T; - - patch(name: RegExp, ...handlers: RequestFunction[]): T; + use(server: Application): Application; + use(handler: RequestHandler): Application; + use(handler: ErrorRequestHandler): Application; + use(path: string, server: Application): Application; + use(path: string, handler: RequestHandler): Application; + use(path: string, handler: ErrorRequestHandler): Application; } - export class Router implements IRouter { - new (options?: any): Router; + export function Router(options?: any): Router; - middleware (): any; - - param(name: string, fn: Function): Router; - - param(name: any[], fn: Function): Router; - - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; - - all(path: string, ...callbacks: Function[]): void; - - get(name: string, ...handlers: RequestFunction[]): Router; - - get(name: RegExp, ...handlers: RequestFunction[]): Router; - - post(name: string, ...handlers: RequestFunction[]): Router; - - post(name: RegExp, ...handlers: RequestFunction[]): Router; - - put(name: string, ...handlers: RequestFunction[]): Router; - - put(name: RegExp, ...handlers: RequestFunction[]): Router; - - del(name: string, ...handlers: RequestFunction[]): Router; - - del(name: RegExp, ...handlers: RequestFunction[]): Router; - - patch(name: string, ...handlers: RequestFunction[]): Router; - - patch(name: RegExp, ...handlers: RequestFunction[]): Router; - } - - interface Handler { - (req: Request, res: Response, next?: Function): void; - } + export interface Router extends IRouter {} interface CookieOptions { maxAge?: number; @@ -189,61 +113,8 @@ declare module "express" { interface Errback { (err: Error): void; } - interface Session { - /** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - touch(): Session; - - /** - * Reset `.maxAge` to `.originalMaxAge`. - */ - resetMaxAge(): Session; - - /** - * Save the session data with optional callback `fn(err)`. - */ - save(fn: Function): Session; - - /** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - */ - reload(fn: Function): Session; - - /** - * Destroy `this` session. - */ - destroy(fn: Function): Session; - - /** - * Regenerate this request's session. - */ - regenerate(fn: Function): Session; - - user: any; - - error: string; - - success: string; - - views: any; - - count: number; - } - interface Request extends http.ServerRequest, Express.Request { - session: Session; - /** * Return request header. * @@ -450,17 +321,6 @@ declare module "express" { */ ips: string[]; - /** - * Return basic auth credentials. - * - * Examples: - * - * // http://tobi:hello@example.com - * req.auth - * // => { username: 'tobi', password: 'hello' } - */ - auth: any; - /** * Return subdomains as an array. * @@ -509,12 +369,6 @@ declare module "express" { //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; @@ -650,11 +504,8 @@ declare module "express" { * }); */ sendfile(path: string): void; - sendfile(path: string, options: any): void; - sendfile(path: string, fn: Errback): void; - sendfile(path: string, options: any, fn: Errback): void; /** @@ -668,11 +519,8 @@ declare module "express" { * 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; /** @@ -782,12 +630,10 @@ declare module "express" { * * Aliased as `res.header()`. */ - set (field: any): Response; - - set (field: string, value?: string): Response; + set(field: any): Response; + set(field: string, value?: string): Response; header(field: any): Response; - header(field: string, value?: string): Response; /** @@ -823,9 +669,7 @@ declare module "express" { * 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; /** @@ -875,9 +719,7 @@ declare module "express" { * res.redirect('../login'); // /blog/post/1 -> /blog/login */ redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; /** @@ -890,9 +732,7 @@ declare module "express" { * - `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; @@ -900,10 +740,18 @@ declare module "express" { charset: string; } - interface RequestFunction { + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: Function): any; + } + + interface RequestHandler { (req: Request, res: Response, next: Function): any; } + interface RequestParamHandler { + (req: Request, res: Response, next: Function, param: any): any; + } + interface Application extends IRouter, Express.Application { /** * Initialize the server. @@ -919,18 +767,6 @@ declare module "express" { */ defaultConfiguration(): void; - /** - * Proxy `connect#use()` to apply settings to - * mounted applications. - **/ - use(route: string, callback?: Function): Application; - - use(route: string, server: Application): Application; - - use(callback: Function): Application; - - use(server: Application): Application; - /** * Register the given template engine callback `fn` * as `ext`. @@ -961,10 +797,6 @@ declare module "express" { */ engine(ext: string, fn: Function): Application; - param(name: string, fn: Function): Application; - - param(name: string[], fn: Function): Application; - /** * Assign `setting` to `val`, or return `setting`'s value. * @@ -977,13 +809,12 @@ declare module "express" { * @param setting * @param val */ - set (setting: string, val: string): Application; - - get(name: string): string; - - get(name: string, ...handlers: RequestFunction[]): Application; - - get(name: RegExp, ...handlers: RequestFunction[]): Application; + set(setting: string, val: string): Application; + get: { + (name: string): string; // Getter + (name: string, ...handlers: RequestHandler[]): Application; + (name: RegExp, ...handlers: RequestHandler[]): Application; + } /** * Return the app's absolute pathname @@ -1079,18 +910,12 @@ declare module "express" { * @param env * @param fn */ - configure(env: 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; - 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` @@ -1108,7 +933,6 @@ declare module "express" { * @param fn */ render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; @@ -1130,16 +954,12 @@ declare module "express" { * 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: IRoute; + route(path: string): IRoute; router: string; @@ -1189,237 +1009,6 @@ declare module "express" { response: Response; } - /** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param options - */ - function bodyParser(options?: any): Handler; - - /** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - */ - function errorHandler(opts?: any): Handler; - - /** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param key - */ - function methodOverride(key?: string): Handler; - - /** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param secret - */ - function cookieParser(secret?: string): Handler; - - /** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent 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") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

views: ' + 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 - */ - function session(options?: any): Handler; - - /** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param sess - */ - function hash(sess: string): string; - /** * Static: * @@ -1444,387 +1033,7 @@ declare module "express" { * @param root * @param options */ - function static(root: string, options?: any): 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 - */ - 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; - - /** - * 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 - */ - function compress(options?: any): 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 - */ - function cookieSession(options?: any): 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 - */ - export function csrf(options?: {value?: Function}): 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 - */ - function directory(root: string, options?: any): 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 - */ - export function favicon(path?: string, options?: any): 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 - */ - function json(options?: any): 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) - */ - function limit(bytes: number): Handler; - - function limit(bytes: string): 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') - */ - function logger(options: string): Handler; - - function logger(options: Function): Handler; - - function logger(options?: any): Handler; - - /** - * Compile `fmt` into a function. - * - * @param fmt - */ - function compile(fmt: string): Handler; - - /** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param name - * @param fn - */ - function token(name: string, fn: Function): any; - - /** - * Define a `fmt` with the given `name`. - */ - function format(name: string, str: string): any; - - function 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. - */ - function query(options: any): Handler; - - /** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - */ - function responseTime(): 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 - */ - function staticCache(options: any): 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`. - */ - function timeout(ms: number): 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 - */ - function vhost(hostname: string, server: any): Handler; - - function urlencoded(): any; - - function multipart(): any; - + function static(root: string, options?: any): RequestHandler; } export = e; diff --git a/method-override/method-override-tests.ts b/method-override/method-override-tests.ts new file mode 100644 index 000000000..84b4e966e --- /dev/null +++ b/method-override/method-override-tests.ts @@ -0,0 +1,15 @@ +/// + +import express = require('express'); +import methodOverride = require('method-override'); +var app = express(); + +app.use(methodOverride('X-HTTP-Method-Override')); +app.use(methodOverride((req: express.Request, res: express.Response) => { + if (req.body && typeof req.body === 'object' && '_method' in req.body) { + // look in urlencoded POST bodies and delete it + var method = req.body._method + delete req.body._method + return method + } +})); diff --git a/method-override/method-override.d.ts b/method-override/method-override.d.ts new file mode 100644 index 000000000..51b62f521 --- /dev/null +++ b/method-override/method-override.d.ts @@ -0,0 +1,24 @@ +// Type definitions for method-override +// Project: https://github.com/expressjs/method-override +// Definitions by: Santi Albo +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + export interface Request { + originalMethod?: string; + } +} + +declare module "method-override" { + import express = require('express'); + module e { + interface MethodOverrideOptions { + methods: string[]; + } + } + function e(getter: string, options?: any): express.RequestHandler; + function e(getter: (req: express.Request, res: express.Response) => string, options?: any): express.RequestHandler; + export = e; +} \ No newline at end of file From 492d456a36abef7eea96331d86632b9b67d00439 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 17:49:05 -0700 Subject: [PATCH 005/167] angular.d.ts: new interface IServiceProviderClass Instead of IModule.provider simply accepting an Function for a class constructor, use an interface to enforce the type of class. --- angularjs/angular.d.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 92a02eef8..f2ecbd783 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -18,6 +18,11 @@ interface Function { /////////////////////////////////////////////////////////////////////////////// declare module ng { + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new(...args: any[]): IServiceProvider; + } + // All service providers extend this interface interface IServiceProvider { $get: any; @@ -140,9 +145,9 @@ declare module ng { filter(name: string, filterFactoryFunction: Function): IModule; filter(name: string, inlineAnnotatedFunction: any[]): IModule; filter(object: Object): IModule; - provider(name: string, serviceProviderConstructor: Function): IModule; + provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; provider(name: string, inlineAnnotatedConstructor: any[]): IModule; - provider(name: string, providerObject: auto.IProvider): IModule; + provider(name: string, providerObject: IServiceProvider): IModule; provider(object: Object): IModule; run(initializationFunction: Function): IModule; run(inlineAnnotatedFunction: any[]): IModule; @@ -991,9 +996,6 @@ declare module ng { // AUTO module (angular.js) /////////////////////////////////////////////////////////////////////////// export module auto { - interface IProvider { - $get: any; - } /////////////////////////////////////////////////////////////////////// // InjectorService From 3a36795eb258f1797f7ebea8c496201a5ea1436b Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 18:13:14 -0700 Subject: [PATCH 006/167] angular.d.ts: new interface IDirectiveFactory Adds intellisense when constructing directive objects --- angularjs/angular.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index f2ecbd783..cb03b6925 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -124,7 +124,7 @@ declare module ng { */ controller(name: string, inlineAnnotatedConstructor: any[]): IModule; controller(object : Object): IModule; - directive(name: string, directiveFactory: Function): IModule; + directive(name: string, directiveFactory: IDirectiveFactory): IModule; directive(name: string, inlineAnnotatedFunction: any[]): IModule; directive(object: Object): IModule; /** @@ -919,6 +919,11 @@ declare module ng { // and http://docs.angularjs.org/guide/directive /////////////////////////////////////////////////////////////////////////// + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirective{ compile?: (templateElement: IAugmentedJQuery, From ef0e9da858b404c022455cbb38e2e95b3f6fa13c Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 18:32:01 -0700 Subject: [PATCH 007/167] angular.d.ts: new interface IServiceProviderFactory Missed provider functions that return objects. Ensure that they also implement ng.IServiceProvider. --- angularjs/angular.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index cb03b6925..e8d1db837 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -22,6 +22,10 @@ declare module ng { interface IServiceProviderClass { new(...args: any[]): IServiceProvider; } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } // All service providers extend this interface interface IServiceProvider { @@ -145,6 +149,7 @@ declare module ng { filter(name: string, filterFactoryFunction: Function): IModule; filter(name: string, inlineAnnotatedFunction: any[]): IModule; filter(object: Object): IModule; + provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; provider(name: string, inlineAnnotatedConstructor: any[]): IModule; provider(name: string, providerObject: IServiceProvider): IModule; From dd4602b27a74218079be508e51ea90f8df68ce44 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 18:41:06 -0700 Subject: [PATCH 008/167] angular-agility need to use ng.IServiceProvider --- angular-agility/angular-agility.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-agility/angular-agility.d.ts b/angular-agility/angular-agility.d.ts index c11aff0b0..872971aed 100644 --- a/angular-agility/angular-agility.d.ts +++ b/angular-agility/angular-agility.d.ts @@ -41,7 +41,7 @@ declare module aa { [settingName: string]: any; } - export interface IFormExtensionsProvider extends ng.auto.IProvider { + export interface IFormExtensionsProvider extends ng.IServiceProvider { defaultLabelStrategy:string; defaultFieldGroupStrategy:string; defaultValMsgPlacementStrategy:string; @@ -88,7 +88,7 @@ declare module aa { message:string; } - export interface INotifyConfigProvider extends ng.auto.IProvider { + export interface INotifyConfigProvider extends ng.IServiceProvider { notifyConfigs:any; defaultTargetContainerName:string; defaultNotifyConfig:string; From 72b9fbed7f7b96de942005c96e23f3535e7d0084 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 18 Jun 2014 19:55:32 -0700 Subject: [PATCH 009/167] angular.d.ts: update test to use class for module Converted the test module, 'http-auth-interceptor', to a class to eliminate error on using anonymous type constructor. --- angularjs/angular-tests.ts | 63 +++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 419bed0d6..bac077131 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -7,27 +7,27 @@ * (c) 2012 Witold Szczerba * License: MIT */ -angular.module('http-auth-interceptor', []) - .provider('authService', function () { - /** - * Holds all the requests which failed due to 401 response, - * so they can be re-requested in future, once login is completed. - */ - var buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; +class AuthService { + /** + * Holds all the requests which failed due to 401 response, + * so they can be re-requested in future, once login is completed. + */ + buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; - /** - * Required by HTTP interceptor. - * Function is attached to provider to be invisible for regular users of this service. - */ - this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred) { - buffer.push({ - config: config, - deferred: deferred - }); - } + /** + * Required by HTTP interceptor. + * Function is attached to provider to be invisible for regular users of this service. + */ + pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { + this.buffer.push({ + config: config, + deferred: deferred + }); + } - this.$get = ['$rootScope', '$injector', function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { + $get = [ + '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { var $http: ng.IHttpService; //initialized later because of circular dependency problem function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { $http = $http || $injector.get('$http'); @@ -36,20 +36,25 @@ angular.module('http-auth-interceptor', []) }); } function retryAll() { - for (var i = 0; i < buffer.length; ++i) { - retry(buffer[i].config, buffer[i].deferred); + for (var i = 0; i < this.buffer.length; ++i) { + retry(this.buffer[i].config, this.buffer[i].deferred); } - buffer = []; + this.buffer = []; } - return { + return { loginConfirmed: function () { $rootScope.$broadcast('event:auth-loginConfirmed'); retryAll(); } } - }] - }) + } + ]; +} + +angular.module('http-auth-interceptor', []) + + .provider('authService', AuthService) /** * $http interceptor. @@ -176,7 +181,8 @@ mod.factory(My.Namespace); mod.filter('name', function ($scope: ng.IScope) { }) mod.filter('name', ['$scope', function ($scope: ng.IScope) { }]) mod.filter(My.Namespace); -mod.provider('name', function ($scope: ng.IScope) { }) +mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } }) +mod.provider('name', TestProvider); mod.provider('name', ['$scope', function ($scope: ng.IScope) { }]) mod.provider(My.Namespace); mod.service('name', function ($scope: ng.IScope) { }) @@ -189,6 +195,13 @@ mod.value('name', 23); mod.value('name', "23"); mod.value(My.Namespace); +class TestProvider implements ng.IServiceProvider { + constructor(private $scope: ng.IScope) { + } + + $get() { + } +} // Promise signature tests var foo: ng.IPromise; From a001147307a688fe0f11ee0053b8e3321a167778 Mon Sep 17 00:00:00 2001 From: Jason Zhao Date: Fri, 27 Jun 2014 17:58:58 -0700 Subject: [PATCH 010/167] added definitions for angular-hotkeys --- angular-hotkeys/angular-hotkeys-tests.ts | 13 ++++++++++ angular-hotkeys/angular-hotkeys.d.ts | 30 ++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 angular-hotkeys/angular-hotkeys-tests.ts create mode 100644 angular-hotkeys/angular-hotkeys.d.ts diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts new file mode 100644 index 000000000..4e63b32fa --- /dev/null +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -0,0 +1,13 @@ +/// + +var hotkeyProvider: ng.hotkeys.HotkeysProvider; +var hotkeyObj: ng.hotkeys.Hotkey; + +hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); +hotkeyProvider.add(hotkeyObj); +hotkeyProvider.del("mod+s"); +hotkeyProvider.get("mod+s"); +hotkeyProvider.toggleCheatSheet(); + +hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); + diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts new file mode 100644 index 000000000..8c2e1ff1c --- /dev/null +++ b/angular-hotkeys/angular-hotkeys.d.ts @@ -0,0 +1,30 @@ +// Type definitions for angular-hotkeys +// Project: https://github.com/chieffancypants/angular-hotkeys +// Definitions by: Jason Zhao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ng.hotkeys { + + interface HotkeysProvider { + template: string; + includeCheatSheet: boolean; + cheatSheetHotkey: string; + cheatSheetDescription: string; + + add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): void; + + add(hotkeyObj: ng.hotkeys.Hotkey): void; + + del(combo: string): void; + + get(combo: string): ng.hotkeys.Hotkey; + + toggleCheatSheet(): void; + } + + interface Hotkey { + combo: string; + description?: string; + callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; + } +} From 56a71f88b0db9a2cd63759e10ba3155a2fde2613 Mon Sep 17 00:00:00 2001 From: Jason Zhao Date: Mon, 14 Jul 2014 14:11:51 -0700 Subject: [PATCH 011/167] added contributos --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ae430f57d..d40176b54 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -13,6 +13,7 @@ All definitions files include a header with the author and editors, so at some p * [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) * [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib)) +* [Angular Hotkeys](https://github.com/chieffancypants/angular-hotkeys/) (by [Jason Zhao](https://github.com/jlz27)) * [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong)) * [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib)) * [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted)) From e43fb420097712a9f3af2758da56e2dbaeab177b Mon Sep 17 00:00:00 2001 From: Jason Zhao Date: Mon, 14 Jul 2014 16:28:09 -0700 Subject: [PATCH 012/167] bumped version to 1.4.0 --- angular-hotkeys/angular-hotkeys-tests.ts | 3 +++ angular-hotkeys/angular-hotkeys.d.ts | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts index 4e63b32fa..66f9e6072 100644 --- a/angular-hotkeys/angular-hotkeys-tests.ts +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -1,10 +1,13 @@ +/// /// +var scope: ng.IScope; var hotkeyProvider: ng.hotkeys.HotkeysProvider; var hotkeyObj: ng.hotkeys.Hotkey; hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); hotkeyProvider.add(hotkeyObj); +hotkeyProvider.bindTo(scope); hotkeyProvider.del("mod+s"); hotkeyProvider.get("mod+s"); hotkeyProvider.toggleCheatSheet(); diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts index 8c2e1ff1c..cc4a3680c 100644 --- a/angular-hotkeys/angular-hotkeys.d.ts +++ b/angular-hotkeys/angular-hotkeys.d.ts @@ -3,6 +3,8 @@ // Definitions by: Jason Zhao // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module ng.hotkeys { interface HotkeysProvider { @@ -15,6 +17,8 @@ declare module ng.hotkeys { add(hotkeyObj: ng.hotkeys.Hotkey): void; + bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProvider; + del(combo: string): void; get(combo: string): ng.hotkeys.Hotkey; From 84f63e9cc3917650186dc88c996bad5436311405 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 16 Jul 2014 13:27:04 -0700 Subject: [PATCH 013/167] Added signal function to CodeMirror module --- codemirror/codemirror.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index affee3458..316284a78 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -86,6 +86,11 @@ declare module CodeMirror { or the line the widget is on require the widget to be redrawn. */ function on(line: LineWidget, eventName: 'redraw', handler: () => void ): void; function off(line: LineWidget, eventName: 'redraw', handler: () => void ): void; + + /** Various CodeMirror-related objects emit events, which allow client code to react to various situations. + Handlers for such events can be registered with the on and off methods on the objects that the event fires on. + To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object. */ + function signal(target: any, name: string, ...args: any[]): void; interface Editor { From 14fdf0edc6c4ea52d1096b4f508a24a93871c09f Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:12:44 +0100 Subject: [PATCH 014/167] Remove express 3 type definitions --- express/express-3.1.0-tests.ts | 1498 ------------------ express/express-3.1.0-tests.ts.tscparams | 1 - express/express-3.1.0.d.ts | 1832 ---------------------- 3 files changed, 3331 deletions(-) delete mode 100644 express/express-3.1.0-tests.ts delete mode 100644 express/express-3.1.0-tests.ts.tscparams delete mode 100644 express/express-3.1.0.d.ts diff --git a/express/express-3.1.0-tests.ts b/express/express-3.1.0-tests.ts deleted file mode 100644 index 904f64511..000000000 --- a/express/express-3.1.0-tests.ts +++ /dev/null @@ -1,1498 +0,0 @@ -/// - -import express = require('express'); -var app = express(); - -////////////////////////// - -var hash: any; - -// config - -app.set('view engine', 'ejs'); -app.set('views', __dirname + '/views'); - -// middleware - -app.use(express.bodyParser()); -app.use(express.cookieParser('shhhh, very secret')); -app.use(express.session()); - -// Session-persisted message middleware - -app.use((req: express.Request, res: express.Response, next) => { - var err = req.session.error - , msg = req.session.success; - delete req.session.error; - delete req.session.success; - res.locals.message = ''; - if (err) res.locals.message = '

' + err + '

'; - if (msg) res.locals.message = '

' + msg + '

'; - next(); -}); - -// dummy database - -var users = { - tj: { name: 'tj' } -}; - -// when you create a user, generate a salt -// and hash the password ('foobar' is the pass here) - -hash('foobar', (err, salt, hash) => { - if (err) throw err; - // store the salt & hash in the "db" - users.tj.salt = salt; - users.tj.hash = hash; -}); - - -// Authenticate using our plain-object database of doom! - -function authenticate(name, pass, fn) { - if (!module.parent) console.log('authenticating %s:%s', name, pass); - var user = users[name]; - // query the db for the given username - if (!user) return fn(new Error('cannot find user')); - // apply the same algorithm to the POSTed password, applying - // the hash against the pass / salt, if there is a match we - // found the user - hash(pass, user.salt, (err, hash) => { - if (err) return fn(err); - if (hash == user.hash) return fn(null, user); - fn(new Error('invalid password')); - }); -} - -function restrict(req: express.Request, res: express.Response, next?: Function) { - if (req.session.user) { - next(); - } else { - req.session.error = 'Access denied!'; - res.redirect('/login'); - } -} - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('login'); -}); - -app.get('/restricted', restrict, (req: express.Request, res: express.Response) => { - res.send('Wahoo! restricted area, click to logout'); -}); - -app.get('/logout', (req: express.Request, res: express.Response) => { - // destroy the user's session to log them out - // will be re-created next request - req.session.destroy(() => { - res.redirect('/'); - }); -}); - -app.get('/login', (req: express.Request, res: express.Response) => { - res.render('login'); -}); - -app.post('/login', (req: express.Request, res: express.Response) => { - authenticate(req.body.username, req.body.password, (err, user) => { - if (user) { - // Regenerate session when signing in - // to prevent fixation - req.session.regenerate(() => { - // Store the user's primary key - // in the session store to be retrieved, - // or in this case the entire user object - req.session.user = user; - req.session.success = 'Authenticated as ' + user.name - + ' click to logout. ' - + ' You may now access /restricted.'; - res.redirect('back'); - }); - } else { - req.session.error = 'Authentication failed, please check your ' - + ' username and password.' - + ' (use "tj" and "foobar")'; - res.redirect('login'); - } - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////// - -app.set('views', __dirname); -app.set('view engine', 'jade'); - -var pets = []; - -var n = 1000; -while (n--) { - pets.push({ name: 'Tobi', age: 2, species: 'ferret' }); - pets.push({ name: 'Loki', age: 1, species: 'ferret' }); - pets.push({ name: 'Jane', age: 6, species: 'ferret' }); -} - -app.use(express.logger('dev')); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('pets', { pets: pets }); -}); - -app.listen(3000); -console.log('Express listening on port 3000'); - -///////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.format({ - html: () => { - res.send('
    ' + users.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('') + '
'); - }, - - text: () => { - res.send(users.map(user => { - return ' - ' + user.name + '\n'; - }).join('')); - }, - - json: () => { - res.json(users); - } - }); -}); - -// or you could write a tiny middleware like -// this to abstract make things a bit more declarative: - -function format(mod) { - var obj = require(mod); - return (req: express.Request, res: express.Response) => { - res.format(obj); - }; -} - -app.get('/users', format('./users')); - -if (!module.parent) { - app.listen(3000); - console.log('listening on port 3000'); -} - -///////////////////////// - -// add favicon() before logger() so -// GET /favicon.ico requests are not -// logged, because this middleware -// reponds to /favicon.ico and does not -// call next() -app.use(express.favicon()); - -// custom log format -if ('test' != process.env.NODE_ENV) - app.use(express.logger(':method :url')); - -// parses request cookies, populating -// req.cookies and req.signedCookies -// when the secret is passed, used -// for signing the cookies. -app.use(express.cookieParser('my secret here')); - -// parses json, x-www-form-urlencoded, and multipart/form-data -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - if (req.cookies.remember) { - res.send('Remembered :). Click to forget!.'); - } else { - res.send('

Check to ' - + '.

'); - } -}); - -app.get('/forget', (req: express.Request, res: express.Response) => { - res.clearCookie('remember'); - res.redirect('back'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - var minute = 60000; - if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); - res.redirect('back'); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// ignore GET /favicon.ico -app.use(express.favicon()); - -// pass a secret to cookieParser() for signed cookies -app.use(express.cookieParser('manny is cool')); - -// add req.session cookie support -app.use(express.cookieSession()); - -// do something with the session -app.use(count); - -// custom middleware -function count(req: express.Request, res: express.Response) { - req.session.count = req.session.count || 0; - var n = req.session.count++; - res.send('viewed ' + n + ' times\n'); -} - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -/////////////// - -var api = app; - -app.use(express.static(__dirname + '/public')); - -// api middleware - -api.use(express.logger('dev')); -api.use(express.bodyParser()); - -/** - * CORS support. - */ - -api.all('*', (req: express.Request, res: express.Response, next) => { - if (!req.get('Origin')) return next(); - // use "*" here to accept any origin - res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); - res.set('Access-Control-Allow-Methods', 'GET, POST'); - res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'); - // res.set('Access-Control-Allow-Max-Age', 3600); - if ('OPTIONS' == req.method) return res.send(200); - next(); -}); - -/** - * POST a user. - */ - -api.post('/user', (req: express.Request, res: express.Response) => { - console.log(req.body); - res.send(201); -}); - -app.listen(3000); -api.listen(3001); - -console.log('app listening on 3000'); -console.log('api listening on 3001'); - -//////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send(''); -}); - -// /files/* is accessed via req.params[0] -// but here we name it :file -app.get('/files/:file(*)', (req: express.Request, res: express.Response) => { - var file = req.params.file - , path = __dirname + '/files/' + file; - - res.download(path); -}); - -// error handling middleware. Because it's -// below our routes, you will be able to -// "intercept" errors, otherwise Connect -// will respond with 500 "Internal Server Error". -app.use((err, req, res: express.Response, next) => { - // special-case 404s, - // remember you could - // render a 404 template here - if (404 == err.status) { - res.statusCode = 404; - res.send('Cant find that file, sorry!'); - } else { - next(err); - } -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// Register ejs as .html. If we did -// not call this, we would need to -// name our views foo.ejs instead -// of foo.html. The __express method -// is simply a function that engines -// use to hook into the Express view -// system by default, so if we want -// to change "foo.ejs" to "foo.html" -// we simply pass _any_ function, in this -// case `ejs.__express`. - -app.engine('.html', require('ejs').__express); - -// Optional since express defaults to CWD/views - -app.set('views', __dirname + '/views'); - -// Without this you would need to -// supply the extension to res.render() -// ex: res.render('users.html'). -app.set('view engine', 'html'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('users', { - users: users, - title: "EJS example", - header: "Some users" - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express app started on port 3000'); -} - -//////////////////// - -var test: any; - -if (!test) app.use(express.logger('dev')); -app.use(app.router); - -// the error handler is strategically -// placed *below* the app.router; if it -// were above it would not receive errors -// from app.get() etc -app.use(error); - -// error handling middleware have an arity of 4 -// instead of the typical (req: express.Request, res: express.Response, next), -// otherwise they behave exactly like regular -// middleware, you may have several of them, -// in different orders etc. - -function error(err, req, res: express.Response, next) { - // log it - if (!test) console.error(err.stack); - - // respond with 500 "Internal Server Error". - res.send(500); -} - -app.get('/', () => { - // Caught and passed down to the errorHandler middleware - throw new Error('something broke!'); -}); - -app.get('/next', (req: express.Request, res: express.Response, next) => { - // We can also pass exceptions to next() - process.nextTick(() => { - next(new Error('oh no!')); - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - -var silent: any; - -// general config -app.set('views', __dirname + '/views'); -app.set('view engine', 'jade'); - -// our custom "verbose errors" setting -// which we can use in the templates -// via settings['verbose errors'] -app.enable('verbose errors'); - -// disable them in production -// use $ NODE_ENV=production node examples/error-pages -if ('production' == app.settings.env) { - app.disable('verbose errors'); -} - -app.use(express.favicon()); - -silent || app.use(express.logger('dev')); - -// "app.router" positions our routes -// above the middleware defined below, -// this means that Express will attempt -// to match & call routes _before_ continuing -// on, at which point we assume it's a 404 because -// no route has handled the request. - -app.use(app.router); - -// Since this is the last non-error-handling -// middleware use()d, we assume 404, as nothing else -// responded. - -// $ curl http://localhost:3000/notfound -// $ curl http://localhost:3000/notfound -H "Accept: application/json" -// $ curl http://localhost:3000/notfound -H "Accept: text/plain" - -app.use((req: express.Request, res: express.Response) => { - res.status(404); - - // respond with html page - if (req.accepts('html')) { - res.render('404', { url: req.url }); - return; - } - - // respond with json - if (req.accepts('json')) { - res.send({ error: 'Not found' }); - return; - } - - // default to plain-text. send() - res.type('txt').send('Not found'); -}); - -// error-handling middleware, take the same form -// as regular middleware, however they require an -// arity of 4, aka the signature (err, req, res: express.Response, next). -// when connect has an error, it will invoke ONLY error-handling -// middleware. - -// If we were to next() here any remaining non-error-handling -// middleware would then be executed, or if we next(err) to -// continue passing the error, only error-handling middleware -// would remain being executed, however here -// we simply respond with an error page. - -app.use((err, req, res: express.Response) => { - // we may use properties of the error object - // here and next(err) appropriately, or if - // we possibly recovered from the error, simply next(). - res.status(err.status || 500); - res.render('500', { error: err }); -}); - -// Routes - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index.jade'); -}); - -app.get('/404', (req: express.Request, res: express.Response, next) => { - // trigger a 404 since no other middleware - // will match /404 after this one, and we're not - // responding here - next(); -}); - -app.get('/403', (req: express.Request, res: express.Response, next) => { - // trigger a 403 error - var err = new Error('not allowed!'); - err.status = 403; - next(err); -}); - -app.get('/500', (req: express.Request, res: express.Response, next) => { - // trigger a generic (500) error - next(new Error('keyboard cat!')); -}); - -if (!module.parent) { - app.listen(3000); - //silent ||  console.log('Express started on port 3000'); -} - -/////////////// - -var fs: any; -var md: any; - -app.set('view engine', 'jade'); -app.set('views', __dirname + '/views'); - -function User(name) { - this.private = 'heyyyy'; - this.secret = 'something'; - this.name = name; - this.id = 123; -} - -// You'll probably want to do -// something like this so you -// dont expose "secret" data. - -User.prototype.toJSON = function () { - return { - id: this.id, - name: this.name - }; -}; - -app.use(express.logger('dev')); - -// earlier on expose an object -// that we can tack properties on. -// all res.locals props are exposed -// to the templates, so "expose" will -// be present. - -app.use((req: express.Request, res: express.Response, next) => { - res.locals.expose = {}; - // you could alias this as req or res.expose - // to make it shorter and less annoying - next(); -}); - -// pretend we loaded a user - -app.use((req: express.Request, res: express.Response, next) => { - req.user = new User('Tobi'); - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user'); -}); - -app.get('/user', (req: express.Request, res: express.Response) => { - // we only want to expose the user - // to the client for this route: - res.locals.expose.user = req.user; - res.render('page'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello World'); -}); - -app.listen(3000); -console.log('Express started on port 3000'); - -//////////////////// - -// register .md as an engine in express view system - -app.engine('md', (path, options, fn) => { - fs.readFile(path, 'utf8', (err, str) => { - if (err) return fn(err); - try { - var html = md(str); - html = html.replace(/\{([^}]+)\}/g, (_, name) => { - return options[name] || ''; - }); - fn(null, html); - } catch (err) { - fn(err); - } - }); -}); - -app.set('views', __dirname + '/views'); - -// make it the default so we dont need .md -app.set('view engine', 'md'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index', { title: 'Markdown Example' }); -}); - -app.get('/fail', (req: express.Request, res: express.Response) => { - res.render('missing', { title: 'Markdown Example' }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////////// - -var mformat: any; - -// bodyParser in connect 2.x uses node-formidable to parse -// the multipart form data. -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('
' - + '

Title:

' - + '

Image:

' - + '

' - + '
'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - // the uploaded file can be found as `req.files.image` and the - // title field as `req.body.title` - res.send(mformat('\nuploaded %s (%d Kb) to %s as %s' - , req.files.image.name - , req.files.image.size / 1024 | 0 - , req.files.image.path - , req.body.title)); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - - -// first: -// $ npm install redis online -// $ redis-server - -/** - * Module dependencies. - */ - -var online: any; -var db: any; - -// online - -online = online(db); - -// activity tracking, in this case using -// the UA string, you would use req.user.id etc - -app.use((req: express.Request, res: express.Response, next) => { - // fire-and-forget - online.add(req.headers['user-agent']); - next(); -}); - -/** - * List helper. - */ - -function list(ids) { - return '
    ' + ids.map(id => { - return '
  • ' + id + '
  • '; - }).join('') + '
'; -} - -/** - * GET users online. - */ - -app.get('/', (req: express.Request, res: express.Response, next) => { - online.last(5, (err, ids) => { - if (err) return next(err); - res.send('

Users online: ' + ids.length + '

' + list(ids)); - }); -}); - -app.listen(3000); -console.log('listening on port 3000'); - -/////////////////// - -// Convert :to and :from to integers - -app.param(['to', 'from'], (req: express.Request, res: express.Response, next, num, name) => { - req.params[name] = num = parseInt(num, 10); - if (isNaN(num)) { - next(new Error('failed to parseInt ' + num)); - } else { - next(); - } -}); - -// Load user by id - -app.param('user', (req: express.Request, res: express.Response, next, id) => { - if (req.user = users[id]) { - next(); - } else { - next(new Error('failed to find user')); - } -}); - -/** - * GET index. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Visit /user/0 or /users/0-2'); -}); - -/** - * GET :user. - */ - -app.get('/user/:user', (req: express.Request, res: express.Response) => { - res.send('user ' + req.user.name); -}); - -/** - * GET users :from - :to. - */ - -app.get('/users/:from-:to', (req: express.Request, res: express.Response) => { - var from = req.params.from - , to = req.params.to - , names = users.map(user => { return user.name; }); - res.send('users ' + names.slice(from, to).join(', ')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - -// Ad-hoc example resource method - -app.resource = function (path, obj) { - this.get(path, obj.index); - this.get(path + '/:a..:b.:format?', (req: express.Request, res: express.Response) => { - var a = parseInt(req.params.a, 10) - , b = parseInt(req.params.b, 10) - , format = req.params.format; - obj.range(req, res, a, b, format); - }); - this.get(path + '/:id', obj.show); - this.del(path + '/:id', obj.destroy); -}; - -// Fake controller. - -var FUser = { - index: (req: express.Request, res: express.Response) => { - res.send(users); - }, - show: (req: express.Request, res: express.Response) => { - res.send(users[req.params.id] || { error: 'Cannot find user' }); - }, - destroy: (req: express.Request, res: express.Response) => { - var id = req.params.id; - var destroyed = id in users; - delete users[id]; - res.send(destroyed ? 'destroyed' : 'Cannot find user'); - }, - range: (req: express.Request, res: express.Response, a, b, format) => { - var range = users.slice(a, b + 1); - switch (format) { - case 'json': - res.send(range); - break; - case 'html': - default: - var html = '
    ' + range.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('\n') + '
'; - res.send(html); - break; - } - } -}; - -// curl http://localhost:3000/users -- responds with all users -// curl http://localhost:3000/users/1 -- responds with user 1 -// curl http://localhost:3000/users/4 -- responds with error -// curl http://localhost:3000/users/1..3 -- responds with several users -// curl -X DELETE http://localhost:3000/users/1 -- deletes the user - -app.resource('/users', FUser); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send([ - '

Examples:

    ' - , '
  • GET /users
  • ' - , '
  • GET /users/1
  • ' - , '
  • GET /users/3
  • ' - , '
  • GET /users/1..3
  • ' - , '
  • GET /users/1..3.json
  • ' - , '
  • DELETE /users/4
  • ' - , '
' - ].join('\n')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - - -var verbose: any; - -app.map = (a, route) => { - route = route || ''; - for (var key in a) { - switch (typeof a[key]) { - // { '/path': { ... }} - case 'object': - app.map(a[key], route + key); - break; - // get: function(){ ... } - case 'function': - if (verbose) console.log('%s %s', key, route); - app[key](route, a[key]); - break; - } - } -}; - -var users2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user list'); - }, - - get: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete users'); - } -}; - -var pets2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid + '\'s pets'); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid); - } -}; - -app.map({ - '/users': { - get: users2.list, - del: users2.del, - '/:uid': { - get: users.get , - '/pets': { - get: pets2.list, - '/:pid': { - del: pets2.del - } - } - } - } -}); - -app.listen(3000); - -/////////////////////////// - -// Example requests: -// curl http://localhost:3000/user/0 -// curl http://localhost:3000/user/0/edit -// curl http://localhost:3000/user/1 -// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) -// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) - -function loadUser(req: express.Request, res: express.Response, next) { - // You would fetch your user from the db - var user = users[req.params.id]; - if (user) { - req.user = user; - next(); - } else { - next(new Error('Failed to load user ' + req.params.id)); - } -} - -function andRestrictToSelf(req: express.Request, res: express.Response, next) { - // If our authenticated user is the user we are viewing - // then everything is fine :) - if (req.authenticatedUser.id == req.user.id) { - next(); - } else { - // You may want to implement specific exceptions - // such as UnauthorizedError or similar so that you - // can handle these can be special-cased in an error handler - // (view ./examples/pages for this) - next(new Error('Unauthorized')); - } -} - -function andRestrictTo(role) { - return (req: express.Request, res: express.Response, next) => { - if (req.authenticatedUser.role == role) { - next(); - } else { - next(new Error('Unauthorized')); - } - }; -} - -// Middleware for faux authentication -// you would of course implement something real, -// but this illustrates how an authenticated user -// may interact with middleware - -app.use((req: express.Request, res: express.Response, next) => { - req.authenticatedUser = users[0]; - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user/0'); -}); - -app.get('/user/:id', loadUser, (req: express.Request, res: express.Response) => { - res.send('Viewing user ' + req.user.name); -}); - -app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req: express.Request, res: express.Response) => { - res.send('Editing user ' + req.user.name); -}); - -app.del('/user/:id', loadUser, andRestrictTo('admin'), (req: express.Request, res: express.Response) => { - res.send('Deleted user ' + req.user.name); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -///////////////////////// - -app.set('view engine', 'jade'); -app.set('views', __dirname); - -// populate search - -db.sadd('ferret', 'tobi'); -db.sadd('ferret', 'loki'); -db.sadd('ferret', 'jane'); -db.sadd('cat', 'manny'); -db.sadd('cat', 'luna'); - -/** - * GET the search page. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('search'); -}); - -/** - * GET search for :query. - */ - -app.get('/search/:query?', (req: express.Request, res: express.Response) => { - var query = req.params.query; - db.smembers(query, (err, vals) => { - if (err) return res.send(500); - res.send(vals); - }); -}); - -/** - * GET client javascript. Here we use sendfile() - * because serving __dirname with the static() middleware - * would also mean serving our server "index.js" and the "search.jade" - * template. - */ - -app.get('/client.js', (req: express.Request, res: express.Response) => { - res.sendfile(__dirname + '/client.js'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////// - -app.use(express.logger('dev')); - -// Required by session() middleware -// pass the secret for signed cookies -// (required by session()) -app.use(express.cookieParser('keyboard cat')); - -// Populates req.session -app.use(express.session()); - -app.get('/', (req: express.Request, res: express.Response) => { - var body = ''; - if (req.session.views) { - ++req.session.views; - } else { - req.session.views = 1; - body += '

First time visiting? view this page in several browsers :)

'; - } - res.send(body + '

viewed ' + req.session.views + ' times.

'); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////////// - -// log requests -app.use(express.logger('dev')); - -// express on its own has no notion -// of a "file". The express.static() -// middleware checks for a file matching -// the `req.path` within the directory -// that you pass it. In this case "GET /js/app.js" -// will look for "./public/js/app.js". - -app.use(express.static(__dirname + '/public')); - -// if you wanted to "prefix" you may use -// the mounting feature of Connect, for example -// "GET /static/js/app.js" instead of "GET /js/app.js". -// The mount-path "/static" is simply removed before -// passing control to the express.static() middleware, -// thus it serves the file correctly by ignoring "/static" -app.use('/static', express.static(__dirname + '/public')); - -// if for some reason you want to serve files from -// several directories, you can use express.static() -// multiple times! Here we're passing "./public/css", -// this will allow "GET /style.css" instead of "GET /css/style.css": -app.use(express.static(__dirname + '/public/css')); - -// this examples does not have any routes, however -// you may `app.use(app.router)` before or after these -// static() middleware. If placed before them your routes -// will be matched BEFORE file serving takes place. If placed -// after as shown here then file serving is performed BEFORE -// any routes are hit: -app.use(app.router); - -app.listen(3000); -console.log('listening on port 3000'); -console.log('try:'); -console.log(' GET /hello.txt'); -console.log(' GET /js/app.js'); -console.log(' GET /css/style.css'); - -////////////////// - -/* -edit /etc/vhosts: - -127.0.0.1 foo.example.com -127.0.0.1 bar.example.com -127.0.0.1 example.com -*/ - -// Main app - -var main = express(); - -main.use(express.logger('dev')); - -main.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello from main app!'); -}); - -main.get('/:sub', (req: express.Request, res: express.Response) => { - res.send('requsted ' + req.params.sub); -}); - -// Redirect app - -var redirect = express(); - -redirect.all('*', (req: express.Request, res: express.Response) => { - console.log(req.subdomains); - res.redirect('http://example.com:3000/' + req.subdomains[0]); -}); - -app.use(express.vhost('*.example.com', redirect)); -app.use(express.vhost('example.com', main)); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////// - -// create an error with .status. we -// can then use the property in our -// custom error handler (Connect repects this prop as well) - -function merror(status, msg) { - var err = new Error(msg); - err.status = status; - return err; -} - -// if we wanted to supply more than JSON, we could -// use something similar to the content-negotiation -// example. - -// here we validate the API key, -// by mounting this middleware to /api -// meaning only paths prefixed with "/api" -// will cause this middleware to be invoked - -app.use('/api', (req, res: express.Response, next) => { - var key = req.query['api-key']; - - // key isnt present - if (!key) return next(merror(400, 'api key required')); - - // key is invalid - if (!~apiKeys.indexOf(key)) return next(merror(401, 'invalid api key')); - - // all good, store req.key for route access - req.key = key; - next(); -}); - -// position our routes above the error handling middleware, -// and below our API middleware, since we want the API validation -// to take place BEFORE our routes -app.use(app.router); - -// middleware with an arity of 4 are considered -// error handling middleware. When you next(err) -// it will be passed through the defined middleware -// in order, but ONLY those with an arity of 4, ignoring -// regular middleware. -app.use((err, req, res: express.Response) => { - // whatever you want here, feel free to populate - // properties on `err` to treat it differently in here. - res.send(err.status || 500, { error: err.message }); -}); - -// our custom JSON 404 middleware. Since it's placed last -// it will be the last middleware called, if all others -// invoke next() and do not respond. -app.use((req: express.Request, res: express.Response) => { - res.send(404, { error: "Lame, can't find that" }); -}); - -// map of valid api keys, typically mapped to -// account info with some sort of database like redis. -// api keys do _not_ serve as authentication, merely to -// track API usage or help prevent malicious behavior etc. - -var apiKeys = ['foo', 'bar', 'baz']; - -// these two objects will serve as our faux database - -var repos = [ - { name: 'express', url: 'http://github.com/visionmedia/express' } - , { name: 'stylus', url: 'http://github.com/learnboost/stylus' } - , { name: 'cluster', url: 'http://github.com/learnboost/cluster' } -]; - -var userRepos = { - tobi: [repos[0], repos[1]] - , loki: [repos[1]] - , jane: [repos[2]] -}; - -// we now can assume the api key is valid, -// and simply expose the data - -app.get('/api/users', (req: express.Request, res: express.Response) => { - res.send(users); -}); - -app.get('/api/repos', (req: express.Request, res: express.Response) => { - res.send(repos); -}); - -app.get('/api/user/:name/repos', (req: express.Request, res: express.Response, next) => { - var name = req.params.name - , user = userRepos[name]; - - if (user) res.send(user); - else next(); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -////// - -var router = new express.Router(); - -router.get('/', function (req, resp, next?) { - resp.send('response from router'); - resp.end(); - if (next) { - next(); - } -}); - -function test_general() { - - app.use((err, req, res: express.Response) => { - console.error(err.stack); - res.send(500, 'Something broke!'); - }); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - app.use(() => {}); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - - app.get('/', (req: express.Request, res: express.Response) => { - res.send('hello world'); - }); - - app.listen(3000); - - app.set('title', 'My Site'); - app.get('title'); - - app.enable('trust proxy'); - app.get('trust proxy'); - - app.disable('trust proxy'); - app.get('trust proxy'); - - app.enabled('trust proxy'); - - app.configure(() => { - app.set('title', 'My Application'); - }); - - app.configure('development', () => { - app.set('db uri', 'localhost/dev'); - }); - - app.configure('stage', 'production', () => {}); - - app.configure('1', '2', '3', () => {}); - - app.use((req: express.Request, res: express.Response) => { - res.send('Hello World'); - }); - - app.engine('jade', require('jade').__express); - - var User; - app.param('user', (req: express.Request, res: express.Response, next, id) => { - User.find(id, (err, user) =>{ - if (err) { - next(err); - } else if (user) { - req.user = user; - next(); - } else { - next(new Error('failed to load user')); - } - }); - }); - - app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req: express.Request, res: express.Response) => { - var from = req.params[0]; - var to = req.params[1] || 'HEAD'; - res.send('commit range ' + from + '..' + to); - }); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - - var requireAuthentication; - var loadUser = () => {}; - app.all('*', requireAuthentication, loadUser); - app.all('*', loadUser); - app.all('*', loadUser, loadUser, loadUser); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - app.locals({ - title: 'My App', - phone: '1-250-858-9990', - email: 'me@myapp.com' - }); - app.render('email', () => {}); - - app.render('email', { name: 'Tobi' }, () => {}); -} - -function test_request() { - var req: express.Request; - req.params.name; - req.params[0]; - req.query.q; - req.body.user.name; - app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })); - req.param('name'); - req.route; - req.cookies.name; - req.signedCookies; - req.get('Content-Type'); - req.accepts('html'); - req.accepts(['html', 'json']); - req.is('html'); - req.ip; - req.path; - req.host; - req.fresh; - req.stale; - req.xhr; - req.protocol; - req.subdomains; - req.originalUrl; - req.acceptedLanguages; - req.acceptedCharsets; - var charset; - req.acceptsCharset(charset); - var lang; - req.acceptsLanguage(lang); - req.session = null; -} - -function test_response() { - var res: express.Response; - res.status(404).sendfile('path/to/404.png'); - res.set('Content-Type', 'text/plain'); - res.set({ - 'Content-Type': 'text/plain', - 'Content-Length': '123', - 'ETag': '12345' - }); - res.get('Content-Type'); - res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); - res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }); - res.cookie('cart', { items: [1, 2, 3] }); - res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });; - res.cookie('name', 'tobi', { signed: true }); - res.cookie('name', 'tobi', { path: '/admin' }); - res.clearCookie('name', { path: '/admin' }); - res.redirect('/foo/bar'); - res.redirect('http://example.com'); - res.redirect(301, 'http://example.com'); - res.charset = 'value'; - res.send('some html'); - res.send(new Buffer('whoop')); - res.send({ some: 'json' }); - res.send('some html'); - res.send(404, 'Sorry, we cannot find that!'); - res.send(500, { error: 'something blew up' }); - res.send(200); - res.set('Content-Type', 'text/html'); - res.send(new Buffer('some html')); - res.send('some html'); - res.send({ user: 'tobi' }); - res.send([1, 2, 3]); - res.json(null); - res.json({ user: 'tobi' }); - res.json(500, { error: 'message' }); - res.jsonp(null); - res.jsonp({ user: 'tobi' }); - res.jsonp(500, { error: 'message' }); - res.jsonp({ user: 'tobi' }); - res.type('application/json'); - - res.format({ - 'text/plain': () => { - res.send('hey'); - }, - 'text/html': () => { - res.send('hey'); - }, - 'application/json': () => { - res.send({ message: 'hey' }); - } - }); - - res.attachment(); - res.attachment('path/to/logo.png'); - app.get('/user/:uid/photos/:file', (req: express.Request, res: express.Response) => { - var uid = req.params.uid - , file = req.params.file; - - req.user.mayViewFilesFrom(uid, yes => { - if (yes) { - res.sendfile('/uploads/' + uid + '/' + file); - } else { - res.send(403, 'Sorry! you cant see that.'); - } - }); - }); - - res.download('/report-12345.pdf'); - res.download('/report-12345.pdf', 'report.pdf'); - res.download('/report-12345.pdf', 'report.pdf', err => { - if (err) { } else { } - }); - - res.links({ - next: 'http://api.example.com/users?page=2', - last: 'http://api.example.com/users?page=5' - }); - - app.use((req: express.Request, res: express.Response, next) => { - res.locals.user = req.user; - res.locals.authenticated = !req.user.anonymous; - next(); - }); - res.render('index', () => {}); - res.render('user', { name: 'Tobi' }, () => {}); - -} - -function test_middleware() { - app.use(express.basicAuth('username', 'password')); - app.use(express.basicAuth((user, pass) => { - return 'tj' == user && 'wahoo' == pass; - })); - app.use(express.bodyParser()); - app.use(express.json()); - app.use(express.urlencoded()); - app.use(express.multipart()); - app.use(express.logger()); - app.use(express.compress()); - app.use(express.methodOverride()); - app.use(express.bodyParser()); - app.use(express.cookieParser()); - app.use(express.cookieParser('some secret')); - app.use(express.cookieSession()); - app.use(express.directory('public')); - app.use(express.static('public')); - app.use(router.middleware); -} - -//////////////////// - -// make sure server can be shut down -var testShutdownServer = app.listen(0); -console.log('listening on port ' + testShutdownServer.address().port); -testShutdownServer.close(); diff --git a/express/express-3.1.0-tests.ts.tscparams b/express/express-3.1.0-tests.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/express/express-3.1.0-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/express/express-3.1.0.d.ts b/express/express-3.1.0.d.ts deleted file mode 100644 index d5865f418..000000000 --- a/express/express-3.1.0.d.ts +++ /dev/null @@ -1,1832 +0,0 @@ -// Type definitions for Express 3.1 -// Project: http://expressjs.com -// Definitions by: Boris Yankov -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped - -/* =================== USAGE =================== - - import express = require('express'); - var app = express(); - - =============================================== */ - -/// - - -declare module Express { - - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example passport.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/passport/passport.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } -} - - -declare module "express" { - import http = require('http'); - - // Merged declaration, e is both a callable function and a namespace - function e(): e.Express; - - module e { - interface IRoute { - path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - - /** - * Check if this route matches `path`, if so - * populate `.params`. - */ - match(path: string): boolean; - } - - class Route implements IRoute { - path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - match(path: string): boolean; - - /** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: - * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param method - * @param path - * @param callbacks - * @param options - */ - new (method: string, path: string, callbacks: Function[], options: any): Route; - } - - interface IRouter { - /** - * 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, fn: Function): T; - - param(name: string[], fn: Function): T; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; - - all(path: string, ...callbacks: Function[]): void; - - get(name: string, ...handlers: RequestFunction[]): T; - - get(name: RegExp, ...handlers: RequestFunction[]): T; - - post(name: string, ...handlers: RequestFunction[]): T; - - post(name: RegExp, ...handlers: RequestFunction[]): T; - - put(name: string, ...handlers: RequestFunction[]): T; - - put(name: RegExp, ...handlers: RequestFunction[]): T; - - del(name: string, ...handlers: RequestFunction[]): T; - - del(name: RegExp, ...handlers: RequestFunction[]): T; - - patch(name: string, ...handlers: RequestFunction[]): T; - - patch(name: RegExp, ...handlers: RequestFunction[]): T; - } - - export class Router implements IRouter { - new (options?: any): Router; - - middleware (): any; - - param(name: string, fn: Function): Router; - - param(name: any[], fn: Function): Router; - - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; - - all(path: string, ...callbacks: Function[]): void; - - get(name: string, ...handlers: RequestFunction[]): Router; - - get(name: RegExp, ...handlers: RequestFunction[]): Router; - - post(name: string, ...handlers: RequestFunction[]): Router; - - post(name: RegExp, ...handlers: RequestFunction[]): Router; - - put(name: string, ...handlers: RequestFunction[]): Router; - - put(name: RegExp, ...handlers: RequestFunction[]): Router; - - del(name: string, ...handlers: RequestFunction[]): Router; - - del(name: RegExp, ...handlers: RequestFunction[]): Router; - - patch(name: string, ...handlers: RequestFunction[]): Router; - - patch(name: RegExp, ...handlers: RequestFunction[]): Router; - } - - interface Handler { - (req: Request, res: Response, next?: Function): void; - } - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean; - } - - interface Errback { (err: Error): void; } - - interface Session { - /** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - touch(): Session; - - /** - * Reset `.maxAge` to `.originalMaxAge`. - */ - resetMaxAge(): Session; - - /** - * Save the session data with optional callback `fn(err)`. - */ - save(fn: Function): Session; - - /** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - */ - reload(fn: Function): Session; - - /** - * Destroy `this` session. - */ - destroy(fn: Function): Session; - - /** - * Regenerate this request's session. - */ - regenerate(fn: Function): Session; - - user: any; - - error: string; - - success: string; - - views: any; - - count: number; - } - - interface Request extends http.ServerRequest, Express.Request { - - session: Session; - - /** - * 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; - - /** - * Check if the given `charset` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param charset - */ - acceptsCharset(charset: string): boolean; - - /** - * Check if the given `lang` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param lang - */ - acceptsLanguage(lang: string): boolean; - - /** - * 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 an array of Accepted languages - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Language: en;q=.5, en-us - * ['en-us', 'en'] - */ - acceptedLanguages: any[]; - - /** - * 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[]; - - /** - * 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 basic auth credentials. - * - * Examples: - * - * // http://tobi:hello@example.com - * req.auth - * // => { username: 'tobi', password: 'hello' } - */ - auth: any; - - /** - * 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. - */ - 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; - - /** - * 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; - } - - 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 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; - } - - interface RequestFunction { - (req: Request, res: Response, next: Function): 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; - - /** - * Proxy `connect#use()` to apply settings to - * mounted applications. - **/ - use(route: string, callback?: Function): Application; - - use(route: string, server: Application): Application; - - use(callback: Function): Application; - - use(server: Application): Application; - - /** - * 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; - - param(name: string, fn: Function): Application; - - param(name: string[], fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set (setting: string, val: string): Application; - - get(name: string): string; - - get(name: string, ...handlers: RequestFunction[]): Application; - - get(name: RegExp, ...handlers: RequestFunction[]): 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(env: 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; - - configure(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: 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; - } - - /** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param options - */ - function bodyParser(options?: any): Handler; - - /** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - */ - function errorHandler(opts?: any): Handler; - - /** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param key - */ - function methodOverride(key?: string): Handler; - - /** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param secret - */ - function cookieParser(secret?: string): Handler; - - /** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent 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") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

views: ' + 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 - */ - function session(options?: any): Handler; - - /** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param sess - */ - function 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 - */ - function static(root: string, options?: any): 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 - */ - 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; - - /** - * 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 - */ - function compress(options?: any): 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 - */ - function cookieSession(options?: any): 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 - */ - export function csrf(options?: {value?: Function}): 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 - */ - function directory(root: string, options?: any): 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 - */ - export function favicon(path?: string, options?: any): 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 - */ - function json(options?: any): 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) - */ - function limit(bytes: number): Handler; - - function limit(bytes: string): 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') - */ - function logger(options: string): Handler; - - function logger(options: Function): Handler; - - function logger(options?: any): Handler; - - /** - * Compile `fmt` into a function. - * - * @param fmt - */ - function compile(fmt: string): Handler; - - /** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param name - * @param fn - */ - function token(name: string, fn: Function): any; - - /** - * Define a `fmt` with the given `name`. - */ - function format(name: string, str: string): any; - - function 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. - */ - function query(options: any): Handler; - - /** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - */ - function responseTime(): 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 - */ - function staticCache(options: any): 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`. - */ - function timeout(ms: number): 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 - */ - function vhost(hostname: string, server: any): Handler; - - function urlencoded(): any; - - function multipart(): any; - - } - - export = e; -} - From 8b07ce8811369dfe80a465e292ba1d1f43281288 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:18:27 +0100 Subject: [PATCH 015/167] A Router is also a RequestHandler --- express/express.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express/express.d.ts b/express/express.d.ts index 052173c83..2dc36199c 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -38,7 +38,7 @@ declare module "express" { (name: RegExp, ...handlers: RequestHandler[]): T; } - interface IRouter { + interface IRouter extends RequestHandler { /** * Map the given param placeholder `name`(s) to the given callback(s). * From 43f1770f23c542e5b07b102f6f2b7fbf58eb82d8 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:22:10 +0100 Subject: [PATCH 016/167] use takes multiple request handlers now --- express/express.d.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index 2dc36199c..3eb3649d9 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -89,12 +89,10 @@ declare module "express" { route(path: string): IRoute; - use(server: Application): Application; - use(handler: RequestHandler): Application; - use(handler: ErrorRequestHandler): Application; - use(path: string, server: Application): Application; - use(path: string, handler: RequestHandler): Application; - use(path: string, handler: ErrorRequestHandler): Application; + use(...handler: RequestHandler[]): T; + use(handler: ErrorRequestHandler): T; + use(path: string, ...handler: RequestHandler[]): T; + use(path: string, handler: ErrorRequestHandler): T; } export function Router(options?: any): Router; From e039638763ea9c7e581a32fcfac3b4559ac47506 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 13:22:19 +0100 Subject: [PATCH 017/167] Add more tests --- express/express-tests.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/express/express-tests.ts b/express/express-tests.ts index cda1e3e2e..76fa4da0d 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -18,4 +18,19 @@ app.get('/', function(req, res){ res.send('hello world'); }); +var router = express.Router(); + +router.use((req, res, next) => { next(); }) +router.route('/users') + .get((req, res, next) => { + res.send(req.query['token']); + }); + +app.use((req, res, next) => { + // hacky trick, router is just a handler + router(req, res, next); +}); + +app.use(router); + app.listen(3000); From c7cb7f5ceaa6eba0e18f4b4c8d67af833cd34ee5 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:17:47 +0100 Subject: [PATCH 018/167] Fix errorhandler test --- errorhandler/errorhandler-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/errorhandler/errorhandler-tests.ts b/errorhandler/errorhandler-tests.ts index 02f788790..1d02ed14c 100644 --- a/errorhandler/errorhandler-tests.ts +++ b/errorhandler/errorhandler-tests.ts @@ -1,4 +1,4 @@ -/// +/// import express = require('express'); import errorhandler = require('errorhandler'); From 9dbba87a0de04697b26391557f48acfff113b7ce Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:20:44 +0100 Subject: [PATCH 019/167] Fix headers --- body-parser/body-parser.d.ts | 2 +- compression/compression.d.ts | 2 +- cookie-parser/cookie-parser.d.ts | 2 +- errorhandler/errorhandler.d.ts | 2 +- express/express.d.ts | 2 +- method-override/method-override.d.ts | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index f16b2eefb..0cd67332a 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,7 +1,7 @@ // Type definitions for body-parser // Project: http://expressjs.com // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/compression/compression.d.ts b/compression/compression.d.ts index 9ef3a8cb7..00b2e0459 100644 --- a/compression/compression.d.ts +++ b/compression/compression.d.ts @@ -1,7 +1,7 @@ // Type definitions for compression // Project: https://github.com/expressjs/compression // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/cookie-parser/cookie-parser.d.ts b/cookie-parser/cookie-parser.d.ts index f43553b7c..a4897c5e7 100644 --- a/cookie-parser/cookie-parser.d.ts +++ b/cookie-parser/cookie-parser.d.ts @@ -1,7 +1,7 @@ // Type definitions for cookie-parser // Project: https://github.com/expressjs/cookie-parser // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/errorhandler/errorhandler.d.ts b/errorhandler/errorhandler.d.ts index e6c3011a5..31bf44ce1 100644 --- a/errorhandler/errorhandler.d.ts +++ b/errorhandler/errorhandler.d.ts @@ -1,7 +1,7 @@ // Type definitions for errorhandler // Project: https://github.com/expressjs/errorhandler // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/express/express.d.ts b/express/express.d.ts index 3eb3649d9..18d6f993a 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -1,7 +1,7 @@ // Type definitions for Express 4.x // Project: http://expressjs.com // Definitions by: Boris Yankov -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/method-override/method-override.d.ts b/method-override/method-override.d.ts index 51b62f521..099b5eeb9 100644 --- a/method-override/method-override.d.ts +++ b/method-override/method-override.d.ts @@ -1,7 +1,7 @@ // Type definitions for method-override // Project: https://github.com/expressjs/method-override // Definitions by: Santi Albo -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 6db771a25952f260a8cbc412fcd158cb9b04e360 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:23:22 +0100 Subject: [PATCH 020/167] Add Handler interface for backwards compatibility on Passport type definitions --- express/express.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/express/express.d.ts b/express/express.d.ts index 18d6f993a..984007192 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -746,6 +746,8 @@ declare module "express" { (req: Request, res: Response, next: Function): any; } + interface Handler extends RequestHandler {} + interface RequestParamHandler { (req: Request, res: Response, next: Function, param: any): any; } From dc8ac9a4789408c9232bd41d42cbc32180455bf6 Mon Sep 17 00:00:00 2001 From: Santi Albo Date: Thu, 17 Jul 2014 19:43:47 +0100 Subject: [PATCH 021/167] Fix passport tests --- passport/passport.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 37d4035a0..fc3dd786f 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -5,6 +5,12 @@ /// +declare module Express { + export interface Request { + session?: any; + } +} + declare module 'passport' { import express = require('express'); From fe47b495c8aa7ee551fb3239fb08c93f15a05f92 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Mon, 21 Jul 2014 11:09:13 +0200 Subject: [PATCH 022/167] angularjs: allow $q.when to be called w/o args The current definition does not cover the case that the input type is void. --- angularjs/angular-tests.ts | 6 ++++++ angularjs/angular.d.ts | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 37dae22f4..d7534bc36 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -139,6 +139,12 @@ module HttpAndRegularPromiseTests { dPromise.then((snack: string) => { $scope.snack = snack; }); + + // $q.when may be called without arguments + var ePromise: ng.IPromise = $q.when(); + ePromise.then(() => { + $scope.nothing = "really nothing"; + }); } // Test that we can pass around a type-checked success/error Promise Callback diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index d6b649a33..3880a8c05 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -565,6 +565,12 @@ declare module ng { * @param value Value or a promise */ when(value: T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(): IPromise; } interface IPromise { From 625b9f2523e465181c9b3793269a2755e4fddca7 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Mon, 21 Jul 2014 15:33:31 +0200 Subject: [PATCH 023/167] Fixup --- angularjs/angular-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index d7534bc36..647287215 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -141,7 +141,7 @@ module HttpAndRegularPromiseTests { }); // $q.when may be called without arguments - var ePromise: ng.IPromise = $q.when(); + var ePromise: ng.IPromise = $q.when(); ePromise.then(() => { $scope.nothing = "really nothing"; }); From a7c4e5074328c50acf03ef0bf5bd44c31c80fed1 Mon Sep 17 00:00:00 2001 From: Frederik Wordenskjold Date: Mon, 21 Jul 2014 15:35:58 +0200 Subject: [PATCH 024/167] Added channel support to Marionette.d.ts Marionette.d.ts includes definitions for Backbone.Wreqr, but does not support the recommended way of using the Wreqr object as seen here: https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.application.md#accessing-the-global-channel I've added the Channel object, and a definition to the Radio class as well. This is only a means of getting a specific channel through the channel() method, so while it is possible to create an instance of Radio, I've chosen only to include channel() method, and make it static. This makes it possible to access the instance of a channel with the name 'global' like this (created if not found), as recommended in the above documentation: var channel = Backbone.Wreqr.radio.channel('global'); // channel.vent; Finally, I've made the parameter context of the setHandler method in the Backbone.Wreqr.Handlers class optional, as this adheres to the actual implementation. --- marionette/marionette.d.ts | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 96672ca3f..9ff239dc5 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -57,13 +57,35 @@ declare module Backbone { // Backbone.Wreqr module Wreqr { + class radio { + + static channel(channelName: string): Channel; + + } + + class Channel { + + constructor(channelName: string); + + vent: Backbone.Wreqr.EventAggregator; + reqres: Backbone.Wreqr.RequestResponse; + commands: Backbone.Wreqr.Commands; + channelName: string; + + reset(): Channel; + connectEvents(hash: string, context: any): Channel; + connectCommands(hash: string, context: any): Channel; + connectRequests(hash: string, context: any): Channel; + + } + class Handlers extends Backbone.Events { constructor(options?: any); options: any; - setHandler(name: string, handler: any, context: any): void; + setHandler(name: string, handler: any, context?: any): void; hasHandler(name: string): boolean; getHandler(name: string): Function; removeHandler(name: string); From c0df8aa594852cec97d841e28488d9b39b1c62ee Mon Sep 17 00:00:00 2001 From: Brian Malehorn Date: Mon, 21 Jul 2014 17:56:42 -0700 Subject: [PATCH 025/167] fix a number of bugs in d3.d.ts Most are a result of setter = foo.bar(x), getter = foo.bar() only reflecting the setter signature. --- d3/d3.d.ts | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 598cd9f34..8da827f4e 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -243,7 +243,7 @@ declare module D3 { * * @param map Array of objects to get the values from */ - values(map: any[]): any[]; + values(map: any): any[]; /** * List the key-value entries of an associative array. * @@ -1720,10 +1720,21 @@ declare module D3 { (): any[]; (values: any[]): Axis; }; - tickSubdivide(count: number): Axis; - tickSize(major?: number, minor?: number, end?: number): Axis; + tickSize: { + (): number; + (inner: number, outer?: number): Axis; + } + innerTickSize: { + (): number; + (value: number): Axis; + } + outerTickSize: { + (): number; + (value: number): Axis; + } tickFormat(formatter: (value: any) => string): Axis; + nice(count?: number): Axis; } export interface Arc { @@ -2569,7 +2580,10 @@ declare module D3 { * * @param clamp Enable or disable */ - clamp(clamp: boolean): QuantitiveScale; + clamp: { + (): boolean; + (clamp: boolean): QuantitiveScale; + } /** * extend the scale domain to nice round numbers. * @@ -2587,7 +2601,7 @@ declare module D3 { * * @param count Aproximate representative values to return */ - tickFormat(count: number): (n: number) => string; + tickFormat(count: number, format?: string): (n: number) => string; /** * create a new scale from an existing scale.. */ @@ -2768,6 +2782,7 @@ declare module D3 { }; tickFormat(count: number): (n: number) => string; copy(): TimeScale; + nice(count?: number): TimeScale; } } From fde9a8e787f472f252b163ba83ed4e86867e1834 Mon Sep 17 00:00:00 2001 From: StefanSchoof Date: Tue, 22 Jul 2014 20:58:26 +0200 Subject: [PATCH 026/167] Added calendar Property to GlobalizeCulture The calendar Property is used to get and set the default calendar. See https://github.com/jquery/globalize/tree/79ae658b842f75f58199d6e9074e01f7ce207468#defining-culture-information and https://github.com/jquery/globalize/blob/79ae658b842f75f58199d6e9074e01f7ce207468/lib/globalize.js#L263 --- globalize/globalize.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index 0bdaeb4bf..4510e38cb 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -91,6 +91,7 @@ interface GlobalizeCulture { isRTL: boolean; language: string; numberFormat: GlobalizeNumberFormat; + calendar: GlobalizeCalendar; calendars: GlobalizeCalendars; messages: any; } From 1d60391f76fc07dc7ba42d3f811c13306d2cd22f Mon Sep 17 00:00:00 2001 From: Bart van der Schoor Date: Tue, 22 Jul 2014 21:27:20 +0200 Subject: [PATCH 027/167] node.d.ts : pass Uint8Array to Buffer constructor closes #2499 --- node/node.d.ts | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index d7c06203b..282120dc6 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -50,6 +50,7 @@ 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; @@ -63,6 +64,7 @@ interface Buffer extends NodeBuffer {} declare var Buffer: { new (str: string, encoding?: string): Buffer; new (size: number): Buffer; + new (size: Uint8Array): Buffer; new (array: any[]): Buffer; prototype: Buffer; isBuffer(obj: any): boolean; @@ -760,18 +762,18 @@ declare module "net" { declare module "dgram" { import events = require("events"); - interface RemoteInfo { - address: string; - port: number; - size: number; - } - - interface AddressInfo { - address: string; - family: string; - port: number; - } - + 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 { From c0e29234f7681f88ada9aa4ce09a32f655cb3388 Mon Sep 17 00:00:00 2001 From: brentj73 Date: Wed, 23 Jul 2014 12:19:26 +0100 Subject: [PATCH 028/167] Added typing for recaptcha.js --- recaptcha/recaptcha-tests.ts | 52 ++++++++++++++++++++++++++++++++++++ recaptcha/recaptcha.d.ts | 39 +++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 recaptcha/recaptcha-tests.ts create mode 100644 recaptcha/recaptcha.d.ts diff --git a/recaptcha/recaptcha-tests.ts b/recaptcha/recaptcha-tests.ts new file mode 100644 index 000000000..61ef51d9f --- /dev/null +++ b/recaptcha/recaptcha-tests.ts @@ -0,0 +1,52 @@ +/// + +var recaptchaOptions: RecaptchaOptions = { + theme : 'custom', + custom_theme_widget: 'recaptcha_widget' + }; + +var recaptchaOptions: RecaptchaOptions = { + custom_translations: { instructions_visual: "This is my text:" } +}; + +var recaptchaOptions: RecaptchaOptions = { + custom_translations: { + instructions_visual: "Scrivi le due parole:", + instructions_audio: "Trascrivi ci\u00f2 che senti:", + play_again: "Riascolta la traccia audio", + cant_hear_this: "Scarica la traccia in formato MP3", + visual_challenge: "Modalit\u00e0 visiva", + audio_challenge: "Modalit\u00e0 auditiva", + refresh_btn: "Chiedi due nuove parole", + help_btn: "Aiuto", + incorrect_try_again: "Scorretto. Riprova.", + }, + lang: 'it', + theme: 'red' +}; + +var recaptchaOptions: RecaptchaOptions = { + theme : 'white', + tabindex : 2 +}; + +Recaptcha.create("public_key_a", + "element_id_a", + { + theme: "red", + callback: Recaptcha.focus_response_field + } +); + +Recaptcha.create("public_key_b", + "element_id_b", + recaptchaOptions +); + +Recaptcha.switch_type("audio"); +Recaptcha.get_challenge(); +Recaptcha.get_response(); +Recaptcha.reload(); +Recaptcha.showhelp(); +Recaptcha.focus_response_field(); +Recaptcha.destroy(); diff --git a/recaptcha/recaptcha.d.ts b/recaptcha/recaptcha.d.ts new file mode 100644 index 000000000..410db7651 --- /dev/null +++ b/recaptcha/recaptcha.d.ts @@ -0,0 +1,39 @@ +// Type definitions for Google Recaptcha +// Project: https://www.google.com/recaptcha +// Definitions by: Brent Jenkins +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class Recaptcha { + constructor(); + static reload(): void; + static switch_type(newtype: any); + static showhelp(): void; + static get_challenge(): string; + static get_response(): string; + static focus_response_field(): void; + static create(public_key: string, element: string, options: RecaptchaOptions): void; + static destroy(): void; +} + +interface RecaptchaOptions { + tabindex?: number; + theme?: string; + callback?: Function; + lang?: string; + custom_theme_widget?: string; + custom_translations?: CustomTranslations; +} + +interface CustomTranslations { + visual_challenge?: string; + audio_challenge?: string; + refresh_btn?: string; + instructions_visual?: string; + instructions_audio?: string; + help_btn?: string; + play_again?: string; + cant_hear_this?: string; + incorrect_try_again?: string; + image_alt_text?: string; + privacy_and_terms?: string; +} \ No newline at end of file From 4c3b64221298a22ea834fbb7c27e5c92a67f1615 Mon Sep 17 00:00:00 2001 From: brentj73 Date: Wed, 23 Jul 2014 13:01:36 +0100 Subject: [PATCH 029/167] Updated switch_type method with correct types --- recaptcha/recaptcha.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/recaptcha/recaptcha.d.ts b/recaptcha/recaptcha.d.ts index 410db7651..db2096275 100644 --- a/recaptcha/recaptcha.d.ts +++ b/recaptcha/recaptcha.d.ts @@ -6,7 +6,7 @@ declare class Recaptcha { constructor(); static reload(): void; - static switch_type(newtype: any); + static switch_type(newtype: string): void; static showhelp(): void; static get_challenge(): string; static get_response(): string; @@ -36,4 +36,4 @@ interface CustomTranslations { incorrect_try_again?: string; image_alt_text?: string; privacy_and_terms?: string; -} \ No newline at end of file +} From ba1b3d7d609b1cde8d828cd67b91003e6aa3a60a Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Wed, 23 Jul 2014 14:08:31 +0200 Subject: [PATCH 030/167] Fixup --- angularjs/angular-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 647287215..788545156 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -95,6 +95,7 @@ module HttpAndRegularPromiseTests { theAnswer: number; letters: string[]; snack: string; + nothing?: string; } var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { From 1e9a25470164976c069ecc4c7dce1941f60e85d8 Mon Sep 17 00:00:00 2001 From: Nickolas Westman Date: Wed, 23 Jul 2014 11:24:32 -0700 Subject: [PATCH 031/167] Update Anon Function Parameters in asyncTest Encountered compiler errors on using asyncTest ... fixed by making sure that the assert is a function of the anon function --- qunit/qunit.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/qunit/qunit.d.ts b/qunit/qunit.d.ts index 5628feaa6..c6fe34f0f 100644 --- a/qunit/qunit.d.ts +++ b/qunit/qunit.d.ts @@ -381,7 +381,7 @@ interface QUnitStatic extends QUnitAssert{ * @param expected Number of assertions in this test * @param test Function to close over assertions */ - asyncTest(name: string, expected: number, test: () => any): any; + asyncTest(name: string, expected: number, test: (assert: QUnitAssert) => any): any; /** * Add an asynchronous test to run. The test must include a call to start(). @@ -392,7 +392,7 @@ interface QUnitStatic extends QUnitAssert{ * @param name Title of unit being tested * @param test Function to close over assertions */ - asyncTest(name: string, test: () => any): any; + asyncTest(name: string, test: (assert: QUnitAssert) => any): any; /** * Specify how many assertions are expected to run within a test. @@ -662,7 +662,7 @@ declare function testStart(callback: (details: TestStartCallbackObject) => any): * @param expected Number of assertions in this test * @param test Function to close over assertions */ -declare function asyncTest(name: string, expected?: any, test?: () => any): any; +declare function asyncTest(name: string, expected?: any, test?: (assert: QUnitAssert) => any): any; /** * Add an asynchronous test to run. The test must include a call to start(). @@ -673,7 +673,7 @@ declare function asyncTest(name: string, expected?: any, test?: () => any): any; * @param name Title of unit being tested * @param test Function to close over assertions */ -declare function asyncTest(name: string, test: () => any): any; +declare function asyncTest(name: string, test: (assert: QUnitAssert) => any): any; /** * Specify how many assertions are expected to run within a test. From b1776d0257335d62d9f7d5a475d3a26cf1b34a74 Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Wed, 23 Jul 2014 23:00:11 +0100 Subject: [PATCH 032/167] Dropbox-JS Definition. The dropbox-js project is a wrapped for the Dropbox API. --- dropboxjs/dropboxjs-tests.ts | 54 +++++++++++++++++++ dropboxjs/dropboxjs.d.ts | 101 +++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 dropboxjs/dropboxjs-tests.ts create mode 100644 dropboxjs/dropboxjs.d.ts diff --git a/dropboxjs/dropboxjs-tests.ts b/dropboxjs/dropboxjs-tests.ts new file mode 100644 index 000000000..cf5fd3827 --- /dev/null +++ b/dropboxjs/dropboxjs-tests.ts @@ -0,0 +1,54 @@ +/// + +var browserClient = new Dropbox.Client({ key: "your-key-here" }); + +browserClient.authenticate(function (error, client) { + if (error) { + alert(error); + } + + client.onError.addListener(function (error) { + if (window.console) { // Skip the "if" in node.js code. + console.error(error); + } + }); + + client.getAccountInfo(function (error, accountInfo) { + if (error) { + alert(error); // Something went wrong. + } + + alert("Hello, " + accountInfo.name + "!"); + }); + + client.writeFile("hello_world.txt", "Hello, world!\n", function (error, stat) { + if (error) { + alert(error); // Something went wrong. + } + + alert("File saved as revision " + stat.versionTag); + }); + + client.readFile("hello_world.txt", function (error, data) { + if (error) { + alert(error); // Something went wrong. + } + + alert(data); // data has the file's contents + }); + + client.readdir("/", function (error, entries) { + if (error) { + alert(error); // Something went wrong. + } + + alert("Your Dropbox contains " + entries.join(", ")); + }); +}); + +var serverClient = new Dropbox.Client({ + key: "your-key-here", + secret: "your-secret-here" +}); + +serverClient.authDriver(new Dropbox.AuthDriver.NodeServer(8191)); \ No newline at end of file diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts new file mode 100644 index 000000000..a718fabaf --- /dev/null +++ b/dropboxjs/dropboxjs.d.ts @@ -0,0 +1,101 @@ +// Type definitions for dropbox-js +// Project: https://github.com/dropbox/dropbox-js +// Definitions by: Steve Fenton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Dropbox { + export interface DropboxConfig { + key: string; + secret?: string; + } + + export interface AccountInfoData { + name: string; + email: string; + countryCode: string; + uid: string; + referralUrl: string; + publicAppUrl: string; + quota: number; + usedQuota: number; + privateBytes: number; + sharedBytes: number; + } + + export interface AccountInfo extends AccountInfoData { + parse(accountInfo: string): AccountInfo; + json(): AccountInfoData; + } + + export interface ApiError { + INVALID_TOKEN: number; + NOT_FOUND: number; + OVER_QUOTA: number; + RATE_LIMITED: number; + NETWORK_ERROR: number; + INVALID_PARAM: number; + OAUTH_ERROR: number; + INVALID_METHOD: number; + } + + export interface FileStatisticsData { + path: string; + name: string; + inAppFolder: boolean; + isFolder: boolean; + isFile: boolean; + isRemoved: boolean; + typeIcon: string; + versionTag: string; + contentHash: string; + mimeType: string; + size: number; + humanSize: string; + hasThumbnail: boolean; + modifiedAt: Date; + clientModifiedAt: Date; + } + + export interface FileStatistics extends FileStatisticsData { + parse(stats: string): FileStatistics; + json(): FileStatisticsData; + } + + export interface ClientOnError { + addListener(callback: (error: number) => any): void; + } + + export interface Client { + new (config: DropboxConfig): Client; + authDriver(authDriver: any): Client; + authenticate(callback: (error: number, client: Client) => any): Client; + credentials(): string; + dropboxUid(): string; + isAuthenticated(): boolean; + onError: ClientOnError; + getAccountInfo(callback: (error: number, accountInfo: AccountInfo) => any): XMLHttpRequest; + getUserInfo(callback: (error: number, accountInfo: AccountInfo) => any): XMLHttpRequest; + signOut(options: {}, callback: (error: number) => any): XMLHttpRequest; + signOff(options: {}, callback: (error: number) => any): XMLHttpRequest; + writeFile(fileName: string, contents: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + writeFile(fileName: string, contents: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + readFile(fileName: string, options: {}, callback: (error: number, contents: string, stats: FileStatistics) => any): XMLHttpRequest; + readFile(fileName: string, callback: (error: number, contents: string, stats: FileStatistics) => any): XMLHttpRequest; + stat(path: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + stat(path: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + metadata(path: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + metadata(path: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest; + readdir(path: string, options: {}, callback: (error: number, entries: any[]) => any): XMLHttpRequest; + readdir(path: string, callback: (error: number, entries: any[]) => any): XMLHttpRequest; + } + + export module AuthDriver { + export interface NodeServer { + new (port: number): any; + } + + export var NodeServer: NodeServer; + } + + export var Client: Client; +} From 00fdeb909473de02d9f6634c47ece4bc87127a61 Mon Sep 17 00:00:00 2001 From: zaneli Date: Thu, 24 Jul 2014 11:32:35 +0900 Subject: [PATCH 033/167] Add definitions for bucks.js --- bucksjs/bucks-test.ts | 222 ++++++++++++++++++++++++++++++++++++++++++ bucksjs/bucks.d.ts | 55 +++++++++++ 2 files changed, 277 insertions(+) create mode 100644 bucksjs/bucks-test.ts create mode 100644 bucksjs/bucks.d.ts diff --git a/bucksjs/bucks-test.ts b/bucksjs/bucks-test.ts new file mode 100644 index 000000000..5ebbd882c --- /dev/null +++ b/bucksjs/bucks-test.ts @@ -0,0 +1,222 @@ +/// + +function add_and_end() { + // + // new Bucks object + // + var b = new Bucks(); + + // + // Add and add several tasks. + // + b.add(function f1(err, res) { + + return 'a'; + + }).add(function f2(err, res, next) { + + // res => 'a' + return next(null, 3); + + }).add(function f3(err, res, next) { + + // res => 3 + return next(new Error('error after 3')); + + }).add(function f4(err, res, next) { + + // err => 'error after 3' + return next(null, "recover 4"); + + }).add(function f5(err, res) { + + // res => 'recover 4' + throw new Error('error in f5'); + + }).add(function f6(err, res) { + + // err => 'error in f5' + throw err; + + }).add(function f7(err, res) { + + // err => 'error in f5' + // ignore and return + return "recover 7"; + + }).add(function f8(err, res, next) { + + // res => 'recover 7'; + throw new Error('error in f8'); + + }).add(function f9(err, res, next) { + + // err => 'Error in f8' + // ignore error + return next(null, 'result of 9'); + + }).end(function last(err, results) { + + // all of results + // are obtained in #end + + // err => null + + // results => [ + // 'a', + // null, + // null, + // 'recover 4', + // null, + // null, + // 'recover 7', + // null, + // 'result of 9' + // ]; + }); +} + +function then() { + var b = new Bucks(); + b.then(function start() { + return 'start'; + }).then(function second(res, next) { + // res => 'start' + return next(null, 'second') + }).end(); +} + +function delay() { + var b = new Bucks(); + b.add(function (){ /** program */ }) + .delay(1 * 1000) // 1ms + .add(function() { /** program */}) + .end(); +} + +function error() { + var b = new Bucks(); + b.then(function start() { + throw new Error('error in start'); + return 'start'; + }).error(function onError(e, next) { + // e => 'error in start' + return next(); + }).end(); +} + +function final_errorback_in_end() { + // + // last error back + // + var b = new Bucks(); + b.empty( + // add empty task (#end with no task cause error) + ).end(function last(err, res) { + // error in last callback + throw new Error('error in end'); + }, function finalErrorback(err) { + // catch uncaught error in last callback + // err => 'error in end' + }); +} + +function uncaught_error() { + try { + var b = new Bucks(); + b.then(function () { + throw new Error('error'); + }).end(); + } catch(e) { + // e => 'error' + } +} + +function waterfall() { + var t1: Bucks.Task = function t1(err, res) { + return 't1'; + }; + var t2: Bucks.Task = function t2(err, res) { + return 't2'; + }; + + new Bucks().waterfall([t1, t2]).end(function finish(err, ress) { + // ress => ['t1', 't2'] + }); + + // same as + new Bucks().add(t1).add(t2).end(function finish(err, ress) { + // ress => ['t1', 't2'] + }); +} + +function parallel() { + var b = new Bucks(); + + b.parallel([ + function task1(err, res) { + return "task1"; + }, + function task2(err, res, next) { + return next(null, "task2"); + }, + function task3(err, res, next) { + return next(new Error('passed error in task3')); + }, + function task4(err, res, next) { + throw new Error('thrown error in task4'); + } + ]).add(function getResults(err, res, next) { + // res => { + // err: [ + // null, + // null, + // [Error: passed error in task3], + // [Error: thrown error in task4] + // ], + // res: [ + // 'task1', + // 'task2', + // null, + // null + // ] + // } + next(); + }).end(); +} + +function onError() { + var onError = function (e: Error, bucks: Bucks.Bucks) { + console.log("Custom onError"); + }; + + // Bucks.onError!! + Bucks.onError(onError); + var b0 = new Bucks(); + b0 + .add(function(err, next) { + throw new Error('b0'); + }) + .end() + ; +} + +function dispose() { + var b0 = new Bucks(); + + b0.dispose = function dispose () { + // delete b0.dummy; + } + + b0 + .add(function(err, next) { + // b0.dummy = "dummy"; + next(); + }) + .end(null, null) + ; +} + +function debug() { + Bucks.DEBUG = true; +} diff --git a/bucksjs/bucks.d.ts b/bucksjs/bucks.d.ts new file mode 100644 index 000000000..111665744 --- /dev/null +++ b/bucksjs/bucks.d.ts @@ -0,0 +1,55 @@ +// Type definitions for bucks.js 0.8.3 +// Project: https://github.com/CyberAgent/bucks.js +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Bucks { + + interface BucksStatic { + + VERSION: string; + + DEBUG: boolean; + + running: Bucks[]; + + living: Bucks[]; + + new (): Bucks; + + onError(onError:(err:Error, bucks:Bucks)=>any): void; + } + + interface Bucks { + + add(task: Task): Bucks; + + then(onSuccess: (res:any, next?:Next)=>any): Bucks; + + empty(): Bucks; + + error(onError: (err:Error, res:any, next?:Next)=>any): Bucks; + + parallel(tasks: Task[]): Bucks; + + waterfall(tasks: Task[]): Bucks; + + delay(ms: number): Bucks; + + dispose(): void; + + destroy(err: Error): Bucks; + + end(callback?: (err?:Error, res?:any)=>any, errback?: (err:Error)=>any): void; + } + + interface Task { + (err?: Error, res?: any, next?: Next): any; + } + + interface Next { + (err?: Error, res?: any): any; + } +} + +declare var Bucks: Bucks.BucksStatic; From c711aaae5cde8691b1d33b6d4d9dae876a0ebfde Mon Sep 17 00:00:00 2001 From: zaneli Date: Thu, 24 Jul 2014 12:17:15 +0900 Subject: [PATCH 034/167] Add comments for bucks.js --- CONTRIBUTORS.md | 1 + bucksjs/bucks.d.ts | 84 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 72 insertions(+), 13 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index e51d544d5..4a2d5d0ea 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -39,6 +39,7 @@ All definitions files include a header with the author and editors, so at some p * [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby)) +* [bucks.js](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) * [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle)) * [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/bucksjs/bucks.d.ts b/bucksjs/bucks.d.ts index 111665744..cac3c7121 100644 --- a/bucksjs/bucks.d.ts +++ b/bucksjs/bucks.d.ts @@ -7,47 +7,105 @@ declare module Bucks { interface BucksStatic { + /** + * bucks.js version. + */ VERSION: string; + /** + * If set `true`, uncaught errors are logged. + */ DEBUG: boolean; + /** + * Running bucks objects. + */ running: Bucks[]; + /** + * Not yet called `end` bucks object. + */ living: Bucks[]; - new (): Bucks; + /** + * Create bucks object. + */ + new(): Bucks; - onError(onError:(err:Error, bucks:Bucks)=>any): void; + /** + * Catch all errors. + * @param onError Function called after catching error + */ + onError(onError: (err:Error, bucks:Bucks)=>any): void; } interface Bucks { - add(task: Task): Bucks; + /** + * Add a task. + * @param task Function added async chain + */ + add(task: TaskWithNext): Bucks; - then(onSuccess: (res:any, next?:Next)=>any): Bucks; + /** + * Add a task called only in case of success. + * @param onSuccess Function called only in case of success + */ + then(onSuccess: (res:any, next?:Task)=>any): Bucks; + /** + * Add a empty task. + */ empty(): Bucks; - error(onError: (err:Error, res:any, next?:Next)=>any): Bucks; + /** + * Add a task called only in case of error. + * @param onError Function called only in case of error + */ + error(onError: (err:Error, next?:Task)=>any): Bucks; - parallel(tasks: Task[]): Bucks; + /** + * Add tasks in asynchronous way and join their results. + * @param tasks Functions called in asynchronous way and join their results + */ + parallel(tasks: TaskWithNext[]): Bucks; - waterfall(tasks: Task[]): Bucks; + /** + * Add tasks in asynchronous way and join their results. + * @param tasks Functions added async chain + */ + waterfall(tasks: TaskWithNext[]): Bucks; + /** + * Add delay execution. + * @param ms number millisecond for delaying + */ delay(ms: number): Bucks; + /** + * Called when destroy async chain. + */ dispose(): void; - destroy(err: Error): Bucks; + /** + * Destroy this object and call last callback function. + * @param err If specify err and no callback, throw to execute failure callback + */ + destroy(err?: Error): Bucks; - end(callback?: (err?:Error, res?:any)=>any, errback?: (err:Error)=>any): void; + /** + * Complete creating async chain and start executing. + * @param callback Last callback function + * @param errback Handler for occurring error in last callback function + */ + end(callback?: Task, errback?: (err:Error)=>any): void; + } + + interface TaskWithNext { + (err?: Error, res?: any, next?: Task): any; } interface Task { - (err?: Error, res?: any, next?: Next): any; - } - - interface Next { (err?: Error, res?: any): any; } } From cd24246cad4b8ccd0cf5c5755cf53dd158bcb060 Mon Sep 17 00:00:00 2001 From: jonathantyates Date: Thu, 24 Jul 2014 00:30:20 -0400 Subject: [PATCH 035/167] Add support for plugin --- browserify/browserify.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/browserify/browserify.d.ts b/browserify/browserify.d.ts index 5326abaeb..02ac29bf2 100644 --- a/browserify/browserify.d.ts +++ b/browserify/browserify.d.ts @@ -22,6 +22,8 @@ interface BrowserifyObject extends NodeJS.EventEmitter { ignore(file: string): BrowserifyObject; transform(tr: string): BrowserifyObject; transform(tr: Function): BrowserifyObject; + plugin(plugin: string, opts?: any): BrowserifyObject; + plugin(plugin: Function, opts?: any): BrowserifyObject; } declare module "browserify" { @@ -33,4 +35,4 @@ declare module "browserify" { }): BrowserifyObject; export = browserify; -} \ No newline at end of file +} From 10f80b4b2080b3c5ede5f44cdf97f2f60b508644 Mon Sep 17 00:00:00 2001 From: zaneli Date: Thu, 24 Jul 2014 15:47:39 +0900 Subject: [PATCH 036/167] rename folder --- CONTRIBUTORS.md | 2 +- {bucksjs => bucks}/bucks-test.ts | 0 {bucksjs => bucks}/bucks.d.ts | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename {bucksjs => bucks}/bucks-test.ts (100%) rename {bucksjs => bucks}/bucks.d.ts (100%) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4a2d5d0ea..57e5eeb6f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -39,7 +39,7 @@ All definitions files include a header with the author and editors, so at some p * [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby)) -* [bucks.js](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [bucks](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) * [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle)) * [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/bucksjs/bucks-test.ts b/bucks/bucks-test.ts similarity index 100% rename from bucksjs/bucks-test.ts rename to bucks/bucks-test.ts diff --git a/bucksjs/bucks.d.ts b/bucks/bucks.d.ts similarity index 100% rename from bucksjs/bucks.d.ts rename to bucks/bucks.d.ts From 2ca13ee457f59caea2c8e49fb44aca1c4cbcd617 Mon Sep 17 00:00:00 2001 From: brentj73 Date: Thu, 24 Jul 2014 13:08:45 +0100 Subject: [PATCH 037/167] Updated contributors.md for recaptcha.js details --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index e51d544d5..ed2927d99 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -277,6 +277,7 @@ All definitions files include a header with the author and editors, so at some p * [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) * [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo)) +* [Recaptcha.js](https://www.google.com/recaptcha) (by [Brent Jenkins](https://github.com/brentj73)) * [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski)) * [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame)) * [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle)) From c322a99ff490720d05718d3d0eb6bb0fbf3c70c7 Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 24 Jul 2014 23:07:06 +0900 Subject: [PATCH 038/167] add test for angular.d.ts --- angularjs/angular-tests.ts | 250 +++++++++++++++++++++++++++++++++++++ angularjs/angular.d.ts | 6 +- 2 files changed, 253 insertions(+), 3 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 8d86949d2..7f1e6edf9 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -271,3 +271,253 @@ test_IAttributes({ }, $attr: {} }); + +// test from https://docs.angularjs.org/guide/directive +angular.module('docsSimpleDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); + +angular.module('docsTemplateUrlDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsRestrictDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsScopeProblemExample', []) + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsIsolateScopeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); + +angular.module('docsIsolationExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); + +angular.module('docsTimeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + + return { + link: function(scope: any, element: any, attrs: any) { + var format: any, + timeoutId: any; + + function updateTime() { + element.text(dateFilter(new Date(), format)); + } + + scope.$watch(attrs.myCurrentTime, function (value: any) { + format = value; + updateTime(); + }); + + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); + + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); + +angular.module('docsTransclusionDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); + +angular.module('docsTransclusionExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: any, element: any) { + scope.name = 'Jeff'; + } + }; + }); + +angular.module('docsIsoFnBindExample', []) + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); + +angular.module('dragModule', []) + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; + + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); + + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); + + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } + + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); + +angular.module('docsTabsExample', []) + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: any) { + var panes: any = $scope.panes = []; + + $scope.select = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; + + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope.select(pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope, element, attrs, tabsCtrl) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index ca8751b8e..42d94ee8a 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1001,9 +1001,9 @@ declare module ng { link?: (scope: IScope, instanceElement: IAugmentedJQuery, - instanceAttributes: IAttributes, - controller: any, - transclude: ITranscludeFunction + instanceAttributes?: IAttributes, + controller?: any, + transclude?: ITranscludeFunction ) => void; name?: string; priority?: number; From e911b3c06170ac7c68391f03f7ac884152f5fbc7 Mon Sep 17 00:00:00 2001 From: Steve Fenton Date: Fri, 25 Jul 2014 08:15:51 +0100 Subject: [PATCH 039/167] Added extensibility point for templates. This allows named templates to be added, for example: interface HandlebarsTemplates { specialListOfThings: HandlebarsTemplateDelegate; } So the strongly typed version can be used. var template = Handlebars.templates.specialListOfThings; --- handlebars/handlebars.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/handlebars/handlebars.d.ts b/handlebars/handlebars.d.ts index ee3098ec4..56cce331f 100644 --- a/handlebars/handlebars.d.ts +++ b/handlebars/handlebars.d.ts @@ -37,9 +37,13 @@ interface HandlebarsStatic extends HandlebarsCommon { compile(input: any, options?: any): HandlebarsTemplateDelegate; } -interface HandlebarsRuntimeStatic extends HandlebarsCommon { +interface HandlebarsTemplates { + [index: string]: HandlebarsTemplateDelegate; +} + +interface HandlebarsRuntimeStatic extends HandlebarsCommon { // Handlebars.templates is the default template namespace in precompiler. - templates: { (s: string): HandlebarsTemplateDelegate }[]; + templates: HandlebarsTemplates; } declare class SafeString { From ba945bd8667d300638a01812e17a1622f4c5e967 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Fri, 25 Jul 2014 14:23:17 +0200 Subject: [PATCH 040/167] Angular-hotkeys : Chaining when hotkeys is bound to a $scope object --- angular-hotkeys/angular-hotkeys-tests.ts | 9 +++++++++ angular-hotkeys/angular-hotkeys.d.ts | 8 +++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts index 66f9e6072..a065d4b21 100644 --- a/angular-hotkeys/angular-hotkeys-tests.ts +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -14,3 +14,12 @@ hotkeyProvider.toggleCheatSheet(); hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); +hotkeyProvider.bindTo(scope) + .add(hotkeyObj) + .add(hotkeyObj) + .add({ + combo: 'w', + description: 'blah blah', + callback: function() {} + }); + diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts index cc4a3680c..f209fbe08 100644 --- a/angular-hotkeys/angular-hotkeys.d.ts +++ b/angular-hotkeys/angular-hotkeys.d.ts @@ -17,7 +17,7 @@ declare module ng.hotkeys { add(hotkeyObj: ng.hotkeys.Hotkey): void; - bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProvider; + bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained; del(combo: string): void; @@ -26,6 +26,12 @@ declare module ng.hotkeys { toggleCheatSheet(): void; } + interface HotkeysProviderChained { + add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; + + add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; + } + interface Hotkey { combo: string; description?: string; From 1f96102ae331de0984cae539f321feb560965d8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Wrzeszcz?= Date: Fri, 25 Jul 2014 14:24:05 +0200 Subject: [PATCH 041/167] Added HashMap definition. --- CONTRIBUTORS.md | 1 + hashmap/hashmap-tests.ts | 24 ++++++++++++++ hashmap/hashmap.d.ts | 71 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 hashmap/hashmap-tests.ts create mode 100644 hashmap/hashmap.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ad46a5f5f..4cf7ab60d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -113,6 +113,7 @@ All definitions files include a header with the author and editors, so at some p * [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy)) * [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov)) * [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [HashMap](https://github.com/flesler/hashmap) (by [Rafał Wrzeszcz](https://wrzasq.pl)) * [HashSet](http://www.timdown.co.uk/jshashtable/jshashset.html) (by [Sergey Gerasimov](https://github.com/gerich-home)) * [Hashtable](http://www.timdown.co.uk/jshashtable/) (by [Sergey Gerasimov](https://github.com/gerich-home)) * [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ)) diff --git a/hashmap/hashmap-tests.ts b/hashmap/hashmap-tests.ts new file mode 100644 index 000000000..4c3d74ee0 --- /dev/null +++ b/hashmap/hashmap-tests.ts @@ -0,0 +1,24 @@ +/// + +var map : HashMap = new HashMap(); + +map.set("foo", 123); + +var value : number = map.get("foo"); + +map.has("foo"); + +map.remove("foo"); + +var keys : string[] = map.keys(); + +var values : number[] = map.values(); + +var count : number = map.count(); + +map.forEach(function(value : number, key : string) : void { + console.log(key); + console.log(value); +}); + +map.clear(); diff --git a/hashmap/hashmap.d.ts b/hashmap/hashmap.d.ts new file mode 100644 index 000000000..c9f858174 --- /dev/null +++ b/hashmap/hashmap.d.ts @@ -0,0 +1,71 @@ +// Type definitions for HashMap 1.1.0 +// Project: https://github.com/flesler/hashmap +// Definitions by: Rafał Wrzeszcz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class HashMap { + /** + * Return value from hashmap. + * + * @param key Key. + * @return Value stored under given key. + */ + get(key : KeyType) : ValueType; + + /** + * Store value in hashmap. + * + * @param key Key. + * @param value Value. + */ + set(key : KeyType, value : ValueType) : void; + + /** + * Checks if given key exists in hashmap. + * + * @param key Key. + * @return Whether given key exists in hashmap. + */ + has(key : KeyType) : boolean; + + /** + * Removes given key from hashmap. + * + * @param key Key. + */ + remove(key : KeyType) : void; + + /** + * Returns all contained keys. + * + * @return List of keys. + */ + keys() : KeyType[]; + + /** + * Returns all container values. + * + * @return List of values. + */ + values() : ValueType[]; + + /** + * Returns size of hashmap (number of entries). + * + * @return Number of entries in hashmap. + */ + count() : number; + + /** + * Clears hashmap. + */ + clear() : void; + + /** + * Iterates over hashmap. + * + * @param callback Function to be invoked for every hashmap entry. + */ + forEach(callback : (value : ValueType, key : KeyType) => void) : void; +} + From 74d8b10775d49c73275dd72296f51fd9ba7067b9 Mon Sep 17 00:00:00 2001 From: Xiaohan Zhang Date: Fri, 25 Jul 2014 17:38:54 -0700 Subject: [PATCH 042/167] Add definitions for fromTextArea methods --- codemirror/codemirror.d.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 316284a78..af4b32046 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -9,7 +9,7 @@ declare function CodeMirror(callback: (host: HTMLElement) => void , options?: Co declare module CodeMirror { export var Pass: any; - function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.Editor; + function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea; var version: string; @@ -374,6 +374,18 @@ declare module CodeMirror { on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; } + + interface EditorFromTextArea extends Editor { + + /** Copy the content of the editor into the textarea. */ + save(): void; + + /** Remove the editor, and restore the original textarea (with the editor's current content). */ + toTextArea(): void; + + /** Returns the textarea that the instance was based on. */ + getTextArea(): HTMLTextAreaElement; + } class Doc { constructor (text: string, mode?: any, firstLineNumber?: number); From bfeb4664189633ede61cc28768fc388a84fca90c Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sat, 26 Jul 2014 11:35:54 +1000 Subject: [PATCH 043/167] Update angular-mocks.d.ts allow ```ts angular.mock.module("myApp", function($provide) { $provide.value("myService", { ... }); }) ``` Also signature is consistent with the global in the same file: ```ts declare var module: (...modules: any[]) => any; ``` --- angularjs/angular-mocks.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 6db753e1f..2591c006e 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -33,9 +33,7 @@ declare module ng { inject(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works // see http://docs.angularjs.org/api/angular.mock.module - module(...modules: string[]): any; - module(...modules: Function[]): any; - module(modules: Object): any; + module(...modules: any[]): any; // see http://docs.angularjs.org/api/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; From abfde2a3003f1a2687f67d6bb0266553b672cf66 Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sat, 26 Jul 2014 11:51:54 +1000 Subject: [PATCH 044/167] Update angular.d.ts remove unnecessary restriction on directive's `link` callback to accept optional parameters --- angularjs/angular.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 42d94ee8a..ca8751b8e 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1001,9 +1001,9 @@ declare module ng { link?: (scope: IScope, instanceElement: IAugmentedJQuery, - instanceAttributes?: IAttributes, - controller?: any, - transclude?: ITranscludeFunction + instanceAttributes: IAttributes, + controller: any, + transclude: ITranscludeFunction ) => void; name?: string; priority?: number; From f8cfab178847551b2a023f133ad10f2b9fca8c71 Mon Sep 17 00:00:00 2001 From: damianog Date: Sat, 26 Jul 2014 14:33:29 +0200 Subject: [PATCH 045/167] Update swig.d.ts Added function renderFile --- swig/swig.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index c8317ac5c..db2353375 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -9,6 +9,7 @@ declare module "swig" { export function init(options: Options): void; export function compileFile(filepath: string): any; export function compile(source: string, options?: Options): any; + export function renderFile(pathName: string, locals: any, cb: (err: any, output: string) => void): string; export interface Options { allowErrors?: boolean; From 1cdae538ab7919cbe3392f37a6d4876491d5d8b7 Mon Sep 17 00:00:00 2001 From: Douglas Eichelberger Date: Fri, 25 Jul 2014 11:40:02 -0700 Subject: [PATCH 046/167] Create ion.rangeSlider.d.ts --- CONTRIBUTORS.md | 1 + ion.rangeSlider/ion.rangeSlider-tests.ts | 38 ++++++++++++++++++ ion.rangeSlider/ion.rangeSlider.d.ts | 51 ++++++++++++++++++++++++ 3 files changed, 90 insertions(+) create mode 100644 ion.rangeSlider/ion.rangeSlider-tests.ts create mode 100644 ion.rangeSlider/ion.rangeSlider.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4cf7ab60d..1eb31acbb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -128,6 +128,7 @@ All definitions files include a header with the author and editors, so at some p * [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [interact.js](http://github.com/taye/interact.js) (by [Douglas Eichelberger](https://github.com/dduugg)) +* [Ion.RangeSlider](https://github.com/IonDen/ion.rangeSlider) (by [Douglas Eichelberger](https://github.com/dduugg)) * [Ionic-Cordova](https://github.com/driftyco/) (by [Hendrik Maus](https://github.com/hendrikmaus)) * [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski)) * [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) diff --git a/ion.rangeSlider/ion.rangeSlider-tests.ts b/ion.rangeSlider/ion.rangeSlider-tests.ts new file mode 100644 index 000000000..6f1d25f0d --- /dev/null +++ b/ion.rangeSlider/ion.rangeSlider-tests.ts @@ -0,0 +1,38 @@ +/// +/// + +var sliderInputElement = $(''); +sliderInputElement.ionRangeSlider({ + min: 10, + max: 100, + from: 30, + to: 80, + type: "single", + step: 10, + prefix: "$", + postfix: ".00", + maxPostfix: "+", + hasGrid: true, + hideMinMax: true, + hideFromTo: true, + prettify: true, + disable: false, + values: ["a", "b", "c"], + onLoad: function (obj) { + console.log(obj); + }, + onChange: function (obj) { + console.log(obj); + }, + onFinish: function (obj) { + console.log(obj); + } +}); +sliderInputElement.ionRangeSlider("update", { + min: 20, + max: 90, + from: 40, + to: 70, + step: 5 +}); +sliderInputElement.ionRangeSlider("remove"); diff --git a/ion.rangeSlider/ion.rangeSlider.d.ts b/ion.rangeSlider/ion.rangeSlider.d.ts new file mode 100644 index 000000000..b60954b3b --- /dev/null +++ b/ion.rangeSlider/ion.rangeSlider.d.ts @@ -0,0 +1,51 @@ +// Type definitions for for Ion.RangeSlider 1.9.1 +// Project: https://github.com/IonDen/ion.rangeSlider/ +// Definitions by: Douglas Eichelberger +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// API documentation: http://ionden.com/a/plugins/ion.rangeSlider/en.html + +interface JQuery { + ionRangeSlider(): JQuery; + ionRangeSlider(options: IonRangeSliderOptions): JQuery; + ionRangeSlider(method: string): JQuery; + ionRangeSlider(method: string, options: IonRangeSliderOptions): JQuery; +} + +interface IonRangeSliderOptions { + disable?: boolean; + from?: number; + hasGrid?: boolean; + hideFromTo?: boolean; + hideMinMax?: boolean; + max?: number; + maxPostfix?: string; + min?: number; + onChange?: (obj: IonRangeSliderEvent) => void; + onFinish?: (obj: IonRangeSliderEvent) => void; + onLoad?: (obj: IonRangeSliderEvent) => void; + postfix?: string; + prefix?: string; + prettify?: boolean; + step?: number; + to?: number; + type?: string; + values?: any[]; +} + +interface IonRangeSliderEvent { + fromNumber: number; + fromPers: number; + fromValue?: any; + fromX: number; + fromX_pure?: number; + input: JQuery; + max: number; + min: number; + slider: JQuery; + toNumber: number; + toPers: number; + toValue?: number; + toX: number; + toX_pure?: number; +} From a9960f762090ba1aa7e59ff8f8f78e1ed04aa51b Mon Sep 17 00:00:00 2001 From: Basarat Ali Syed Date: Sun, 27 Jul 2014 11:19:19 +1000 Subject: [PATCH 047/167] add api doc link --- swig/swig.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index c8317ac5c..6255815bd 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -5,6 +5,8 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/swig.d.ts +// API Documentation : http://paularmstrong.github.io/swig/docs/api/ + declare module "swig" { export function init(options: Options): void; export function compileFile(filepath: string): any; From 312632f1a4af24b7ae6ceacc0ad2cbab098d28d9 Mon Sep 17 00:00:00 2001 From: damianog Date: Sun, 27 Jul 2014 08:58:58 +0200 Subject: [PATCH 048/167] Update swig.d.ts --- swig/swig.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swig/swig.d.ts b/swig/swig.d.ts index db2353375..3d4e07df1 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -9,7 +9,7 @@ declare module "swig" { export function init(options: Options): void; export function compileFile(filepath: string): any; export function compile(source: string, options?: Options): any; - export function renderFile(pathName: string, locals: any, cb: (err: any, output: string) => void): string; + export function renderFile(pathName: string, locals?: any, cb?: (err: any, output: string) => void): string; export interface Options { allowErrors?: boolean; From c51cfd5670e04deb30d2e7866293dc210fb15b2f Mon Sep 17 00:00:00 2001 From: rsamec Date: Sun, 27 Jul 2014 09:05:21 +0200 Subject: [PATCH 049/167] node-form typescript definition file added --- CONTRIBUTORS.md | 1 + node-form/node-form-tests.ts | 31 ++ node-form/node-form.d.ts | 681 +++++++++++++++++++++++++++++++++++ 3 files changed, 713 insertions(+) create mode 100644 node-form/node-form-tests.ts create mode 100644 node-form/node-form.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1eb31acbb..35e2980f7 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -251,6 +251,7 @@ All definitions files include a header with the author and editors, so at some p * [Node.js](http://nodejs.org/) (from TypeScript samples) * [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) * [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) +* [node-form] (https://github.com/rsamec/form) (by [Roman Samec] (https://github.com/rsamec)) * [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame)) * [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo)) * [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) diff --git a/node-form/node-form-tests.ts b/node-form/node-form-tests.ts new file mode 100644 index 000000000..776014b68 --- /dev/null +++ b/node-form/node-form-tests.ts @@ -0,0 +1,31 @@ +/// +/// +/// +/// + + +export interface IPerson{ + Checked:boolean; + FirstName:string; + LastName:string; + Email:string; +} + +//create custom composite validator +var personValidator = new Validation.AbstractValidator(); + +//create field validators +var required = new Validation.RequiredValidator(); +var email = new Validation.EmailValidator(); +var maxLength = new Validation.MaxLengthValidator(); +maxLength.MaxLength = 15; + + +personValidator.RuleFor("FirstName", required); +personValidator.RuleFor("FirstName", maxLength); + +personValidator.RuleFor("LastName", required); +personValidator.RuleFor("LastName", maxLength); + +personValidator.RuleFor("Email", required); +personValidator.RuleFor("Email", email); diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts new file mode 100644 index 000000000..b84236896 --- /dev/null +++ b/node-form/node-form.d.ts @@ -0,0 +1,681 @@ +// Type definitions for node-form v1.0.0 +// Project: https://github.com/rsamec/form +// Definitions by: Roman Samec +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// +declare module Validation { + /** + * It represents a propert y validator for atomic object. + */ + interface IPropertyValidator { + isAcceptable(s: any): boolean; + customMessage? (config: any, args: any): string; + tagName?: string; + } + /** + * It represents a property validator for simple string value. + */ + interface IStringValidator extends IPropertyValidator { + isAcceptable(s: string): boolean; + } + /** + * It represents an async property validator for atomic object. + */ + interface IAsyncPropertyValidator { + isAcceptable(s: any): Q.Promise; + customMessage? (config: any, args: any): string; + isAsync: boolean; + tagName?: string; + } + /** + * It represents an async property validator for simple string value. + */ + interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { + isAcceptable(s: string): Q.Promise; + } + /** + * It defines compare operators. + */ + enum CompareOperator { + LessThan = 0, + LessThanEqual = 1, + Equal = 2, + NotEqual = 3, + GreaterThanEqual = 4, + GreaterThan = 5, + } + class StringFce { + static format(s: string, args: any): string; + } + class NumberFce { + static GetNegDigits(value: string): number; + } + class LettersOnlyValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class ZipCodeValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class EmailValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class UrlValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class RequiredValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DateValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DateISOValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class NumberValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DigitValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class SignedDigitValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class MinLengthValidator implements IStringValidator { + public MinLength: number; + constructor(MinLength?: number); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class MaxLengthValidator implements IStringValidator { + public MaxLength: number; + constructor(MaxLength?: number); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class RangeLengthValidator implements IStringValidator { + public RangeLength: number[]; + constructor(RangeLength?: number[]); + public isAcceptable(s: string): boolean; + public MinLength : number; + public MaxLength : number; + public tagName: string; + } + class MinValidator implements IPropertyValidator { + public Min: number; + constructor(Min?: number); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class MaxValidator implements IPropertyValidator { + public Max: number; + constructor(Max?: number); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class RangeValidator implements IPropertyValidator { + public Range: number[]; + constructor(Range?: number[]); + public isAcceptable(s: any): boolean; + public Min : number; + public Max : number; + public tagName: string; + } + class StepValidator implements IPropertyValidator { + public Step: string; + constructor(Step?: string); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class PatternValidator implements IStringValidator { + public Pattern: string; + constructor(Pattern?: string); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class ContainsValidator implements IAsyncPropertyValidator { + public Options: Q.Promise; + constructor(Options: Q.Promise); + public isAcceptable(s: string): Q.Promise; + public isAsync: boolean; + public tagName: string; + } +} +declare module Validation { + /** + * basic error structure + */ + interface IError { + HasError: boolean; + ErrorMessage: string; + TranslateArgs?: IErrorTranslateArgs; + } + /** + * support for localization of error messages + */ + interface IErrorTranslateArgs { + TranslateId: string; + MessageArgs: any; + } + /** + * It defines conditional function. + */ + interface IOptional { + (): boolean; + } + /** + * It represents the validation result. + */ + interface IValidationFailure extends IError { + IsAsync: boolean; + Error: IError; + } + /** + * This class provides unit of information about error. + * Implements composite design pattern to enable nesting of error information. + */ + interface IValidationResult { + /** + * The name of error collection. + */ + Name: string; + /** + * Add error information to child collection of errors. + * @param validationResult - error information to be added. + */ + Add(validationResult: IValidationResult): void; + /** + * Remove error information from child collection of errors. + * @param index - index of error information to be removed. + */ + Remove(index: number): void; + /** + * Return collections of child errors information. + */ + Children: IValidationResult[]; + /** + * Return true if there is any error. + */ + HasErrors: boolean; + /** + * Return true if there is any error and hasw dirty state. + */ + HasErrorsDirty: boolean; + /** + * Return error message, if there is no error, return empty string. + */ + ErrorMessage: string; + /** + * Return number of errors. + */ + ErrorCount: number; + /** + * It enables to have errors optional. + */ + Optional?: IOptional; + /** + * It enables support for localization of error messages. + */ + TranslateArgs?: IErrorTranslateArgs[]; + } + /** + * + * @ngdoc object + * @name Error + * @module Validation + * + * + * @description + * It represents basic error structure. + */ + class Error implements IError { + public HasError: boolean; + public ErrorMessage: string; + constructor(); + } + /** + * + * @ngdoc object + * @name ValidationFailure + * @module Validation + * + * + * @description + * It represents validation failure. + */ + class ValidationFailure implements IError { + public Error: IError; + public IsAsync: boolean; + constructor(Error: IError, IsAsync: boolean); + public HasError : boolean; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs; + } + /** + * + * @ngdoc object + * @name ValidationResult + * @module Validation + * + * + * @description + * It represents simple abstract error object. + */ + class ValidationResult implements IValidationResult { + public Name: string; + constructor(Name: string); + public IsDirty: boolean; + public Children : IValidationResult[]; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public Optional: IOptional; + public TranslateArgs: IErrorTranslateArgs[]; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + } + /** + * + * @ngdoc object + * @name CompositeValidationResult + * @module Validation + * + * + * @description + * It represents composite error object. + */ + class CompositeValidationResult implements IValidationResult { + public Name: string; + public Children: IValidationResult[]; + constructor(Name: string); + public Optional: IOptional; + public AddFirst(error: IValidationResult): void; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + public LogErrors(headerMessage?: string): void; + public Errors : { + [name: string]: IValidationResult; + }; + private FlattenErros; + public SetDirty(): void; + public SetPristine(): void; + private SetDirtyEx(node, dirty); + private flattenErrors(node, errorCollection); + private traverse(node, indent); + } +} +declare module Validation { + /** + * @ngdoc module + * @name Validation + * + * + * @description + * # Validation (core module) + * The module itself contains the essential components for an validation engine to function. The table below + * lists a high level breakdown of each of the components (object, functions) available within this core module. + * + *
+ */ + /** + * It defines validation function. + */ + interface IValidate { + (args: IError): void; + } + /** + * It represents named validation function. + */ + interface IValidatorFce { + Name: string; + ValidationFce: IValidate; + } + /** + * This class represents custom validator. + */ + interface IValidator { + Validate(context: any): boolean; + Error: IError; + } + /** + * It represents abstract validator for type of . + */ + interface IAbstractValidator { + RuleFor(prop: string, validator: IPropertyValidator): any; + ValidationFor(prop: string, validator: IValidatorFce): any; + ValidatorFor(prop: string, validator: IAbstractValidator): any; + /** + * It creates new concrete validation rule and assigned data context to this rule. + * @param name of the rule + * @constructor + */ + CreateRule(name: string): IAbstractValidationRule; + CreateAbstractRule(name: string): IAbstractValidationRule; + CreateAbstractListRule(name: string): IAbstractValidationRule; + /** + * return true if this validation rule is intended for list of items, otherwise true + */ + ForList: boolean; + } + /** + * It represents concrete validation rule for type of . + */ + interface IAbstractValidationRule { + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + Validate(context: T): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + ValidateAsync(context: T): Q.Promise; + /** + * Performs validation and async validation using a validation context. + */ + ValidateAll(context: T): void; + /** + * Performs validation and async validation using a validation context for a passed field. + */ + ValidateField(context: T, propName: string): void; + /** + * Return validation results. + */ + ValidationResult: IValidationResult; + Rules: { + [name: string]: IPropertyValidationRule; + }; + Validators: { + [name: string]: IValidator; + }; + Children: { + [name: string]: AbstractValidationRule; + }; + } + /** + * It represents property validation rule for type of . + */ + interface IPropertyValidationRule { + /** + *The validators that are grouped under this rule. + */ + Validators: { + [name: string]: any; + }; + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + Validate(context: IValidationContext): IValidationFailure[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + ValidateAsync(context: IValidationContext): Q.Promise; + } + /** + * It represents a data context for validation rule. + */ + interface IValidationContext { + /** + * Return current value. + */ + Value: string; + /** + * Return property name for current data context. + */ + Key: string; + /** + * Data context for validation rule. + */ + Data: T; + } + /** + * + * @ngdoc object + * @name AbstractValidator + * @module Validation + * + * + * @description + * It enables to create custom validator for your own abstract object (class) and to assign validation rules to its properties. + * You can assigned these rules + * + * + property validation rules - use _RuleFor_ property + * + property async validation rules - use _RuleFor_ property + * + shared validation rules - use _ValidationFor_ property + * + custom object validator - use _ValidatorFor_ property - enables composition of child custom validators + */ + class AbstractValidator implements IAbstractValidator { + public Validators: { + [name: string]: IPropertyValidator[]; + }; + public AbstractValidators: { + [name: string]: IAbstractValidator; + }; + public ValidationFunctions: { + [name: string]: IValidatorFce[]; + }; + public RuleFor(prop: string, validator: IPropertyValidator): void; + public ValidationFor(prop: string, fce: IValidatorFce): void; + public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; + public CreateAbstractRule(name: string): AbstractValidationRule; + public CreateAbstractListRule(name: string): AbstractListValidationRule; + public CreateRule(name: string): AbstractValidationRule; + /** + * Return true if this validation rule is intended for list of items, otherwise true. + */ + public ForList: boolean; + } + /** + * + * @ngdoc object + * @name AbstractValidationRule + * @module Validation + * + * + * @description + * It represents concreate validator for custom object. It enables to assign validation rules to custom object properties. + */ + class AbstractValidationRule implements IAbstractValidationRule { + public Name: string; + public validator: AbstractValidator; + public ValidationResult: IValidationResult; + public Rules: { + [name: string]: IPropertyValidationRule; + }; + public Validators: { + [name: string]: IValidator; + }; + public Children: { + [name: string]: AbstractValidationRule; + }; + /** + * Return true if this validation rule is intended for list of items, otherwise true. + */ + public ForList: boolean; + constructor(Name: string, validator: AbstractValidator, forList?: boolean); + public addChildren(): void; + public SetOptional(fce: IOptional): void; + private createRuleFor(prop); + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: T): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: T): Q.Promise; + public ValidateAll(context: T): void; + public ValidateField(context: T, propName: string): void; + } + /** + * + * @ngdoc object + * @name AbstractListValidationRule + * @module Validation + * + * + * @description + * It represents an validator for custom object. It enables to assign rules to custom object properties. + */ + class AbstractListValidationRule extends AbstractValidationRule { + public Name: string; + public validator: AbstractValidator; + constructor(Name: string, validator: AbstractValidator); + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: any): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: any): Q.Promise; + private getValidationRule(i); + private getIndexedKey(i); + public NotifyListChanged(list: any[]): void; + } + /** + * + * @ngdoc object + * @name ValidationContext + * @module Validation + * + * + * @description + * It represents a data context for validation rule. + */ + class ValidationContext implements IValidationContext { + public Key: string; + public Data: T; + constructor(Key: string, Data: T); + public Value : any; + } + class MessageLocalization { + static customMsg: string; + static defaultMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static ValidationMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static GetValidationMessage(validator: any): string; + } + /** + * + * @ngdoc object + * @name PropertyValidationRule + * @module Validation + * + * + * @description + * It represents a property validation rule. The property has assigned collection of property validators. + */ + class PropertyValidationRule extends ValidationResult implements IPropertyValidationRule { + public Name: string; + public Validators: { + [name: string]: any; + }; + public ValidationFailures: { + [name: string]: IValidationFailure; + }; + constructor(Name: string, validatorsToAdd?: IPropertyValidator[]); + public AddValidator(validator: any): void; + public Errors : IError[]; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: IValidationContext): IValidationFailure[]; + public ValidateEx(value: any): IValidationFailure[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: IValidationContext): Q.Promise; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsyncEx(value: string): Q.Promise; + } + /** + * + * @ngdoc object + * @name Validator + * @module Validation + * + * + * @description + * It represents a custom validator. It enables to define your own shared validation rules + */ + class Validator extends ValidationResult implements IValidator { + public Name: string; + private ValidateFce; + public Error: IError; + constructor(Name: string, ValidateFce: IValidate); + public Optional: IOptional; + public Validate(context: any): boolean; + public HasError : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + } +} From 45f3f63865b75968ce1aade8d771aad94b849170 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Mon, 28 Jul 2014 04:10:48 +0900 Subject: [PATCH 050/167] Add chrome.sockets.* --- chrome/chrome-app.d.ts | 188 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 187 insertions(+), 1 deletion(-) diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index ad319394f..e82de28b2 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Adam Lay +// Definitions by: Adam Lay , MIZUNE Pine // Definitions: https://github.com/borisyankov/DefinitelyTyped //////////////////// @@ -93,3 +93,189 @@ declare module chrome.app.window { var onMinimized: WindowEvent; var onRestored: WindowEvent; } + + +//////////////////// +// Sockets +//////////////////// +declare module chrome.sockets.tcp { + interface CreateInfo { + socketId: number; + } + + interface SendInfo { + resultCode: number; + bytesSent?: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface ReceiveEventArgs { + socketId: number; + data: ArrayBuffer; + } + + interface ReceiveErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + bufferSize?: number; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + bufferSize?: number; + paused: boolean; + connected: boolean; + localAddress?: string; + localPort?: number; + peerAddress?: string; + peerPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback: () => void): void; + + export function setKeepAlive(socketId: number, + enable: boolean, callback: (result: number) => void): void; + export function setKeepAlive(socketId: number, + enable: boolean, delay: number, callback: (result: number) => void): void; + + export function setNoDelay(socketId: number, + peerAddress: string, peerPort: number, callback: (result: number) => void): void; + export function disconnect(socketId: number, callback?: () => void): void; + export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + export function getSockets(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + + var onReceive: Event; + var onReceiveError: Event; +} + +declare module chrome.sockets.udp { + interface CreateInfo { + socketId: number; + } + + interface SendInfo { + resultCode: number; + bytesSent?: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface ReceiveEventArgs { + socketId: number; + data: ArrayBuffer; + remoteAddress: string; + remotePort: number; + } + + interface ReceiveErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + bufferSize?: number; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + bufferSize?: number; + paused: boolean; + connected: boolean; + localAddress?: string; + localPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, + callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + export function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + export function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; + export function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; + export function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; + export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; + export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; + + var onReceive: Event; + var onReceiveError: Event; +} + +declare module chrome.sockets.tcpServer { + interface CreateInfo { + socketId: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface AcceptEventArgs { + socketId: number; + clientSocketId: number; + } + + interface AcceptErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + paused: boolean; + localAddress?: string; + localPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback: () => void): void; + + export function listen(socketId: number, address: string, + port: number, backlog: number, callback: (result: number) => void): void; + export function listen(socketId: number, address: string, + port: number, callback: (result: number) => void): void; + + export function disconnect(socketId: number, callback?: () => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + + var onAccept: Event; + var onAcceptError: Event; +} \ No newline at end of file From 9084225d447d22acdee8b0102274e92b8f4bbebf Mon Sep 17 00:00:00 2001 From: rsamec Date: Mon, 28 Jul 2014 08:36:08 +0200 Subject: [PATCH 051/167] explicitly define node-form module with export = Validation --- node-form/node-form.d.ts | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts index b84236896..8c9bc73a8 100644 --- a/node-form/node-form.d.ts +++ b/node-form/node-form.d.ts @@ -1,14 +1,9 @@ -// Type definitions for node-form v1.0.0 -// Project: https://github.com/rsamec/form -// Definitions by: Roman Samec -// Definitions: https://github.com/borisyankov/DefinitelyTyped - /// /// /// declare module Validation { /** - * It represents a propert y validator for atomic object. + * It represents a property validator for atomic object. */ interface IPropertyValidator { isAcceptable(s: any): boolean; @@ -163,11 +158,18 @@ declare module Validation { TranslateArgs?: IErrorTranslateArgs; } /** + * Custom message functions. + */ + interface IErrorCustomMessage { + (config: any, args: any): string; + } + /** * support for localization of error messages */ interface IErrorTranslateArgs { TranslateId: string; MessageArgs: any; + CustomMessage?: IErrorCustomMessage; } /** * It defines conditional function. @@ -636,7 +638,9 @@ declare module Validation { }; constructor(Name: string, validatorsToAdd?: IPropertyValidator[]); public AddValidator(validator: any): void; - public Errors : IError[]; + public Errors : { + [name: string]: IValidationFailure; + }; public HasErrors : boolean; public ErrorCount : number; public ErrorMessage : string; @@ -669,13 +673,22 @@ declare module Validation { public Name: string; private ValidateFce; public Error: IError; + public ValidationFailures: { + [name: string]: IValidationFailure; + }; constructor(Name: string, ValidateFce: IValidate); public Optional: IOptional; public Validate(context: any): boolean; public HasError : boolean; + public Errors : { + [name: string]: IValidationFailure; + }; public HasErrors : boolean; public ErrorCount : number; public ErrorMessage : string; public TranslateArgs : IErrorTranslateArgs[]; } } +declare module "node-form" { + export = Validation ; +} \ No newline at end of file From 76781c4c859386006983e34c1046c43f143cb901 Mon Sep 17 00:00:00 2001 From: rsamec Date: Mon, 28 Jul 2014 08:47:12 +0200 Subject: [PATCH 052/167] explicitly define node-form module with export = Validation --- node-form/node-form.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts index 8c9bc73a8..96fab7001 100644 --- a/node-form/node-form.d.ts +++ b/node-form/node-form.d.ts @@ -2,12 +2,18 @@ /// /// declare module Validation { + /** + * Custom message functions. + */ + interface IErrorCustomMessage { + (config: any, args: any): string; + } /** * It represents a property validator for atomic object. */ interface IPropertyValidator { isAcceptable(s: any): boolean; - customMessage? (config: any, args: any): string; + customMessage?: IErrorCustomMessage; tagName?: string; } /** @@ -21,7 +27,7 @@ declare module Validation { */ interface IAsyncPropertyValidator { isAcceptable(s: any): Q.Promise; - customMessage? (config: any, args: any): string; + customMessage?: IErrorCustomMessage; isAsync: boolean; tagName?: string; } @@ -158,12 +164,6 @@ declare module Validation { TranslateArgs?: IErrorTranslateArgs; } /** - * Custom message functions. - */ - interface IErrorCustomMessage { - (config: any, args: any): string; - } - /** * support for localization of error messages */ interface IErrorTranslateArgs { @@ -690,5 +690,5 @@ declare module Validation { } } declare module "node-form" { - export = Validation ; +export = Validation ; } \ No newline at end of file From c320d0fac2fad31e762ff9931cd292928307a010 Mon Sep 17 00:00:00 2001 From: rsamec Date: Mon, 28 Jul 2014 09:25:35 +0200 Subject: [PATCH 053/167] explicitly define node-form module with export = Validation --- node-form/node-form.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts index 96fab7001..d75e313cd 100644 --- a/node-form/node-form.d.ts +++ b/node-form/node-form.d.ts @@ -1,3 +1,8 @@ +// Type definitions for node-form v1.0.6 +// Project: https://github.com/rsamec/form +// Definitions by: Roman Samec +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// /// /// From 4bd26e0a11d78732670f081984dfe2ebcc0f9b35 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Mon, 28 Jul 2014 23:17:35 +0900 Subject: [PATCH 054/167] Fix bug --- chrome/chrome-app.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index e82de28b2..830b26e4f 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -145,14 +145,15 @@ declare module chrome.sockets.tcp { export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; - export function setPaused(socketId: number, paused: boolean, callback: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; export function setKeepAlive(socketId: number, enable: boolean, callback: (result: number) => void): void; export function setKeepAlive(socketId: number, enable: boolean, delay: number, callback: (result: number) => void): void; - export function setNoDelay(socketId: number, + export function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; + export function connect(socketId: number, peerAddress: string, peerPort: number, callback: (result: number) => void): void; export function disconnect(socketId: number, callback?: () => void): void; export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; @@ -202,7 +203,6 @@ declare module chrome.sockets.udp { name?: string; bufferSize?: number; paused: boolean; - connected: boolean; localAddress?: string; localPort?: number; } @@ -265,7 +265,7 @@ declare module chrome.sockets.tcpServer { export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; - export function setPaused(socketId: number, paused: boolean, callback: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; export function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void; From f4dbe8f1e780cd583c038879b18ae9dcb442573c Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Mon, 28 Jul 2014 23:17:55 +0900 Subject: [PATCH 055/167] Add tests --- chrome/chrome-app-tests.ts | 251 ++++++++++++++++++++++++++++++++++++- 1 file changed, 250 insertions(+), 1 deletion(-) diff --git a/chrome/chrome-app-tests.ts b/chrome/chrome-app-tests.ts index 0ae0ae2af..12dc7b97d 100644 --- a/chrome/chrome-app-tests.ts +++ b/chrome/chrome-app-tests.ts @@ -24,4 +24,253 @@ chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchDa chrome.app.runtime.onRestarted.addListener(function () { return; }); // Get Current Window -var currentWindow: cwindow.AppWindow = chrome.app.window.current(); \ No newline at end of file +var currentWindow: cwindow.AppWindow = chrome.app.window.current(); + +// Sockets +// https://developer.chrome.com/apps/sockets_tcp +function test_socketsTcp(): void { + var socketId: number; + var properties: chrome.sockets.tcp.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcp.update(socketId, properties); + chrome.sockets.tcp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcp.setPaused(socketId, true); + chrome.sockets.tcp.setPaused(socketId, true, () => { }); + + // setKeepAlive + chrome.sockets.tcp.setKeepAlive(socketId, true, (result: number) => { }); + chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result: number) => { }); + + // setNoDelay + chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { }); + + // connect + chrome.sockets.tcp.connect(socketId, "192.168.0.1", 8080, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // send + chrome.sockets.tcp.send(socketId, buffer, (info: chrome.sockets.tcp.SendInfo) => { }); + + // close + chrome.sockets.tcp.close(socketId); + chrome.sockets.tcp.close(socketId, () => { }); + + // getInfo + chrome.sockets.tcp.getInfo(socketId, (info: chrome.sockets.tcp.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); +} + +function test_socketsTcpEvents(): void { + chrome.sockets.tcp.onReceive.addListener((info: chrome.sockets.tcp.ReceiveEventArgs) => { }); + chrome.sockets.tcp.onReceiveError.addListener((info: chrome.sockets.tcp.ReceiveErrorEventArgs) => { }); +} + +function testSocketsTcpTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcp.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test", + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcp.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true, + connected: false + }; + + socketInfo.name = "test"; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; + socketInfo.peerAddress = "192.168.0.3"; + socketInfo.peerPort = 1000; +} + +// https://developer.chrome.com/apps/sockets_udp +function test_socketsUdp(): void { + var socketId: number; + var properties: chrome.sockets.udp.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.udp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.udp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.udp.update(socketId, properties); + chrome.sockets.udp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.udp.setPaused(socketId, true); + chrome.sockets.udp.setPaused(socketId, true, () => { }); + + // bind + chrome.sockets.udp.bind(socketId, "0.0.0.0", 8080, (result: number) => { }); + + // send + chrome.sockets.udp.send(socketId, buffer, "172.21.0.1", 10080, (info: chrome.sockets.udp.SendInfo) => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); + + // getSockets + chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { }); + + // joinGroup + chrome.sockets.udp.joinGroup(socketId, "224.0.0.1", (result: number) => { }); + + // leaveGroup + chrome.sockets.udp.leaveGroup(socketId, "224.0.0.1", (result: number) => { }); + + // setMulticastTimeToLive + chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { }); + + // setMulticastLoopbackMode + chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result: number) => { }); + + // getJoinedGroups + chrome.sockets.udp.getJoinedGroups(socketId, (groups: string[]) => { }); +} + +function test_socketsUdpEvents(): void { + chrome.sockets.udp.onReceive.addListener((info: chrome.sockets.udp.ReceiveEventArgs) => { }); + chrome.sockets.udp.onReceiveError.addListener((info: chrome.sockets.udp.ReceiveErrorEventArgs) => { }); +} + +function testSocketsUdpTypes(): void { + // SocketProperties + var properties: chrome.sockets.udp.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test", + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.udp.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = "test"; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; +} + +// https://developer.chrome.com/apps/sockets_tcpServer +function test_socketsTcpServer(): void { + var socketId: number; + var properties: chrome.sockets.tcpServer.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcpServer.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcpServer.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcpServer.update(socketId, properties); + chrome.sockets.tcpServer.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcpServer.setPaused(socketId, true); + chrome.sockets.tcpServer.setPaused(socketId, true, () => { }); + + // listen + chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, (result: number) => { }); + chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, 128, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); +} + +function test_socketsTcpServerEvents(): void { + chrome.sockets.tcpServer.onAccept.addListener((info: chrome.sockets.tcpServer.AcceptEventArgs) => { }); + chrome.sockets.tcpServer.onAcceptError.addListener((info: chrome.sockets.tcpServer.AcceptErrorEventArgs) => { }); +} + +function testSocketsTcpServerTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcpServer.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test" + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcpServer.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = "test"; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; +} From 61144d85fd840981dee0221ac875008ee9eb5633 Mon Sep 17 00:00:00 2001 From: Daniel Mane Date: Mon, 28 Jul 2014 13:41:43 -0700 Subject: [PATCH 056/167] Rename "QuantitiveScale" to "QuantitativeScale" for consistency with d3's API docs and common usage of the english language. Close #2573 --- d3/d3.d.ts | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 598cd9f34..0354bc264 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -749,7 +749,7 @@ declare module D3 { insert: (name: string, before: string) => Selection; remove: () => Selection; empty: () => boolean; - + data: { (values: (data: any, index?: number) => any[], key?: (data: any, index?: number) => any): UpdateSelection; (values: any[], key?: (data: any, index?: number) => any): UpdateSelection; @@ -2508,7 +2508,7 @@ declare module D3 { copy(): Scale; } - export interface QuantitiveScale extends Scale { + export interface QuantitativeScale extends Scale { /** * Get the range value corresponding to a given domain value. * @@ -2530,7 +2530,7 @@ declare module D3 { * * @param value The input domain */ - (values: any[]): QuantitiveScale; + (values: any[]): QuantitativeScale; /** * Get the scale's input domain. */ @@ -2545,7 +2545,7 @@ declare module D3 { * * @param value The output range. */ - (values: any[]): QuantitiveScale; + (values: any[]): QuantitativeScale; /** * Get the scale's output range. */ @@ -2556,26 +2556,26 @@ declare module D3 { * * @param value The output range. */ - rangeRound: (values: any[]) => QuantitiveScale; + rangeRound: (values: any[]) => QuantitativeScale; /** * get or set the scale's output interpolator. */ interpolate: { (): D3.Transition.Interpolate; - (factory: D3.Transition.Interpolate): QuantitiveScale; + (factory: D3.Transition.Interpolate): QuantitativeScale; }; /** * enable or disable clamping of the output range. * * @param clamp Enable or disable */ - clamp(clamp: boolean): QuantitiveScale; + clamp(clamp: boolean): QuantitativeScale; /** * extend the scale domain to nice round numbers. - * + * * @param count Optional number of ticks to exactly fit the domain */ - nice(count?: number): QuantitiveScale; + nice(count?: number): QuantitativeScale; /** * get representative values from the input domain. * @@ -2591,10 +2591,10 @@ declare module D3 { /** * create a new scale from an existing scale.. */ - copy(): QuantitiveScale; + copy(): QuantitativeScale; } - export interface LinearScale extends QuantitiveScale { + export interface LinearScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2630,7 +2630,7 @@ declare module D3 { tickFormat(count: number): (n: number) => string; } - export interface SqrtScale extends QuantitiveScale { + export interface SqrtScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2639,7 +2639,7 @@ declare module D3 { (value: number): number; } - export interface PowScale extends QuantitiveScale { + export interface PowScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2648,7 +2648,7 @@ declare module D3 { (value: number): number; } - export interface LogScale extends QuantitiveScale { + export interface LogScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -3417,7 +3417,7 @@ declare module D3 { * * @param constant The new constant value. */ - (constant: number): Voronoi; + (constant: number): Voronoi; } clipExtent: { /** From 2d73f7313823d22ad7434872110c207eb58bda6c Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Mon, 28 Jul 2014 23:22:10 +0200 Subject: [PATCH 057/167] Add getVideoData() + interfaces --- youtube/youtube.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/youtube/youtube.d.ts b/youtube/youtube.d.ts index 3f21dcb86..44e98dd84 100644 --- a/youtube/youtube.d.ts +++ b/youtube/youtube.d.ts @@ -71,6 +71,13 @@ declare module YT { suggestedQuality?: string; } + export interface VideoData + { + video_id: string; + author: string; + title: string; + } + export class Player { // Constructor constructor(id: string, playerOptions: PlayerOptions); @@ -132,6 +139,7 @@ declare module YT { getDuration(): number; getVideoUrl(): string; getVideoEmbedCode(): string; + getVideoData(): VideoData; // Playlist getPlaylist(): any[]; From 7f47a884ea46c73ca44078e960aefc8b3f4fe9a1 Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Mon, 28 Jul 2014 23:22:29 +0200 Subject: [PATCH 058/167] Remove trailing spaces from empty lines --- youtube/youtube.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/youtube/youtube.d.ts b/youtube/youtube.d.ts index 44e98dd84..cfdba0efb 100644 --- a/youtube/youtube.d.ts +++ b/youtube/youtube.d.ts @@ -95,7 +95,7 @@ declare module YT { // Properties size; - + // Playing playVideo(): void; pauseVideo(): void; @@ -122,7 +122,7 @@ declare module YT { getPlaybackRate(): number; setPlaybackRate(suggestedRate:number): void; getAvailablePlaybackRates(): number[]; - + // Behavior setLoop(loopPlaylists: boolean): void; setShuffle(shufflePlaylist: boolean): void; @@ -144,7 +144,7 @@ declare module YT { // Playlist getPlaylist(): any[]; getPlaylistIndex(): number; - + // Event Listener addEventListener(event: string, listener: string): void; } From 22894235a23f59f738278398144d9fc57c002cd9 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 29 Jul 2014 11:08:28 +0100 Subject: [PATCH 059/167] Add genericised forEach and indexer for FormController --- angularjs/angular-tests.ts | 9 ++++++++ angularjs/angular.d.ts | 45 ++++++++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 7f1e6edf9..1502ac963 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -251,6 +251,15 @@ httpFoo.then((x) => { }); +function test_angular_forEach() { + var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; + var log = []; + angular.forEach(values, function (value, key) { + this.push(key + ': ' + value); + }, log); + //expect(log).toEqual(['name: misko', 'gender: male']); +} + // angular.element() tests var element = angular.element("div.myApp"); var scope: ng.IScope = element.scope(); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index ca8751b8e..c515b096f 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -46,7 +46,38 @@ declare module ng { element: IAugmentedJQueryStatic; equals(value1: any, value2: any): boolean; extend(destination: any, ...sources: any[]): any; + + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + fromJson(json: string): any; identity(arg?: any): any; injector(modules?: any[]): auto.IInjectorService; @@ -221,11 +252,17 @@ declare module ng { $attr: Object; } - /////////////////////////////////////////////////////////////////////////// - // FormController - // see http://docs.angularjs.org/api/ng.directive:form.FormController - /////////////////////////////////////////////////////////////////////////// + /** + * form.FormController - type in module ng + * see https://docs.angularjs.org/api/ng/type/form.FormController + */ interface IFormController { + + /** + * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 + */ + [name: string]: any; + $pristine: boolean; $dirty: boolean; $valid: boolean; From 68a3cb28753ddce6c9d9b1ea0f3dc5c5a9d3e42f Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 29 Jul 2014 11:21:28 +0100 Subject: [PATCH 060/167] Fix test --- angularjs/angular-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 1502ac963..d7f2a5bd5 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -254,7 +254,7 @@ httpFoo.then((x) => { function test_angular_forEach() { var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; var log = []; - angular.forEach(values, function (value, key) { + angular.forEach(values, function (value: string, key: string) { this.push(key + ': ' + value); }, log); //expect(log).toEqual(['name: misko', 'gender: male']); From 86d681f2890170baae4a47016fb3bf01dcdc41d0 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 29 Jul 2014 11:26:06 +0100 Subject: [PATCH 061/167] Fix test --- angularjs/angular-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index d7f2a5bd5..a1577856e 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -253,8 +253,8 @@ httpFoo.then((x) => { function test_angular_forEach() { var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; - var log = []; - angular.forEach(values, function (value: string, key: string) { + var log: string[] = []; + angular.forEach(values, function (value, key) { this.push(key + ': ' + value); }, log); //expect(log).toEqual(['name: misko', 'gender: male']); From 4394dc65a298c715dc6bbf3111dfae2aa8e4f840 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Tue, 29 Jul 2014 15:43:41 +0200 Subject: [PATCH 062/167] API update (version 0.7.3) --- leaflet/leaflet.d.ts | 145 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 141 insertions(+), 4 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 54f0fe4f0..ff5a42d05 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Leaflet.js 0.6.4 +// Type definitions for Leaflet.js 0.7.3 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Vladimir Zotov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -870,6 +870,13 @@ declare module L { * Default value: [0, 0]. */ padding?: Point; + + /** + * The maximum possible zoom to use. + * + * Default value: null + */ + maxZoom?: number; } } @@ -1128,6 +1135,11 @@ declare module L { * Mercator-based CRS. */ scale(zoom: number): number; + + /** + * Returns the size of the world in pixels for a particular zoom. + */ + getSize(zoom: number): Point; } } @@ -1277,6 +1289,11 @@ declare module L { * Sets the opacity of the overlay. */ setOpacity(opacity: number): ImageOverlay; + + /** + * Changes the URL of the image. + */ + setUrl(imageUrl: string): ImageOverlay; /** * Brings the layer to the top of all overlays. @@ -1802,6 +1819,17 @@ declare module L { popup: Popup; } } + +declare module L { + + export interface LeafletDragEndEvent extends LeafletEvent { + + /** + * The distance in pixels the draggable element was moved by. + */ + distance: number; + } +} declare module L { @@ -1960,7 +1988,7 @@ declare module L { * Sets the view of the map (geographical center and zoom) with the given * animation options. */ - setView(center: LatLng, zoom: number, options?: ZoomPanOptions): Map; + setView(center: LatLng, zoom?: number, options?: ZoomPanOptions): Map; /** * Sets the zoom of the map. @@ -2370,17 +2398,24 @@ declare module L { /** * Whether the map can be zoomed by using the mouse wheel. + * If passed 'center', it will zoom to the center of the view regardless of + * where the mouse was. * * Default value: true. */ scrollWheelZoom?: boolean; + scrollWheelZoom?: string; /** - * Whether the map can be zoomed in by double clicking on it. + * Whether the map can be zoomed in by double clicking on it and zoomed out + * by double clicking while holding shift. + * If passed 'center', double-click zoom will zoom to the center of the view + * regardless of where the mouse was. * * Default value: true. */ doubleClickZoom?: boolean; + doubleClickZoom?: string; /** * Whether the map can be zoomed to a rectangular area specified by dragging @@ -2529,6 +2564,14 @@ declare module L { * in all browsers that support CSS3 Transitions except Android. */ markerZoomAnimation?: boolean; + + /** + * Set it to false if you don't want the map to zoom beyond min/max zoom + * and then bounce back when pinch-zooming. + * + * Default value: true. + */ + bounceAtZoomLimits?: boolean; } } @@ -2652,6 +2695,11 @@ declare module L { * Opens the popup previously bound by the bindPopup method. */ openPopup(): Marker; + + /** + * Returns the popup previously bound by the bindPopup method. + */ + getPopup(): Popup; /** * Closes the bound popup of the marker if it's opened. @@ -2752,6 +2800,13 @@ declare module L { * Default value: ''. */ title?: string; + + /** + * Text for the alt attribute of the icon image (useful for accessibility). + * + * Default value: ''. + */ + alt?: string; /** * By default, marker images zIndex is set automatically based on its latitude. @@ -2814,6 +2869,11 @@ declare module L { */ getLatLngs(): LatLng[][]; + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolygon; + /** * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). */ @@ -2848,6 +2908,11 @@ declare module L { */ getLatLngs(): LatLng[][]; + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolyline; + /** * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). */ @@ -3076,6 +3141,20 @@ declare module L { * layers (e.g. Android 2). */ dashArray?: string; + + /** + * A string that defines shape to be used at the end of the stroke. + * + * Default: null. + */ + lineCap?: string; + + /** + * A string that defines shape to be used at the corners of the stroke. + * + * Default: null. + */ + lineJoin?: string; /** * If false, the vector will not emit mouse events and will act as a part of the @@ -3089,6 +3168,13 @@ declare module L { * Sets the pointer-events attribute on the path if SVG backend is used. */ pointerEvents?: boolean; + + /** + * Custom class name set on an element. + * + * Default value: ''. + */ + className?: string; } } @@ -3308,7 +3394,12 @@ declare module L { * Sets the geographical point where the popup will open. */ setLatLng(latlng: LatLng): Popup; - + + /** + * Returns the geographical point of popup. + */ + getLatLng(): LatLng; + /** * Sets the HTML content of the popup. */ @@ -3319,6 +3410,16 @@ declare module L { */ setContent(el: HTMLElement): Popup; + /** + * Returns the content of the popup. + */ + getContent(): string; + + /** + * Returns the content of the popup. + */ + getContent(): HTMLElement; + //////////// //////////// /** @@ -3333,6 +3434,12 @@ declare module L { * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; + + /** + * Updates the popup content, layout and position. Useful for updating the popup after + * something inside changed, e.g. image loaded. + */ + update(): Popup; } } @@ -3382,6 +3489,22 @@ declare module L { * Default value: new Point(0, 6). */ offset?: Point; + + /** + * The margin between the popup and the top left corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingTopLeft?: Point; + + /** + * The margin between the popup and the bottom right corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingBottomRight?: Point; /** * The margin between the popup and the edges of the map view after autopanning @@ -3695,6 +3818,15 @@ declare module L { * Default value: 18. */ maxZoom?: number; + + /** + * Maximum zoom number the tiles source has available. If it is specified, + * the tiles on all zoom levels higher than maxNativeZoom will be loaded from + * maxZoom level and auto-scaled. + * + * Default value: null. + */ + maxNativeZoom?: number; /** * Tile size (width and height in pixels, assuming tiles are square). @@ -3997,6 +4129,11 @@ declare module L { * An equivalent of passing animate to both zoom and pan options (see below). */ animate?: boolean; + + /** + * If true, it will delay moveend event so that it doesn't happen many times in a row. + */ + debounceMoveend?: boolean; } } From c11810a1cc5cbf7f8008b930bb2abef2d332fe7e Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Tue, 29 Jul 2014 15:55:02 +0200 Subject: [PATCH 063/167] L.Handler object --- leaflet/leaflet.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index ff5a42d05..42a7d4d82 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1243,6 +1243,10 @@ declare module L { */ enabled(): boolean; } + + export class Handler extends Class implements IHandler { + initialize(map: Map): void; + } } declare module L { From 4d014a48600d27b4626bab48816977cb7c850aa5 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Tue, 29 Jul 2014 16:17:55 +0200 Subject: [PATCH 064/167] Leaflet: L.Mixin.Events --- leaflet/leaflet.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 42a7d4d82..7f7b8dc9a 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1267,6 +1267,17 @@ declare module L { onRemove(map: Map): void; } } + +declare module L { + export var Mixin: any; + + module Mixin { + export interface LeafletMixinEvents implements IEventPowered { + } + + export var Events: LeafletMixinEvents; + } +} declare module L { From 133ace301b80361b41695133d883bcbaa2b6574e Mon Sep 17 00:00:00 2001 From: Frederik Wordenskjold Date: Tue, 29 Jul 2014 20:36:17 +0200 Subject: [PATCH 065/167] Made Wreqr.radio a module --- marionette/marionette.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 9ff239dc5..cee7b1845 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -57,9 +57,9 @@ declare module Backbone { // Backbone.Wreqr module Wreqr { - class radio { + module radio { - static channel(channelName: string): Channel; + function channel(channelName: string): Channel; } From 2bb123d25009b368292613891e62b1c1599105d8 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Tue, 29 Jul 2014 20:58:09 -0300 Subject: [PATCH 066/167] add object path --- object-path/object-path-tests.ts | 68 +++++++++ object-path/object-path.d.ts | 238 +++++++++++++++++++++++++++++++ 2 files changed, 306 insertions(+) create mode 100644 object-path/object-path-tests.ts create mode 100644 object-path/object-path.d.ts diff --git a/object-path/object-path-tests.ts b/object-path/object-path-tests.ts new file mode 100644 index 000000000..5984c78a8 --- /dev/null +++ b/object-path/object-path-tests.ts @@ -0,0 +1,68 @@ +/// + +var + object = { + one: 1, + two: { + three: 3, + four: ['4'] + } + }, + array: any[] = [], + Null:any = null; + +objectPath.del(array) === ['12']; +objectPath.del(object) === object; +objectPath.del(object) === object; + +objectPath.del() === void 0; +objectPath.del(object, ['1','2','3']); +objectPath.del(object, [1,2,3]); +objectPath.del(object, 1); +objectPath.del(object, 'one').one === 1; + +objectPath.coalesce(object, ['1','2']) === void 0; +objectPath.coalesce(object, ['1',['2','1']]) === void 0; +objectPath.coalesce(object, ['1',['2','1']], 1) === 1; +objectPath.coalesce(object, [1,1], 1) === 1; +objectPath.coalesce(object, >[1,[1,1]], 1) === 1; + +objectPath.ensureExists(object, '1.2', 2); +objectPath.ensureExists(object, 1, 2); +objectPath.ensureExists(object, [1,2], 2); +objectPath.ensureExists(object, ['1','2'], 2); +objectPath.ensureExists(object, ['1','2'], 2) === 3; +objectPath.ensureExists(object, ['1','2'], 2) === [[]]; + +objectPath.push(object, 1, 1,2,3,4); +objectPath.push(object, 1, 1,'2', 3, false); +objectPath.push(object, 'one.four', 1,'2', 3, false); +objectPath.push(object, ['one','two'], [1,'2', 3, false]); + +objectPath.get(array) === array; +objectPath.get(Null) === Null; +objectPath.get() === void 0; +objectPath.get(object, 'one') === 1; +objectPath.get(object, ['two','three']) === 3; +objectPath.get(object, ['three'], 3) === 3; +objectPath.get(object, 'three', 3) === 3; +objectPath.get(object, 0, 3) === 3; +objectPath.get(object, 0, '3') === '3'; +objectPath.get(object, 0, ['1','2']) === ['1','2']; +objectPath.get(object, 0) === 10; + +objectPath.set(object, '1.2', true); +objectPath.set(object, ['1','2'], true); +objectPath.set(object, [1, 2], true); +objectPath.set(object, '1.2', true, true); +objectPath.set(object, '1.2', true, false); +objectPath.set(object, '1.2', true, false) === ['string']; +objectPath.set(object, '1.2', true, false) === object; + +objectPath.insert(object, '1.2', 1); +objectPath.insert(object, ['1','2'], 1); +objectPath.insert(object, 1, 1); +objectPath.insert(object, [1,2], 1); +objectPath.insert(object, '1.2', 1, 2); +objectPath.insert(object, ['1.2'], 1, 6); + diff --git a/object-path/object-path.d.ts b/object-path/object-path.d.ts new file mode 100644 index 000000000..fe38f8702 --- /dev/null +++ b/object-path/object-path.d.ts @@ -0,0 +1,238 @@ +// Type definitions for objectPath v0.6.0 +// Project: https://github.com/mariocasciaro/object-path +// Definitions by: Paulo Cesar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var objectPath: objectPath.IObjectPathStatic; + +declare module objectPath { + + interface IStringArray { + [index: number]: string; + } + + interface INumberArray { + [index: number]: number; + } + + interface IObjectPathStatic { + /*======== Del =========*/ + + /** + * Deletes a member from object or array + * @param {object} object + * @param {string[]|string} path + * @return object + */ + del(object: T, path: IStringArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: INumberArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: number): T; + /** + * @see objectPath.del + */ + del(object: T, path: string): T; + /** + * @see objectPath.del + */ + del(object: T): T; + /** + * @see objectPath.del + */ + del():void; + + /*======== Get =========*/ + /** + * Get a path from an object + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} [defaultValue=undefined] + */ + get(object: T, path: string, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: IStringArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: number, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: INumberArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T): T; + /** + * @see objectPath.get + */ + get():void; + + /*======== Set =========*/ + /** + * Set a path to a value + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {boolean} [doNotReplace=false] + * @return Any existing value on the path if any + */ + set(object: T, path: string, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: number, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: IStringArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: INumberArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T): T; + /** + * @see objectPath.set + */ + set():void; + + /*======== Push =========*/ + /** + * Create (if path isn't an array) and push the value to it. Can push unlimited number of values + * @param {object} object + */ + push(object: T, path: INumberArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: IStringArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: number, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: string, ...args:any[]):void; + /** + * @see objectPath.push + */ + push():void; + + /*======== Coalesce =========*/ + /** + * Get the first non undefined property + * @param {object} object + * @param {string[]|string[][]|number[]|number[][]} paths + * @param {*} defaultValue + * @return {*} + */ + coalesce(object: T, paths: IStringArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: IStringArray[], defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray[], defaultValue?: any):TResult; + + /*======== Empty =========*/ + /** + * Empty a path. Arrays are set to length 0, objects have all elements deleted, strings + * are set to empty, numbers to 0, everything else is set to null + * @param {object} object + * @param {string|string[]|number[]} path + */ + empty(object: T, path: string):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: INumberArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: IStringArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: number):TResult; + /** + * @see objectPath.empty + */ + empty(object: T):T; + /** + * @see objectPath.empty + */ + empty():void; + + /*======== EnsureExists =========*/ + /** + * Set a value if it doesn't exist, do nothing if it does + * @param {object} object + * @param {string|string[]|number|number[]} path + */ + ensureExists(object: T, path: string, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: number, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: INumberArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: IStringArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T): T; + /** + * @see objectPath.ensureExists + */ + ensureExists():void; + + /*======== Insert =========*/ + /** + * Insert an item in an array path + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {number} [at=0] + */ + insert(object: T, path: string, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: INumberArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: IStringArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: number, value: any, at?: number):void; + } + +} + +declare module 'objectPath' { + export = objectPath; +} \ No newline at end of file From 70ff4da3eee5250de662c8faa3d5eb6399a48a09 Mon Sep 17 00:00:00 2001 From: Bo Miller Date: Tue, 29 Jul 2014 23:49:35 -0400 Subject: [PATCH 067/167] Underscore.js: Updated chained calls to first() so that they return a _ChainSingle instead of _Chain. This causes a future call to value() to return a single T rather than an array of T which matches underscore's behavior. --- underscore/underscore-tests.ts | 4 ++++ underscore/underscore.d.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index 11624abeb..8b638ee50 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -328,4 +328,8 @@ function chain_tests() { .flatten() .find(num => num % 2 == 0) .value(); + + var firstVal: number = _.chain([1, 2, 3]) + .first() + .value(); } diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 5b64aceb1..7d9c84f82 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -2620,7 +2620,7 @@ interface _Chain { * Wrapped type `any[]`. * @see _.first **/ - first(): _Chain; + first(): _ChainSingle; /** * Wrapped type `any[]`. From 49664879ddf34d597e8a032dba22cb6feae5e10b Mon Sep 17 00:00:00 2001 From: zaneli Date: Wed, 30 Jul 2014 12:12:40 +0900 Subject: [PATCH 068/167] Add definitions for fingerprintjs --- CONTRIBUTORS.md | 1 + fingerprintjs/fingerprint-tests.ts | 53 ++++++++++++++++ fingerprintjs/fingerprint.d.ts | 99 ++++++++++++++++++++++++++++++ 3 files changed, 153 insertions(+) create mode 100644 fingerprintjs/fingerprint-tests.ts create mode 100644 fingerprintjs/fingerprint.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 35e2980f7..38519a81a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -82,6 +82,7 @@ All definitions files include a header with the author and editors, so at some p * [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/)) * [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/)) * [Finch](https://github.com/stoodder/finchjs) (by [David Sichau](https://github.com/DavidSichau/)) +* [fingerprintjs](https://github.com/Valve/fingerprintjs) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov)) * [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone)) * [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame)) diff --git a/fingerprintjs/fingerprint-tests.ts b/fingerprintjs/fingerprint-tests.ts new file mode 100644 index 000000000..8b0789870 --- /dev/null +++ b/fingerprintjs/fingerprint-tests.ts @@ -0,0 +1,53 @@ +/// + +function test_no_option() { + var fingerprint = new Fingerprint().get(); +} + +function test_set_canvas_enabled() { + var fingerprint = new Fingerprint({canvas: true}).get(); +} + +function test_set_screen_resolution_enabled() { + var fingerprint = new Fingerprint({screen_resolution: true}).get(); +} + +function test_set_ie_activex_enabled() { + var fingerprint = new Fingerprint({ie_activex: true}).get(); +} + +function test_set_hasher_in_option() { + var my_hasher = (value: string, seed: number) => { return value.length % seed; }; + var fingerprint = new Fingerprint({hasher: my_hasher}).get(); + + var fingerprint = new Fingerprint({hasher: (value, seed) => { return value.length % seed; }}).get(); +} + +function test_set_hasher_in_constructor() { + var my_hasher = (value: string, seed: number) => { return value.length % seed; }; + var fingerprint = new Fingerprint(my_hasher).get(); + + var fingerprint = new Fingerprint((value, seed) => { return value.length % seed; }).get(); +} + +function test_call_methods() { + var f = new Fingerprint(); + f.murmurhash3_32_gc("abcde", 123); + if (f.hasLocalStorage()) { + alert("LocalStorage"); + } + if (f.hasSessionStorage()) { + alert("SessionStorage"); + } + if (f.isCanvasSupported()) { + alert("CanvasSupported"); + } + if (f.isIE()) { + alert("IE"); + } + f.getPluginsString(); + f.getRegularPluginsString(); + f.getIEPluginsString(); + f.getScreenResolution(); + f.getCanvasFingerprint(); +} diff --git a/fingerprintjs/fingerprint.d.ts b/fingerprintjs/fingerprint.d.ts new file mode 100644 index 000000000..f472b0489 --- /dev/null +++ b/fingerprintjs/fingerprint.d.ts @@ -0,0 +1,99 @@ +// Type definitions for fingerprintjs 0.5.4 +// Project: https://github.com/Valve/fingerprintjs +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module FingerprintJs { + + interface FingerprintStatic { + /** + * Create Fingerprint object. + */ + new(hasher: (key: string, seed: number) => number): Fingerprint; + new(option: FingerprintOption): Fingerprint; + new(): Fingerprint; + } + + interface Fingerprint { + /** + * Generate fingerprint number. + */ + get(): number; + + /** + * Generate fingerprint number using Murmur hashing. + * @param key ASCII only + * @param seed Positive integer only + */ + murmurhash3_32_gc(key: string, seed: number): number; + + /** + * Check whether or not the browser has local storage. + */ + hasLocalStorage(): boolean; + + /** + * Check whether or not the browser has session storage. + */ + hasSessionStorage(): boolean; + + /** + * Check whether or not the browser supports canvas. + */ + isCanvasSupported(): boolean; + + /** + * Check whether or not the browser is IE. + */ + isIE(): boolean; + + /** + * Get plugins string. + */ + getPluginsString(): string; + + /** + * Get plugins string from navigator plugins. + */ + getRegularPluginsString(): string; + + /** + * Get plugins string from ActiveXObject. + */ + getIEPluginsString(): string; + + /** + * Get screen height and width. + */ + getScreenResolution(): number[]; + + /** + * Get canvas data url string. + */ + getCanvasFingerprint(): string; + } + + interface FingerprintOption { + /** + * If you want to use canvas fingerprinting, set true. + */ + canvas?: boolean; + + /** + * If you want to use the screen resolution in calculating the fingerprint, set true. + */ + screen_resolution?: boolean; + + /** + * If you want to query the IE plugins info to further diversify the fingerprinting process, set true. + */ + ie_activex?: boolean; + + /** + * If you want to use custom hashing function, set function. + */ + hasher?: (key: string, seed: number) => number; + } +} + +declare var Fingerprint: FingerprintJs.FingerprintStatic; From 8cc523f0fa559172971834b74254688c95dd1d9f Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Wed, 30 Jul 2014 09:44:38 -0300 Subject: [PATCH 069/167] Update CONTRIBUTORS.md --- CONTRIBUTORS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 35e2980f7..b3acae253 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -251,7 +251,7 @@ All definitions files include a header with the author and editors, so at some p * [Node.js](http://nodejs.org/) (from TypeScript samples) * [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) * [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) -* [node-form] (https://github.com/rsamec/form) (by [Roman Samec] (https://github.com/rsamec)) +* [node-form](https://github.com/rsamec/form) (by [Roman Samec](https://github.com/rsamec)) * [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame)) * [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo)) * [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) @@ -260,6 +260,7 @@ All definitions files include a header with the author and editors, so at some p * [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker)) * [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) * [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) +* [object-path](https://github.com/mariocasciaro/object-path) (by [Paulo Cesar](https://github.com/pocesar/)) * [ocLazyLoad](https://github.com/ocombe/ocLazyLoad) (by [Roland Zwaga](https://github.com/rolandzwaga/)) * [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) @@ -293,7 +294,7 @@ All definitions files include a header with the author and editors, so at some p * [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) * [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov)) * [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) -* [rtree.js] (https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz)) +* [rtree.js](https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz)) * [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov)) * [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong)) From adec6babb59ef08a52e7ec69e995d63169137c33 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Wed, 30 Jul 2014 17:22:20 +0100 Subject: [PATCH 070/167] Added title to --- angularjs/angular.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index c515b096f..878f4f3cc 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -961,7 +961,9 @@ declare module ng { // RootScopeService // see http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// - interface IRootScopeService extends IScope {} + interface IRootScopeService extends IScope { + title: string; + } /////////////////////////////////////////////////////////////////////////// // SCEService From a664ce369bc2afb45a27206931843e8295a5ef57 Mon Sep 17 00:00:00 2001 From: Wayne Maurer Date: Wed, 30 Jul 2014 21:17:53 +0200 Subject: [PATCH 071/167] added static html() methods to cheerio --- cheerio/cheerio.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index df5058f20..af5f0172e 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/cheeriojs/cheerio // Definitions by: Bret Little // Definitions by: VILIC VANE +// Definitions by: Wayne Maurer // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Cheerio { @@ -190,6 +191,11 @@ interface CheerioStatic { root(): Cheerio; contains(container: CheerioElement, contained: CheerioElement): boolean; parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[]; + + html(options?: CheerioOptionsInterface): string; + html(selector: string, options?: CheerioOptionsInterface): string; + html(element: Cheerio, options?: CheerioOptionsInterface): string; + html(element: CheerioElement, options?: CheerioOptionsInterface): string; } interface CheerioElement { From 1b831404eebc5f7ab6f741aac08b9bd3f74b04c3 Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 31 Jul 2014 11:06:46 +0900 Subject: [PATCH 072/167] fix .travis.yml from https://github.com/travis-ci/travis-ci/issues/2591 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d138403cc..acfc5176f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - 0.10 + - "0.10" notifications: email: false From 500fc1022b92c5c856eb11d07054ebf9cc5c44bb Mon Sep 17 00:00:00 2001 From: allentc Date: Thu, 31 Jul 2014 01:12:24 -0600 Subject: [PATCH 073/167] Correct parameter optionality The last three parameters of ticker.addEventListener are optional. See: http://api.greensock.com/js/com/greensock/TweenMax.html#ticker --- greensock/greensock.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/greensock/greensock.d.ts b/greensock/greensock.d.ts index 4cf521e15..42fa6aa85 100644 --- a/greensock/greensock.d.ts +++ b/greensock/greensock.d.ts @@ -7,7 +7,7 @@ // Version 1.1 (TypeScript 0.9) interface IDispatcher { - addEventListener(type:string, callback:Function, scope:Object, useParam:boolean, priority:number):void; + addEventListener(type:string, callback:Function, scope?:Object, useParam?:boolean, priority?:number):void; removeEventListener(type:string, callback:Function):void; } From a4661ce23c4241f822f56acc5b4a7bbf56871a68 Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Thu, 31 Jul 2014 09:20:10 +0200 Subject: [PATCH 074/167] Added definition and tests for angular-bootstrap-lightbox. (https://github.com/compact/angular-bootstrap-lightbox) --- .../angular-bootstrap-lightbox-tests.ts | 35 +++++++++++++ .../angular-bootstrap-lightbox.d.ts | 49 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts create mode 100644 angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts new file mode 100644 index 000000000..21e9b2ce9 --- /dev/null +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts @@ -0,0 +1,35 @@ +/// + +var imageList:angular.bootstrap.lightbox.ILightboxImageInfo[] = []; +imageList.push({ + url: 'url1', + width: 100, + height: 100 +}); +imageList.push({ + url: 'url2', + width: 100, + height: 100, + thumbUrl: 'thumbUrl', + caption: 'caption' +}); + +var lightBox:angular.bootstrap.lightbox.ILightbox = {}; +lightBox.openModal(imageList, 0); + +var provider:angular.bootstrap.lightbox.ILightBoxProvider = {}; +provider.templateUrl = 'templateUrl'; +provider.calculateImageDimensionLimits = (dimensions:angular.bootstrap.lightbox.IImageDimensionParameter):angular.bootstrap.lightbox.IImageDimensionLimits=> { + return { + minWidth: 100, + minHeight: 100, + maxWidth: dimensions.windowWidth - 102, + maxHeight: dimensions.windowHeight - 136 + }; +}; +provider.calculateModalDimensions = (dimensions:angular.bootstrap.lightbox.IModalDimensionsParameter):angular.bootstrap.lightbox.IModalDimensions=> { + return { + width: Math.max(500, dimensions.imageDisplayWidth + 42), + height: Math.max(500, dimensions.imageDisplayHeight + 76) + }; + }; \ No newline at end of file diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts new file mode 100644 index 000000000..d8c831249 --- /dev/null +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts @@ -0,0 +1,49 @@ +/** + * Created by Roland on 7/31/2014. + */ +declare module angular.bootstrap.lightbox { + + export interface ILightboxImageInfo { + url: string; + width: number; + height: number; + thumbUrl?: string; + caption?: string; + } + + export interface IImageDimensionLimits { + minWidth?: number; + minHeight?: number; + maxWidth?: number; + maxHeight?: number; + } + + export interface IImageDimensionParameter { + windowWidth:number; + windowHeight:number; + imageWidth:number; + imageHeight:number; + } + + export interface IModalDimensionsParameter { + windowWidth:number; + windowHeight:number; + imageDisplayWidth:number; + imageDisplayHeight:number; + } + + export interface IModalDimensions { + width:number; + height:number; + } + + export interface ILightbox { + openModal(images:ILightboxImageInfo[], index:number):void; + } + + export interface ILightBoxProvider { + templateUrl:string; + calculateImageDimensionLimits:(dimensions:IImageDimensionParameter)=>IImageDimensionLimits; + calculateModalDimensions:(dimensions:IModalDimensionsParameter)=>IModalDimensions; + } +} \ No newline at end of file From cf1a372e77c46cc40c21c73276decc64bbbff3fe Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Thu, 31 Jul 2014 09:27:05 +0200 Subject: [PATCH 075/167] Update CONTRIBUTORS.md --- CONTRIBUTORS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 83d78bfd6..088a423eb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,7 +8,8 @@ All definitions files include a header with the author and editors, so at some p * [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei)) * [Add To Home Screen](http://cubiq.org/add-to-home-screen) (by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw)) * [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/)) -* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga) +* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga)) +* [AngularBootstrapLightbox](https://github.com/compact/angular-bootstrap-lightbox) (by [Roland Zwaga](https://github.com/rolandzwaga)) * [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft)) * [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) From 3ae57ef657a2006e409b8dc4931908e0e8f84859 Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 31 Jul 2014 18:45:02 +0900 Subject: [PATCH 076/167] fix SlickGrid declaration --- slickgrid/SlickGrid-tests.ts | 14 ++++++++++++-- slickgrid/SlickGrid-tests.ts.tscparams | 1 - slickgrid/SlickGrid.d.ts | 4 ++-- 3 files changed, 14 insertions(+), 5 deletions(-) delete mode 100644 slickgrid/SlickGrid-tests.ts.tscparams diff --git a/slickgrid/SlickGrid-tests.ts b/slickgrid/SlickGrid-tests.ts index 50db88b52..e267a8594 100644 --- a/slickgrid/SlickGrid-tests.ts +++ b/slickgrid/SlickGrid-tests.ts @@ -47,7 +47,7 @@ grid.getDataItem(14).title; grid.setData([{ title: "task", duration: "5 days", percentComplete: 5, start: "01/01/2013", finish: "12/12/2013", effortDriven: false }], true); -var ids = []; +var ids: string[] = []; for (i = 0; i < grid.getDataLength(); i++) { ids.push(grid.getDataItem(i).title); } @@ -82,7 +82,7 @@ class SingleCellSelectionModel extends Slick.SelectionModel(); var gridWithDataView = new Slick.Grid('#grid2', dataView, columns, options); dataView.getIdxById('foo') + 5; + +columns.forEach(column => { + if (column.editor !== Slick.Editors.Integer) { + return; + } +}); + +grid.onSort.subscribe((e, args) => { + var sortCol:string = args.sortCols[0].sortCol.field; +}); diff --git a/slickgrid/SlickGrid-tests.ts.tscparams b/slickgrid/SlickGrid-tests.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/slickgrid/SlickGrid-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index 90aa9cf13..d8a365d94 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -424,7 +424,7 @@ declare module Slick { /** * The editor for cell edits {TextEditor, IntegerEditor, DateEditor...} See slick.editors.js **/ - editor?: Editors.Editor; + editor?: any; // typeof Editors.Editor; /** * The property name in the data object to pull content from. (This is assumed to be on the root of the data object.) @@ -1333,7 +1333,7 @@ declare module Slick { // todo: merge with existing column definition export interface Column { - sortCol?: string; + sortCol?: Column; sortAsc?: boolean; } From f6f588b101906b5ac539bcbb7b3cd3ea07fc4432 Mon Sep 17 00:00:00 2001 From: Peter Kooijmans Date: Thu, 31 Jul 2014 12:29:26 +0200 Subject: [PATCH 077/167] Add loadZoneDataFromObject function. --- timezone-js/timezone-js.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/timezone-js/timezone-js.d.ts b/timezone-js/timezone-js.d.ts index ecf7d9e48..9aca2738e 100644 --- a/timezone-js/timezone-js.d.ts +++ b/timezone-js/timezone-js.d.ts @@ -75,6 +75,7 @@ declare module "timezone-js" { transport(opts: TimezoneJsOptions): any; init(opts?: TimezoneJsOptions): any; getAllZones(): string[]; + loadZoneDataFromObject(obj: Object): void; } export interface TimezoneJsOptions { From 761209a551bad41077686a39b03d77104f1248b3 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Thu, 31 Jul 2014 13:26:15 +0100 Subject: [PATCH 078/167] Pull title back off --- angularjs/angular.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 878f4f3cc..c515b096f 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -961,9 +961,7 @@ declare module ng { // RootScopeService // see http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// - interface IRootScopeService extends IScope { - title: string; - } + interface IRootScopeService extends IScope {} /////////////////////////////////////////////////////////////////////////// // SCEService From 9c8cef88118832b21b10add82ba566896c428b6c Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Thu, 31 Jul 2014 16:50:05 +0200 Subject: [PATCH 079/167] Added correct headers --- .../angular-bootstrap-lightbox.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts index d8c831249..299967bdd 100644 --- a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts @@ -1,6 +1,8 @@ -/** - * Created by Roland on 7/31/2014. - */ +// Type definitions for angular-bootstrap-lightbox +// Project: https://github.com/compact/angular-bootstrap-lightbox +// Definitions by: Roland Zwaga +// Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module angular.bootstrap.lightbox { export interface ILightboxImageInfo { From 7961ac184b54a1dfd28457121dbdcfc2531e832b Mon Sep 17 00:00:00 2001 From: Wayne Maurer Date: Thu, 31 Jul 2014 17:29:48 +0200 Subject: [PATCH 080/167] cheerio: fixed format of header as suggested by Bartvds - https://github.com/borisyankov/DefinitelyTyped/pull/2588 --- cheerio/cheerio.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index af5f0172e..cd0be3593 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -1,8 +1,6 @@ // Type definitions for Cheerio v0.17.0 // Project: https://github.com/cheeriojs/cheerio -// Definitions by: Bret Little -// Definitions by: VILIC VANE -// Definitions by: Wayne Maurer +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Cheerio { From d564ddbb2c4f6642331f615eaa41d0ef46e14d5d Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Fri, 1 Aug 2014 11:29:04 +0900 Subject: [PATCH 081/167] Add LastError interface --- chrome/chrome.d.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 796635c27..23ee0d916 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -843,8 +843,12 @@ declare module chrome.extension { type?: string; } + interface LastError { + message?: string; + } + var inIncognitoContext: boolean; - var lastError: Object; + var lastError: LastError; export function getBackgroundPage(): Window; export function getURL(path: string): string; @@ -1487,9 +1491,13 @@ declare module chrome.proxy { // Runtime //////////////////// declare module chrome.runtime { - var lastError: Object; + var lastError: LastError; var id: string; + interface LastError { + message?: string; + } + interface ConnectInfo { name?: string; } From 88e093242ad84927f986a92aa287020566ebbdb2 Mon Sep 17 00:00:00 2001 From: rsamec Date: Fri, 1 Aug 2014 06:49:29 +0200 Subject: [PATCH 082/167] IValidator - async support --- node-form/node-form.d.ts | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts index d75e313cd..3e56ddc4a 100644 --- a/node-form/node-form.d.ts +++ b/node-form/node-form.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-form v1.0.6 +// Type definitions for node-form v1.0.13 // Project: https://github.com/rsamec/form // Definitions by: Roman Samec // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -349,17 +349,25 @@ declare module Validation { (args: IError): void; } /** + * It defines async validation function. + */ + interface IAsyncValidate { + (args: IError): Q.Promise; + } + /** * It represents named validation function. */ interface IValidatorFce { Name: string; - ValidationFce: IValidate; + ValidationFce?: IValidate; + AsyncValidationFce?: IAsyncValidate; } /** * This class represents custom validator. */ interface IValidator { - Validate(context: any): boolean; + Validate(context: any): IValidationFailure; + ValidateAsync(context: any): Q.Promise; Error: IError; } /** @@ -677,13 +685,15 @@ declare module Validation { class Validator extends ValidationResult implements IValidator { public Name: string; private ValidateFce; + private AsyncValidationFce; public Error: IError; public ValidationFailures: { [name: string]: IValidationFailure; }; - constructor(Name: string, ValidateFce: IValidate); + constructor(Name: string, ValidateFce?: IValidate, AsyncValidationFce?: IAsyncValidate); public Optional: IOptional; - public Validate(context: any): boolean; + public Validate(context: any): IValidationFailure; + public ValidateAsync(context: any): Q.Promise; public HasError : boolean; public Errors : { [name: string]: IValidationFailure; @@ -694,6 +704,7 @@ declare module Validation { public TranslateArgs : IErrorTranslateArgs[]; } } -declare module "node-form" { -export = Validation ; + +declare module "node-form"{ + export = Validation; } \ No newline at end of file From 52318243888c4aa02b3c0b5e68631577728ffcf8 Mon Sep 17 00:00:00 2001 From: vvakame Date: Fri, 1 Aug 2014 17:26:03 +0900 Subject: [PATCH 083/167] js-yaml support on browser --- js-yaml/js-yaml.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/js-yaml/js-yaml.d.ts b/js-yaml/js-yaml.d.ts index 0607b4891..0de5a8f6b 100644 --- a/js-yaml/js-yaml.d.ts +++ b/js-yaml/js-yaml.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module 'js-yaml' { +declare module jsyaml { export function safeLoad(str: string, opts?: LoadOptions): any; export function load(str: string, opts?: LoadOptions): any; @@ -46,3 +46,7 @@ declare module 'js-yaml' { // all supported YAML types. export var DEFAULT_FULL_SCHEMA: any; } + +declare module 'js-yaml' { + export = jsyaml; +} From 4c104285874869143ce48c05f00605310a296f0a Mon Sep 17 00:00:00 2001 From: Zalim Bashorov Date: Fri, 1 Aug 2014 16:26:37 +0400 Subject: [PATCH 084/167] Fix return type of PullDecl.isRootDecl: void -> boolean --- typescript-services/typescriptServices.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/typescript-services/typescriptServices.d.ts b/typescript-services/typescriptServices.d.ts index 18bef7b3d..25f174b43 100644 --- a/typescript-services/typescriptServices.d.ts +++ b/typescript-services/typescriptServices.d.ts @@ -5640,7 +5640,7 @@ declare module TypeScript { public hasBeenBound(): boolean; public isSynthesized(): boolean; public ast(): AST; - public isRootDecl(): void; + public isRootDecl(): boolean; } class RootPullDecl extends PullDecl { private _isExternalModule; @@ -9317,4 +9317,4 @@ declare module TypeScript.Services { declare module 'typescript-services' { export = TypeScript; -} \ No newline at end of file +} From f7c9354f94582093578d6911bb128eed15ca3c1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 15:40:16 +0200 Subject: [PATCH 085/167] body-parser definitions added --- body-parser/body-parser.d.ts | 63 +++++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 0cd67332a..3f2f90057 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,12 +1,65 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definitions by: Santi Albo + +// Definition by: Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module "body-parser" { - import express = require('express'); - function e(options?: any): express.RequestHandler; - export = e; -} \ No newline at end of file + import express = require('express'); + + module e { + + // JSON Options + interface JsonOptions { + strict? : boolean; // only parse objects and arrays. (default: true) + inflate? : boolean; // if deflated bodies will be inflated. (default: true) + limit? : number; // maximum request body size. (default: <100kb>) + reviver? : (k :any, v:any) => any // passed to JSON.parse() + type? : string; // request content-type to parse (default: json) + verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + } + + // Raw Options + interface RawOptions { + inflate? : boolean; // if deflated bodies will be inflated. (default: true) + limit? :number; // maximum request body size. (default: <100kb>) + type? : string; // request content-type to parse (default: application/octet-stream) + verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + } + + // Text Options + interface TextOptions { + defaultCharset? : string; // the default charset to parse as, if not specified in content-type. (default: utf-8) + inflate? : boolean; // if deflated bodies will be inflated. (default: true) + limit? : number; // maximum request body size. (default: <100kb>) + type? : string; // request content-type to parse (default: text/plain) + verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + } + + // UrlEncoded Options + interface UrlEncodedOptions { + extended? : boolean; // parse extended syntax with the qs module. (default: true) + inflate? : boolean; // if deflated bodies will be inflated. (default: true) + limit: number; // maximum request body size. (default: <100kb>) + type: string; // request content-type to parse (default: urlencoded) + verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + } + + + // Returns middleware that only parses json + function json(options? : JsonOptions) : express.RequestHandler; + + // Returns middleware that parses all bodies as a Buffer + function raw(options? : RawOptions) : express.RequestHandler; + + // Returns middleware that parses all bodies as a string + function text(options? : TextOptions) : express.RequestHandler; + + // Returns middleware that only parses urlencoded bodies + function urlencoded(options? : UrlEncodedOptions) : express.RequestHandler; + } + + export = e; +} From 72943b80ba4c330379a4f2dcd05765a5bbb64fc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 16:03:41 +0200 Subject: [PATCH 086/167] Fixed: expected '// Definitions by: ' at line 3 --- body-parser/body-parser.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 3f2f90057..9271144dc 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,6 +1,5 @@ // Type definitions for body-parser // Project: http://expressjs.com - // Definition by: Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped From 6165fcf3c2b20a34fcfd7b221543bc0e4cbf4117 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 16:11:38 +0200 Subject: [PATCH 087/167] Fixed: expected url at line 3 --- body-parser/body-parser.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 9271144dc..a1932dae0 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definition by: Jonathan Häberle +// Definition by: Jonathan Haeberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 21ec790831327a8116ac55e3dfe5a52019d147df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 16:24:03 +0200 Subject: [PATCH 088/167] Fixed Header --- body-parser/body-parser.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index a1932dae0..614a63555 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definition by: Jonathan Haeberle +// Definition by: Santi Albo , Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 2e08343a0d65f2cacf393cf85be57f11e609366f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Fri, 1 Aug 2014 16:40:46 +0200 Subject: [PATCH 089/167] typing header format fixed --- body-parser/body-parser.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 614a63555..a46b5e336 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definition by: Santi Albo , Jonathan Häberle +// Definitions by: Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 83717637aef10852c667b559853fa57bae0edabf Mon Sep 17 00:00:00 2001 From: Maxime Fabre Date: Fri, 1 Aug 2014 18:24:47 +0200 Subject: [PATCH 090/167] Add new accessToken property to Mapbox --- mapbox/mapbox.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/mapbox/mapbox.d.ts b/mapbox/mapbox.d.ts index cf2da20b5..d15598cfd 100644 --- a/mapbox/mapbox.d.ts +++ b/mapbox/mapbox.d.ts @@ -13,6 +13,7 @@ ////////////////////////////////////////////////////////////////////// declare module L.mapbox { + var accessToken: string; /** * Create and automatically configure a map with layers, markers, and interactivity. From 2d77b19dfab6cc00e8d9423ffa71f621709151f8 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Fri, 1 Aug 2014 23:24:54 +0800 Subject: [PATCH 091/167] merged conflict --- body-parser/body-parser.d.ts | 180 ++++++++++++++++++++++++----------- 1 file changed, 127 insertions(+), 53 deletions(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index a46b5e336..994aa4e1b 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -1,64 +1,138 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definitions by: Jonathan Häberle +// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module "body-parser" { - import express = require('express'); + import express = require('express'); - module e { + /** + * bodyParser: use individual json/urlencoded middlewares + * @deprecated + */ - // JSON Options - interface JsonOptions { - strict? : boolean; // only parse objects and arrays. (default: true) - inflate? : boolean; // if deflated bodies will be inflated. (default: true) - limit? : number; // maximum request body size. (default: <100kb>) - reviver? : (k :any, v:any) => any // passed to JSON.parse() - type? : string; // request content-type to parse (default: json) - verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content + 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; + + module 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. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; } - // Raw Options - interface RawOptions { - inflate? : boolean; // if deflated bodies will be inflated. (default: true) - limit? :number; // maximum request body size. (default: <100kb>) - type? : string; // request content-type to parse (default: application/octet-stream) - verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content - } - - // Text Options - interface TextOptions { - defaultCharset? : string; // the default charset to parse as, if not specified in content-type. (default: utf-8) - inflate? : boolean; // if deflated bodies will be inflated. (default: true) - limit? : number; // maximum request body size. (default: <100kb>) - type? : string; // request content-type to parse (default: text/plain) - verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content - } - - // UrlEncoded Options - interface UrlEncodedOptions { - extended? : boolean; // parse extended syntax with the qs module. (default: true) - inflate? : boolean; // if deflated bodies will be inflated. (default: true) - limit: number; // maximum request body size. (default: <100kb>) - type: string; // request content-type to parse (default: urlencoded) - verify? : (req : express.Request, res : express.Response, streamBuf : any, encoding : string) => void; // function to verify body content - } - - - // Returns middleware that only parses json - function json(options? : JsonOptions) : express.RequestHandler; - - // Returns middleware that parses all bodies as a Buffer - function raw(options? : RawOptions) : express.RequestHandler; - - // Returns middleware that parses all bodies as a string - function text(options? : TextOptions) : express.RequestHandler; - - // Returns middleware that only parses urlencoded bodies - function urlencoded(options? : UrlEncodedOptions) : express.RequestHandler; - } - - export = e; -} + export = bodyParser; +} \ No newline at end of file From 8e33cf7b841fc1bc072824d990ce970781294572 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Sat, 2 Aug 2014 08:31:04 +0900 Subject: [PATCH 092/167] Add text-encoding library --- CONTRIBUTORS.md | 1 + text-encoding/text-encoding-tests.ts | 60 ++++++++++++++++++++++++++++ text-encoding/text-encoding.d.ts | 45 +++++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 text-encoding/text-encoding-tests.ts create mode 100644 text-encoding/text-encoding.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 088a423eb..af326634b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -326,6 +326,7 @@ All definitions files include a header with the author and editors, so at some p * [Tags Manager](http://welldonethings.com/tags/manager) (by [Vincent Bortone](https://github.com/vbortone)) * [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com)) * [text-buffer](https://github.com/atom/text-buffer) (by [vvakame](https://github.com/vvakame)) +* [text-encoding](https://github.com/inexorabletash/text-encoding) (by [MIZUNE Pine](https://github.com/pine613)) * [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/)) * [TimelineJS](https://github.com/NUKnightLab/TimelineJS) (by [Roland Zwaga](https://github.com/rolandzwaga)) * [timezonecomplete](https://github.com/SpiritIT/timezonecomplete) (by [Rogier Schouten](https://github.com/rogierschouten)) diff --git a/text-encoding/text-encoding-tests.ts b/text-encoding/text-encoding-tests.ts new file mode 100644 index 000000000..e0274a04c --- /dev/null +++ b/text-encoding/text-encoding-tests.ts @@ -0,0 +1,60 @@ +/// + +function test_encoder() { + var text = "plain text"; + var uint8array: Uint8Array; + + // constructor + uint8array = new TextEncoder().encode(text); + uint8array = new TextEncoder('utf-8').encode(text); + uint8array = new TextEncoder('windows-1252', { NONSTANDARD_allowLegacyEncoding: true }).encode(text); + + uint8array = TextEncoder().encode(text); + uint8array = TextEncoder('utf-8').encode(text); + uint8array = TextEncoder('windows-1252', { NONSTANDARD_allowLegacyEncoding: true }).encode(text); + + // attributes + var encoder = new TextEncoder(); + encoder.encoding = 'utf-8'; + var encoding: string = encoder.encoding; + + // methods + encoder.encode(); + encoder.encode(text); + encoder.encode(text, { stream: true }); +} + +function test_decoder() { + var text = "plain text"; + var uint8array: Uint8Array = TextEncoder().encode(text); + + // constructor + text = new TextDecoder().decode(uint8array); + text = new TextDecoder('utf-8').decode(uint8array); + text = new TextDecoder('windows-1252', {}).decode(uint8array); + text = new TextDecoder('windows-1252', { fatal: true }).decode(uint8array); + text = new TextDecoder('windows-1252', { ignoreBOM: true }).decode(uint8array); + + text = TextDecoder().decode(uint8array); + text = TextDecoder('utf-8').decode(uint8array); + text = TextDecoder('windows-1252', {}).decode(uint8array); + text = TextDecoder('windows-1252', { fatal: true }).decode(uint8array); + text = TextDecoder('windows-1252', { ignoreBOM: true }).decode(uint8array); + + // attributes + var decoder = new TextDecoder(); + + decoder.encoding = 'utf-8'; + var encoding: string = decoder.encoding; + + decoder.fatal = true; + var fatal: boolean = decoder.fatal; + + decoder.ignoreBOM = true; + var ignoreBOM: boolean = decoder.ignoreBOM; + + // methods + decoder.decode(); + decoder.decode(uint8array); + decoder.decode(uint8array, { stream: true }); +} \ No newline at end of file diff --git a/text-encoding/text-encoding.d.ts b/text-encoding/text-encoding.d.ts new file mode 100644 index 000000000..422597b41 --- /dev/null +++ b/text-encoding/text-encoding.d.ts @@ -0,0 +1,45 @@ +// Type definitions for text-encoding +// Project: https://github.com/inexorabletash/text-encoding +// Definitions by: MIZUNE Pine +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module TextEncodingStatic { + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + + interface TextDecodeOptions { + stream?: boolean; + } + + interface TextEncoderOptions { + NONSTANDARD_allowLegacyEncoding?: boolean; + } + + interface TextDecoder { + encoding: string; + fatal: boolean; + ignoreBOM: boolean; + decode(input?: ArrayBufferView, options?: TextDecodeOptions): string; + } + + interface TextEncoder { + encoding: string; + encode(input?: string, options?: TextEncodeOptions): Uint8Array; + } + + interface TextEncodeOptions { + stream?: boolean; + } +} + +declare var TextDecoder: { + (label?: string, options?: TextEncodingStatic.TextDecoderOptions): TextEncodingStatic.TextDecoder; + new (label?: string, options?: TextEncodingStatic.TextDecoderOptions): TextEncodingStatic.TextDecoder; +}; + +declare var TextEncoder: { + (utfLabel?: string, options?: TextEncodingStatic.TextEncoderOptions): TextEncodingStatic.TextEncoder; + new (utfLabel?: string, options?: TextEncodingStatic.TextEncoderOptions): TextEncodingStatic.TextEncoder; +}; \ No newline at end of file From a417b07f5b2ebc8610c24d8f35a5fc3d66384b91 Mon Sep 17 00:00:00 2001 From: Atsushi Kanehara Date: Sat, 2 Aug 2014 08:57:23 +0900 Subject: [PATCH 093/167] Fixed signature of `verifyClient`. --- ws/ws.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ws/ws.d.ts b/ws/ws.d.ts index ef7acc3ba..d12e2913f 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -91,8 +91,8 @@ declare module "ws" { port?: number; server?: http.Server; verifyClient?: { - (info: {origin: string; secure: boolean; req: http.ClientRequest}): boolean; - (info: {origin: string; secure: boolean; req: http.ClientRequest}, + (info: {origin: string; secure: boolean; req: http.ServerRequest}): boolean; + (info: {origin: string; secure: boolean; req: http.ServerRequest}, callback: (res: boolean) => void): void; }; handleProtocols?: any; From c874738f2eee50077d77659a114ad05e449f5f77 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sat, 2 Aug 2014 01:23:38 -0300 Subject: [PATCH 094/167] add angular $viewChangeListeners to ngModelController --- angularjs/angular.d.ts | 93 ++++++++++++++++++++++-------------------- 1 file changed, 49 insertions(+), 44 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index c515b096f..e447985fb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -22,7 +22,7 @@ declare module ng { interface IServiceProviderClass { new(...args: any[]): IServiceProvider; } - + interface IServiceProviderFactory { (...args: any[]): IServiceProvider; } @@ -49,9 +49,9 @@ declare module ng { /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * + * * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * + * * @param obj Object to iterate over. * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. @@ -59,9 +59,9 @@ declare module ng { forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * + * * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * + * * @param obj Object to iterate over. * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. @@ -69,9 +69,9 @@ declare module ng { forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. - * + * * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. - * + * * @param obj Object to iterate over. * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. @@ -96,7 +96,7 @@ declare module ng { * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. - * + * * @param name The name of the module to create or retrieve. * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. * @param configFn Optional configuration function for the module. @@ -128,19 +128,19 @@ declare module ng { animation(object: Object): IModule; /** * Use this method to register work which needs to be performed on module loading. - * + * * @param configFn Execute this function on module load. Useful for service configuration. */ config(configFn: Function): IModule; /** * Use this method to register work which needs to be performed on module loading. - * + * * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. */ config(inlineAnnotatedFunction: any[]): IModule; /** * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. - * + * * @param name The name of the constant. * @param value The constant value. */ @@ -148,18 +148,18 @@ declare module ng { constant(object: Object): IModule; /** * The $controller service is used by Angular to create new controllers. - * + * * This provider allows controller registration via the register method. - * + * * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). */ controller(name: string, controllerConstructor: Function): IModule; /** * The $controller service is used by Angular to create new controllers. - * + * * This provider allows controller registration via the register method. - * + * * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). */ @@ -170,14 +170,14 @@ declare module ng { directive(object: Object): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. - * + * * @param name The name of the instance. * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). */ factory(name: string, $getFn: Function): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. - * + * * @param name The name of the instance. * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). */ @@ -291,6 +291,7 @@ declare module ng { $parsers: IModelParser[]; $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; $error: any; $pristine: boolean; $dirty: boolean; @@ -306,6 +307,10 @@ declare module ng { (value: any): any; } + interface IModelViewChangeListener { + (): void; + } + /////////////////////////////////////////////////////////////////////////// // Scope // see http://docs.angularjs.org/api/ng.$rootScope.Scope @@ -574,17 +579,17 @@ declare module ng { interface IQService { /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. - * + * * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * + * * @param promises An array or hash of promises. */ all(promises: IPromise[]): IPromise; /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. - * + * * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * + * * @param promises An array or hash of promises. */ all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any }>; @@ -594,27 +599,27 @@ declare module ng { defer(): IDeferred; /** * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. - * + * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. - * + * * @param reason Constant, message, exception or an object representing the rejection reason. */ reject(reason?: any): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * + * * @param value Value or a promise */ when(value: IPromise): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * + * * @param value Value or a promise */ when(value: T): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * + * * @param value Value or a promise */ when(): IPromise; @@ -702,7 +707,7 @@ declare module ng { aHrefSanitizationWhitelist(): RegExp; aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; - + imgSrcSanitizationWhitelist(): RegExp; imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; } @@ -742,7 +747,7 @@ declare module ng { } /** - * HttpService + * HttpService * see http://docs.angularjs.org/api/ng/service/$http */ interface IHttpService { @@ -753,7 +758,7 @@ declare module ng { /** * Shortcut method to perform GET request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -761,7 +766,7 @@ declare module ng { /** * Shortcut method to perform DELETE request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -769,7 +774,7 @@ declare module ng { /** * Shortcut method to perform HEAD request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -777,7 +782,7 @@ declare module ng { /** * Shortcut method to perform JSONP request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -785,7 +790,7 @@ declare module ng { /** * Shortcut method to perform POST request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param data Request content * @param config Optional configuration object @@ -794,7 +799,7 @@ declare module ng { /** * Shortcut method to perform PUT request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param data Request content * @param config Optional configuration object @@ -814,12 +819,12 @@ declare module ng { /** * Object describing the request to be made and how it should be processed. - * see http://docs.angularjs.org/api/ng/service/$http#usage + * see http://docs.angularjs.org/api/ng/service/$http#usage */ interface IRequestShortcutConfig { /** * {Object.} - * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. + * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. */ params?: any; @@ -850,7 +855,7 @@ declare module ng { withCredentials?: boolean; /** - * {string|Object} + * {string|Object} * Data to be sent as the request message data. */ data?: any; @@ -881,7 +886,7 @@ declare module ng { /** * Object describing the request to be made and how it should be processed. - * see http://docs.angularjs.org/api/ng/service/$http#usage + * see http://docs.angularjs.org/api/ng/service/$http#usage */ interface IRequestConfig extends IRequestShortcutConfig { /** @@ -1114,7 +1119,7 @@ declare module ng { annotate(fn: Function): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; get(name: string): any; - has(name: string): boolean; + has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): any; invoke(inlineAnnotatedFunction: any[]): any; invoke(func: Function, context?: any, locals?: any): any; @@ -1130,7 +1135,7 @@ declare module ng { // constant(name: string, value: any): any; /** * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. - * + * * @param name The name of the constant. * @param value The constant value. */ @@ -1138,19 +1143,19 @@ declare module ng { /** * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * + * * @param name The name of the service to decorate. * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: - * + * * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. */ decorator(name: string, decorator: Function): void; /** * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * + * * @param name The name of the service to decorate. * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: - * + * * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. */ decorator(name: string, inlineAnnotatedFunction: any[]): void; From 281db74a55053efb4084f96021be65eafd96029f Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Sat, 2 Aug 2014 21:59:16 +0900 Subject: [PATCH 095/167] Change module name --- text-encoding/text-encoding.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/text-encoding/text-encoding.d.ts b/text-encoding/text-encoding.d.ts index 422597b41..574b25d71 100644 --- a/text-encoding/text-encoding.d.ts +++ b/text-encoding/text-encoding.d.ts @@ -3,7 +3,7 @@ // Definitions by: MIZUNE Pine // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module TextEncodingStatic { +declare module TextEncoding { interface TextDecoderOptions { fatal?: boolean; ignoreBOM?: boolean; @@ -35,11 +35,11 @@ declare module TextEncodingStatic { } declare var TextDecoder: { - (label?: string, options?: TextEncodingStatic.TextDecoderOptions): TextEncodingStatic.TextDecoder; - new (label?: string, options?: TextEncodingStatic.TextDecoderOptions): TextEncodingStatic.TextDecoder; + (label?: string, options?: TextEncoding.TextDecoderOptions): TextEncoding.TextDecoder; + new (label?: string, options?: TextEncoding.TextDecoderOptions): TextEncoding.TextDecoder; }; declare var TextEncoder: { - (utfLabel?: string, options?: TextEncodingStatic.TextEncoderOptions): TextEncodingStatic.TextEncoder; - new (utfLabel?: string, options?: TextEncodingStatic.TextEncoderOptions): TextEncodingStatic.TextEncoder; + (utfLabel?: string, options?: TextEncoding.TextEncoderOptions): TextEncoding.TextEncoder; + new (utfLabel?: string, options?: TextEncoding.TextEncoderOptions): TextEncoding.TextEncoder; }; \ No newline at end of file From b7dda17cc1b21040560192daeccead6114fdce8f Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sat, 2 Aug 2014 13:59:17 -0300 Subject: [PATCH 096/167] angular directive changes, still missing #2605 --- angularjs/angular-tests.ts | 461 ++++++++++++++++++++----------------- angularjs/angular.d.ts | 38 +-- 2 files changed, 269 insertions(+), 230 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index a1577856e..2507d7f8c 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -231,11 +231,11 @@ foo.then((x) => { }).then((x) => { // Object is inferred here x.a = 123; - //Try a promise + //Try a promise var y: ng.IPromise; - return y; + return y; }).then((x) => { - // x is infered to be a number, which is the resolved value of a promise + // x is infered to be a number, which is the resolved value of a promise x.toFixed(); }); @@ -281,252 +281,279 @@ test_IAttributes({ $attr: {} }); +class SampleDirective implements ng.IDirective { + public restrict = 'A'; + name = 'doh'; + + compile(templateElement: any) { + return this.link; + } + + link(scope: any) { + + } +} + +class SampleDirective2 implements ng.IDirective { + public restrict = 'EAC'; + + compile(templateElement: any) { + return { + pre: this.link + }; + } + + link(scope: any) { + + } +} + // test from https://docs.angularjs.org/guide/directive angular.module('docsSimpleDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - template: 'Name: {{customer.name}} Address: {{customer.address}}' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); angular.module('docsTemplateUrlDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - templateUrl: 'my-customer.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); angular.module('docsRestrictDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - templateUrl: 'my-customer.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); angular.module('docsScopeProblemExample', []) - .controller('NaomiController', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .controller('IgorController', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Igor', - address: '123 Somewhere' - }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - templateUrl: 'my-customer.html' - }; - }); + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); angular.module('docsIsolateScopeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; - $scope.igor = { name: 'Igor', address: '123 Somewhere' }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - scope: { - customerInfo: '=info' - }, - templateUrl: 'my-customer-iso.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); angular.module('docsIsolationExample', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; - $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - scope: { - customerInfo: '=info' - }, - templateUrl: 'my-customer-plus-vojta.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); angular.module('docsTimeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.format = 'M/d/yy h:mm:ss a'; - }]) - .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { - return { - link: function(scope: any, element: any, attrs: any) { - var format: any, - timeoutId: any; + return { + link: function(scope: any, element: any, attrs: any) { + var format: any, + timeoutId: any; - function updateTime() { - element.text(dateFilter(new Date(), format)); - } + function updateTime() { + element.text(dateFilter(new Date(), format)); + } - scope.$watch(attrs.myCurrentTime, function (value: any) { - format = value; - updateTime(); - }); + scope.$watch(attrs.myCurrentTime, function (value: any) { + format = value; + updateTime(); + }); - element.on('$destroy', function () { - $interval.cancel(timeoutId); - }); + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); - // start the UI update process; save the timeoutId for canceling - timeoutId = $interval(function () { - updateTime(); // update DOM - }, 1000); - } - }; - }]); + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); angular.module('docsTransclusionDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.name = 'Tobias'; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - templateUrl: 'my-dialog.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); angular.module('docsTransclusionExample', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.name = 'Tobias'; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - scope: {}, - templateUrl: 'my-dialog.html', - link: function (scope: any, element: any) { - scope.name = 'Jeff'; - } - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: any, element: any) { + scope.name = 'Jeff'; + } + }; + }); angular.module('docsIsoFnBindExample', []) - .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { - $scope.name = 'Tobias'; - $scope.hideDialog = function () { - $scope.dialogIsHidden = true; - $timeout(function () { - $scope.dialogIsHidden = false; - }, 2000); - }; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - scope: { - 'close': '&onClose' - }, - templateUrl: 'my-dialog-close.html' - }; - }); + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); angular.module('dragModule', []) - .directive('myDraggable', ['$document', function($document: any) { - return function(scope: any, element: any, attr: any) { - var startX = 0, startY = 0, x = 0, y = 0; + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; - element.css({ - position: 'relative', - border: '1px solid red', - backgroundColor: 'lightgrey', - cursor: 'pointer' - }); + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); - element.on('mousedown', function(event: any) { - // Prevent default dragging of selected content - event.preventDefault(); - startX = event.pageX - x; - startY = event.pageY - y; - $document.on('mousemove', mousemove); - $document.on('mouseup', mouseup); - }); + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); - function mousemove(event: any) { - y = event.pageY - startY; - x = event.pageX - startX; - element.css({ - top: y + 'px', - left: x + 'px' - }); - } + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } - function mouseup() { - $document.off('mousemove', mousemove); - $document.off('mouseup', mouseup); - } - }; - }]); + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); angular.module('docsTabsExample', []) - .directive('myTabs', function() { - return { - restrict: 'E', - transclude: true, - scope: {}, - controller: function($scope: any) { - var panes: any = $scope.panes = []; + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: any) { + var panes: any = $scope.panes = []; - $scope.select = function(pane: any) { - angular.forEach(panes, function(pane: any) { - pane.selected = false; - }); - pane.selected = true; - }; + $scope.select = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; - this.addPane = function(pane: any) { - if (panes.length === 0) { - $scope.select(pane); - } - panes.push(pane); - }; - }, - templateUrl: 'my-tabs.html' - }; - }) - .directive('myPane', function() { - return { - require: '^myTabs', - restrict: 'E', - transclude: true, - scope: { - title: '@' - }, - link: function(scope, element, attrs, tabsCtrl) { - tabsCtrl.addPane(scope); - }, - templateUrl: 'my-pane.html' - }; - }); + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope.select(pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope: any, element: any, attrs: any, tabsCtrl: any) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..b1b5e358f 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1031,22 +1031,34 @@ declare module ng { (...args: any[]): IDirective; } + interface IDirectiveLinkFn { + ( + scope?: IScope, + instanceElement?: IAugmentedJQuery, + instanceAttributes?: IAttributes, + controller?: any, + transclude?: ITranscludeFunction + ): void; + } - interface IDirective{ - compile?: - (templateElement: IAugmentedJQuery, - templateAttributes: IAttributes, - transclude: ITranscludeFunction - ) => any; + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement?: IAugmentedJQuery, + templateAttributes?: IAttributes, + transclude?: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; controller?: any; controllerAs?: string; - link?: - (scope: IScope, - instanceElement: IAugmentedJQuery, - instanceAttributes: IAttributes, - controller: any, - transclude: ITranscludeFunction - ) => void; + link?: IDirectivePrePost; name?: string; priority?: number; replace?: boolean; From 12fba7b62683f4ed7a78247756b69bdb06675ada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Sat, 2 Aug 2014 20:29:45 +0200 Subject: [PATCH 097/167] missing npost() function added --- q/Q.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/q/Q.d.ts b/q/Q.d.ts index 8e9696be5..617bf0140 100644 --- a/q/Q.d.ts +++ b/q/Q.d.ts @@ -214,6 +214,7 @@ declare module Q { export function nfapply(nodeFunction: Function, args: any[]): Promise; export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; + export function npost(nodeModule: any, functionName: string, args: any[]): Promise; export function nsend(nodeModule: any, functionName: string, ...args: any[]): Promise; export function nmcall(nodeModule: any, functionName: string, ...args: any[]): Promise; From 64795f2f0f0b96d7bf95d1d485e11dbc6d6703d1 Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Sun, 3 Aug 2014 04:47:28 +0800 Subject: [PATCH 098/167] Added morgan definitions --- morgan/morgan-tests.ts | 29 +++++++++++++ morgan/morgan.d.ts | 93 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 morgan/morgan-tests.ts create mode 100644 morgan/morgan.d.ts diff --git a/morgan/morgan-tests.ts b/morgan/morgan-tests.ts new file mode 100644 index 000000000..00e67f875 --- /dev/null +++ b/morgan/morgan-tests.ts @@ -0,0 +1,29 @@ +/// +/** + * Created by staticfunction on 8/3/14. + */ + +import morgan = require('morgan'); + +// a pre-defined name +morgan('combined') +morgan('common') +morgan('short') +morgan('tiny') + +// a format string +morgan(':remote-addr :method :url') + +// a custom function +morgan(function (req, res) { + return req.method + ' ' + req.url +}) + +morgan('combined', { + buffer: true, + immediate: true, + skip: function (req, res) { return res.statusCode < 400 }, + stream: (str: string) => { + console.log(str); + } +}); diff --git a/morgan/morgan.d.ts b/morgan/morgan.d.ts new file mode 100644 index 000000000..b889bc7be --- /dev/null +++ b/morgan/morgan.d.ts @@ -0,0 +1,93 @@ +// Type definitions for morgan 1.2.2 +// Project: https://github.com/expressjs/morgan +// Definitions by: James Roland Cabresos +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module "morgan" { + + import express = require('express'); + + module morgan { + + export function token(name: string, callback: (req: express.Request, res: express.Response) => T): express.RequestHandler; + + /*** + * Morgan accepts these properties in the options object. + */ + export interface Options { + + /*** + * Buffer duration before writing logs to the stream, defaults to false. When set to true, defaults to 1000 ms. + */ + buffer?: boolean; + + /*** + * Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response cannot be logged (like the response code). + */ + immediate?: boolean; + + /*** + * Function to determine if logging is skipped, defaults to false. This function will be called as skip(req, res). + */ + skip?: (req: express.Request, res: express.Response) => boolean; + + /*** + * Output stream for writing log lines, defaults to process.stdout. + * @param str + */ + stream?: (str: string) => void; + } + } + + /*** + * Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry. + * @param format + * @param options + */ + function morgan(format: string, options?: morgan.Options): express.RequestHandler; + + /*** + * Standard Apache combined log output. + * :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" + * @param format + * @param options + */ + function morgan(format: 'combined', options?: morgan.Options): express.RequestHandler; + + /*** + * Standard Apache common log output. + * :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] + * @param format + * @param options + */ + function morgan(format: 'common', options?: morgan.Options): express.RequestHandler; + + /*** + * Concise output colored by response status for development use. The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes. + * :method :url :status :response-time ms - :res[content-length] + * @param format + * @param options + */ + function morgan(format: 'dev', options?: morgan.Options): express.RequestHandler; + + /*** + * Shorter than default, also including response time. + * :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms + * @param format + * @param options + */ + function morgan(format: 'short', options?: morgan.Options): express.RequestHandler; + + /*** + * The minimal output. + * :method :url :status :res[content-length] - :response-time ms + * @param format + * @param options + */ + function morgan(format: 'tiny', options?: morgan.Options): express.RequestHandler; + + function morgan(custom: (req: express.Request, res: express.Response) => string): express.RequestHandler + + export = morgan; +} \ No newline at end of file From d9ada3076f601e05a8fb85eee418ced6ba545e26 Mon Sep 17 00:00:00 2001 From: satoru kimura Date: Sun, 3 Aug 2014 13:13:23 +0900 Subject: [PATCH 099/167] update to three.js r68. --- threejs/tests/canvas/canvas_geometry_cube.ts | 2 +- .../canvas/canvas_interactive_cubes_tween.ts | 1 + .../tests/canvas/canvas_lights_pointlights.ts | 43 +- threejs/tests/canvas/canvas_materials.ts | 19 +- threejs/tests/css3d/css3d_sprites.ts | 20 +- threejs/tests/math/test_unit_math.ts | 640 ++++++++++++---- .../webgl/webgl_animation_skinning_morph.ts | 297 ++++++++ threejs/tests/webgl/webgl_buffergeometry.ts | 18 +- threejs/tests/webgl/webgl_camera.ts | 2 +- ...webgl_interactive_raycasting_pointcloud.ts | 335 +++++++++ threejs/tests/webgl/webgl_lensflares.ts | 2 +- threejs/tests/webgl/webgl_materials.ts | 10 +- .../tests/webgl/webgl_particles_billboards.ts | 4 +- threejs/tests/webgl/webgl_postprocessing.ts | 2 - threejs/three-tests.ts | 3 + threejs/three.d.ts | 710 ++++++++++++------ 16 files changed, 1653 insertions(+), 455 deletions(-) create mode 100644 threejs/tests/webgl/webgl_animation_skinning_morph.ts create mode 100644 threejs/tests/webgl/webgl_interactive_raycasting_pointcloud.ts diff --git a/threejs/tests/canvas/canvas_geometry_cube.ts b/threejs/tests/canvas/canvas_geometry_cube.ts index 00c3b0426..bf5f9ae99 100644 --- a/threejs/tests/canvas/canvas_geometry_cube.ts +++ b/threejs/tests/canvas/canvas_geometry_cube.ts @@ -43,7 +43,7 @@ // Cube - var geometry = new THREE.CubeGeometry(200, 200, 200); + var geometry = new THREE.BoxGeometry(200, 200, 200); for (var i = 0; i < geometry.faces.length; i += 2) { diff --git a/threejs/tests/canvas/canvas_interactive_cubes_tween.ts b/threejs/tests/canvas/canvas_interactive_cubes_tween.ts index 8fbd7c2cf..865e07023 100644 --- a/threejs/tests/canvas/canvas_interactive_cubes_tween.ts +++ b/threejs/tests/canvas/canvas_interactive_cubes_tween.ts @@ -1,5 +1,6 @@ /// /// +/// // https://github.com/mrdoob/three.js/blob/master/examples/canvas_interactive_cubes_tween.html diff --git a/threejs/tests/canvas/canvas_lights_pointlights.ts b/threejs/tests/canvas/canvas_lights_pointlights.ts index 1b6a6663f..ad1a103d5 100644 --- a/threejs/tests/canvas/canvas_lights_pointlights.ts +++ b/threejs/tests/canvas/canvas_lights_pointlights.ts @@ -7,7 +7,6 @@ // ------- variable definitions that does not exist in the original code. These are for typescript. // ------- var camera, scene, renderer, - particle1, particle2, particle3, light1, light2, light3, loader, mesh; @@ -43,14 +42,14 @@ } - particle1 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xff0040, program: program })); - scene.add(particle1); + var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0xff0040, program: program } ) ); + light1.add( sprite ); - particle2 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x0040ff, program: program })); - scene.add(particle2); + var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0x0040ff, program: program } ) ); + light2.add( sprite ); - particle3 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x80ff80, program: program })); - scene.add(particle3); + var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0x80ff80, program: program } ) ); + light3.add( sprite ); loader = new THREE.JSONLoader(); loader.load('obj/WaltHeadLo.js', function (geometry) { @@ -94,29 +93,17 @@ if (mesh) mesh.rotation.y -= 0.01; - particle1.position.x = Math.sin(time * 0.7) * 30; - particle1.position.y = Math.cos(time * 0.5) * 40; - particle1.position.z = Math.cos(time * 0.3) * 30; + light1.position.x = Math.sin( time * 0.7 ) * 30; + light1.position.y = Math.cos( time * 0.5 ) * 40; + light1.position.z = Math.cos( time * 0.3 ) * 30; - light1.position.x = particle1.position.x; - light1.position.y = particle1.position.y; - light1.position.z = particle1.position.z; + light2.position.x = Math.cos( time * 0.3 ) * 30; + light2.position.y = Math.sin( time * 0.5 ) * 40; + light2.position.z = Math.sin( time * 0.7 ) * 30; - particle2.position.x = Math.cos(time * 0.3) * 30; - particle2.position.y = Math.sin(time * 0.5) * 40; - particle2.position.z = Math.sin(time * 0.7) * 30; - - light2.position.x = particle2.position.x; - light2.position.y = particle2.position.y; - light2.position.z = particle2.position.z; - - particle3.position.x = Math.sin(time * 0.7) * 30; - particle3.position.y = Math.cos(time * 0.3) * 40; - particle3.position.z = Math.sin(time * 0.5) * 30; - - light3.position.x = particle3.position.x; - light3.position.y = particle3.position.y; - light3.position.z = particle3.position.z; + light3.position.x = Math.sin( time * 0.7 ) * 30; + light3.position.y = Math.cos( time * 0.3 ) * 40; + light3.position.z = Math.sin( time * 0.5 ) * 30; renderer.render(scene, camera); diff --git a/threejs/tests/canvas/canvas_materials.ts b/threejs/tests/canvas/canvas_materials.ts index 23524098a..a39a780ca 100644 --- a/threejs/tests/canvas/canvas_materials.ts +++ b/threejs/tests/canvas/canvas_materials.ts @@ -11,7 +11,7 @@ var container, stats; var camera, scene, renderer, objects; - var particleLight, pointLight; + var pointLight; init(); animate(); @@ -103,10 +103,6 @@ } - particleLight = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xffffff, program: program })); - particleLight.scale.x = particleLight.scale.y = 8; - scene.add(particleLight); - // Lights scene.add(new THREE.AmbientLight(Math.random() * 0x202020)); @@ -121,6 +117,10 @@ pointLight = new THREE.PointLight(0xffffff, 1); scene.add(pointLight); + var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0xffffff, program: program } ) ); + sprite.scale.set( 8, 8, 8 ); + pointLight.add( sprite ); + renderer = new THREE.CanvasRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); container.appendChild(renderer.domElement); @@ -198,13 +198,10 @@ } - particleLight.position.x = Math.sin(timer * 7) * 300; - particleLight.position.y = Math.cos(timer * 5) * 400; - particleLight.position.z = Math.cos(timer * 3) * 300; + pointLight.position.x = Math.sin( timer * 7 ) * 300; + pointLight.position.y = Math.cos( timer * 5 ) * 400; + pointLight.position.z = Math.cos( timer * 3 ) * 300; - pointLight.position.x = particleLight.position.x; - pointLight.position.y = particleLight.position.y; - pointLight.position.z = particleLight.position.z; renderer.render(scene, camera); diff --git a/threejs/tests/css3d/css3d_sprites.ts b/threejs/tests/css3d/css3d_sprites.ts index 20760735a..0b69a85bf 100644 --- a/threejs/tests/css3d/css3d_sprites.ts +++ b/threejs/tests/css3d/css3d_sprites.ts @@ -1,5 +1,6 @@ /// /// +/// // https://github.com/mrdoob/three.js/blob/master/examples/css3d_sprites.html @@ -26,23 +27,16 @@ scene = new THREE.Scene(); - var sprite = document.createElement('img'); - sprite.addEventListener('load', function (event) { + var image = document.createElement( 'img' ); + image.addEventListener( 'load', function ( event ) { - for (var i = 0, j = 0; i < particlesTotal; i++, j += 3) { + for ( var i = 0; i < particlesTotal; i ++ ) { - var canvas = document.createElement('canvas'); - canvas.width = sprite.width; - canvas.height = sprite.height; - - var context = canvas.getContext('2d'); - context.drawImage(sprite, 0, 0); - - var object = new THREE.CSS3DSprite(canvas); + var object = new THREE.CSS3DSprite( image.cloneNode() ); object.position.x = Math.random() * 4000 - 2000, object.position.y = Math.random() * 4000 - 2000, object.position.z = Math.random() * 4000 - 2000 - scene.add(object); + scene.add(object); objects.push(object); @@ -51,7 +45,7 @@ transition(); }, false); - sprite.src = 'textures/sprite.png'; + image.src = 'textures/sprite.png'; // Plane diff --git a/threejs/tests/math/test_unit_math.ts b/threejs/tests/math/test_unit_math.ts index f1c3818cc..a30e60dcd 100644 --- a/threejs/tests/math/test_unit_math.ts +++ b/threejs/tests/math/test_unit_math.ts @@ -6,6 +6,7 @@ // https://github.com/mrdoob/three.js/tree/master/test/unit/math ()=>{ + // -------------------------------------------- Constants var x = 2; var y = 3; var z = 4; @@ -25,8 +26,7 @@ var one3 = new THREE.Vector3( 1, 1, 1 ); var two3 = new THREE.Vector3( 2, 2, 2 ); - (QUnit.module)( "Box2" ); - + // -------------------------------------------- Box2 test( "constructor", function() { var a = new THREE.Box2(); ok( a.min.equals( posInf2 ), "Passed!" ); @@ -62,6 +62,21 @@ ok( a.max.equals( one2 ), "Passed!" ); }); + test( "setFromPoints", function() { + var a = new THREE.Box2(); + + a.setFromPoints( [ zero2, one2, two2 ] ); + ok( a.min.equals( zero2 ), "Passed!" ); + ok( a.max.equals( two2 ), "Passed!" ); + + a.setFromPoints( [ one2 ] ); + ok( a.min.equals( one2 ), "Passed!" ); + ok( a.max.equals( one2 ), "Passed!" ); + + a.setFromPoints( [] ); + ok( a.empty(), "Passed!" ); + }); + test( "empty/makeEmpty", function() { var a = new THREE.Box2(); @@ -197,21 +212,6 @@ ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); }); - test( "distanceToPoint", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == Math.sqrt( 2 ), "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == Math.sqrt( 2 ), "Passed!" ); - - ok( b.distanceToPoint( new THREE.Vector2( 2, 2 ) ) == Math.sqrt( 2 ), "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); - }); - test( "isIntersectionBox", function() { var a = new THREE.Box2( zero2.clone(), zero2.clone() ); var b = new THREE.Box2( zero2.clone(), one2.clone() ); @@ -267,6 +267,7 @@ ok( b.clone().translate( one2.clone().negate() ).equals( d ), "Passed!" ); }); + // -------------------------------------------- Box3 test( "constructor", function() { var a = new THREE.Box3(); ok( a.min.equals( posInf3 ), "Passed!" ); @@ -302,6 +303,21 @@ ok( a.max.equals( one3 ), "Passed!" ); }); + test( "setFromPoints", function() { + var a = new THREE.Box3(); + + a.setFromPoints( [ zero3, one3, two3 ] ); + ok( a.min.equals( zero3 ), "Passed!" ); + ok( a.max.equals( two3 ), "Passed!" ); + + a.setFromPoints( [ one3 ] ); + ok( a.min.equals( one3 ), "Passed!" ); + ok( a.max.equals( one3 ), "Passed!" ); + + a.setFromPoints( [] ); + ok( a.empty(), "Passed!" ); + }); + test( "empty/makeEmpty", function() { var a = new THREE.Box3(); @@ -508,7 +524,7 @@ var compareBox = function ( a, b, threshold? ) { threshold = threshold || 0.0001; return ( a.min.distanceTo( b.min ) < threshold && - a.max.distanceTo( b.max ) < threshold ); + a.max.distanceTo( b.max ) < threshold ); }; test( "applyMatrix4", function() { @@ -538,11 +554,19 @@ ok( b.clone().translate( one3.clone().negate() ).equals( d ), "Passed!" ); }); + // -------------------------------------------- Color test( "constructor", function(){ var c = new THREE.Color(); ok( c.r, "Red: " + c.r ); ok( c.g, "Green: " + c.g ); - ok( c.b, "Blue: " + c.g ); + ok( c.b, "Blue: " + c.b ); + }); + + test( "rgb constructor", function(){ + var c = new THREE.Color( 1, 1, 1 ); + ok( c.r == 1, "Passed" ); + ok( c.g == 1, "Passed" ); + ok( c.b == 1, "Passed" ); }); test( "copyHex", function(){ @@ -560,48 +584,48 @@ }); test( "setRGB", function(){ - var c = new THREE.Color() - c.setRGB(255, 2, 1); - ok( c.r == 255, "Red: " + c.r ); - ok( c.g == 2, "Green: " + c.g ); - ok( c.b == 1, "Blue: " + c.b ); + var c = new THREE.Color(); + c.setRGB(1, 0.2, 0.1); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g == 0.2, "Green: " + c.g ); + ok( c.b == 0.1, "Blue: " + c.b ); }); test( "copyGammaToLinear", function(){ var c = new THREE.Color(); var c2 = new THREE.Color(); - c2.setRGB(2, 4, 8) - c.copyGammaToLinear(c2) - ok( c.r == 4, "Red c: " + c.r + " Red c2: " + c2.r); - ok( c.g == 16, "Green c: " + c.g + " Green c2: " + c2.g); - ok( c.b == 64, "Blue c: " + c.b + " Blue c2: " + c2.b); + c2.setRGB(0.3, 0.5, 0.9); + c.copyGammaToLinear(c2); + ok( c.r == 0.09, "Red c: " + c.r + " Red c2: " + c2.r); + ok( c.g == 0.25, "Green c: " + c.g + " Green c2: " + c2.g); + ok( c.b == 0.81, "Blue c: " + c.b + " Blue c2: " + c2.b); }); test( "copyLinearToGamma", function(){ var c = new THREE.Color(); var c2 = new THREE.Color(); - c2.setRGB(4, 9, 16) - c.copyLinearToGamma(c2) - ok( c.r == 2, "Red c: " + c.r + " Red c2: " + c2.r); - ok( c.g == 3, "Green c: " + c.g + " Green c2: " + c2.g); - ok( c.b == 4, "Blue c: " + c.b + " Blue c2: " + c2.b); + c2.setRGB(0.09, 0.25, 0.81); + c.copyLinearToGamma(c2); + ok( c.r == 0.3, "Red c: " + c.r + " Red c2: " + c2.r); + ok( c.g == 0.5, "Green c: " + c.g + " Green c2: " + c2.g); + ok( c.b == 0.9, "Blue c: " + c.b + " Blue c2: " + c2.b); }); test( "convertGammaToLinear", function(){ var c = new THREE.Color(); - c.setRGB(2, 4, 8) - c.convertGammaToLinear() - ok( c.r == 4, "Red: " + c.r ); - ok( c.g == 16, "Green: " + c.g ); - ok( c.b == 64, "Blue: " + c.b ); + c.setRGB(0.3, 0.5, 0.9); + c.convertGammaToLinear(); + ok( c.r == 0.09, "Red: " + c.r ); + ok( c.g == 0.25, "Green: " + c.g ); + ok( c.b == 0.81, "Blue: " + c.b ); }); test( "convertLinearToGamma", function(){ var c = new THREE.Color(); - c.setRGB(4, 9, 16) - c.convertLinearToGamma() + c.setRGB(4, 9, 16); + c.convertLinearToGamma(); ok( c.r == 2, "Red: " + c.r ); ok( c.g == 3, "Green: " + c.g ); ok( c.b == 4, "Blue: " + c.b ); @@ -611,8 +635,8 @@ var c = new THREE.Color(); c.set(0xFF0000); ok( c.r == 1, "Red: " + c.r ); - ok( c.g == 0, "Green: " + c.g ); - ok( c.b == 0, "Blue: " + c.b ); + ok( c.g === 0, "Green: " + c.g ); + ok( c.b === 0, "Blue: " + c.b ); }); @@ -633,11 +657,11 @@ var c = new THREE.Color(); var c2 = new THREE.Color(); c.setRGB(0, 0, 0); - c.lerp(c2, 2); - ok( c.r == 2, "Red: " + c.r ); - ok( c.g == 2, "Green: " + c.g ); - ok( c.b == 2, "Blue: " + c.b ); - + c.lerp(c2, 0.2); + ok( c.r == 0.2, "Red: " + c.r ); + ok( c.g == 0.2, "Green: " + c.g ); + ok( c.b == 0.2, "Blue: " + c.b ); + }); @@ -645,8 +669,16 @@ var c = new THREE.Color(); c.setStyle('rgb(255,0,0)'); ok( c.r == 1, "Red: " + c.r ); - ok( c.g == 0, "Green: " + c.g ); - ok( c.b == 0, "Blue: " + c.b ); + ok( c.g === 0, "Green: " + c.g ); + ok( c.b === 0, "Blue: " + c.b ); + }); + + test( "setStyleRGBRedWithSpaces", function(){ + var c = new THREE.Color(); + c.setStyle('rgb(255, 0, 0)'); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g === 0, "Green: " + c.g ); + ok( c.b === 0, "Blue: " + c.b ); }); test( "setStyleRGBPercent", function(){ @@ -657,6 +689,14 @@ ok( c.b == 0.1, "Blue: " + c.b ); }); + test( "setStyleRGBPercentWithSpaces", function(){ + var c = new THREE.Color(); + c.setStyle('rgb(100%,50%,10%)'); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g == 0.5, "Green: " + c.g ); + ok( c.b == 0.1, "Blue: " + c.b ); + }); + test( "setStyleHexSkyBlue", function(){ var c = new THREE.Color(); c.setStyle('#87CEEB'); @@ -706,10 +746,7 @@ ok( hsl.h == 0.5, "hue: " + hsl.h ); ok( hsl.s == 1.0, "saturation: " + hsl.s ); - - - //ok( (Math.round(parseFloat(hsl.l)*100)/100) == 0.75, "lightness: " + hsl.l ); - ok( (Math.round(hsl.l*100)/100) == 0.75, "lightness: " + hsl.l ); + ok( (Math.round(parseFloat(hsl.l.toString())*100)/100) == 0.75, "lightness: " + hsl.l ); }); test( "setHSL", function () { @@ -722,6 +759,98 @@ ok( hsl.l == 0.25, "lightness: " + hsl.l ); }); + // -------------------------------------------- Euler + + var eulerZero = new THREE.Euler( 0, 0, 0, "XYZ" ); + var eulerAxyz = new THREE.Euler( 1, 0, 0, "XYZ" ); + var eulerAzyx = new THREE.Euler( 0, 1, 0, "ZYX" ); + + var matrixEquals4 = function( a, b ) { + var tolerance = 0.0001; + if( a.elements.length != b.elements.length ) { + return false; + } + for( var i = 0, il = a.elements.length; i < il; i ++ ) { + var delta = a.elements[i] - b.elements[i]; + if( delta > tolerance ) { + return false; + } + } + return true; + }; + + test( "constructor/equals", function() { + var a = new THREE.Euler(); + ok( a.equals( eulerZero ), "Passed!" ); + ok( ! a.equals( eulerAxyz ), "Passed!" ); + ok( ! a.equals( eulerAzyx ), "Passed!" ); + }); + + test( "clone/copy/equals", function() { + var a = eulerAxyz.clone(); + ok( a.equals( eulerAxyz ), "Passed!" ); + ok( ! a.equals( eulerZero ), "Passed!" ); + ok( ! a.equals( eulerAzyx ), "Passed!" ); + + a.copy( eulerAzyx ); + ok( a.equals( eulerAzyx ), "Passed!" ); + ok( ! a.equals( eulerAxyz ), "Passed!" ); + ok( ! a.equals( eulerZero ), "Passed!" ); + + }); + + test( "set", function() { + var a = new THREE.Euler(); + + a.set( 0, 1, 0, "ZYX" ); + ok( a.equals( eulerAzyx ), "Passed!" ); + ok( ! a.equals( eulerAxyz ), "Passed!" ); + ok( ! a.equals( eulerZero ), "Passed!" ); + }); + + test( "Quaternion.setFromEuler/Euler.fromQuaternion", function() { + var testValues = [ eulerZero, eulerAxyz, eulerAzyx ]; + for( var i = 0; i < testValues.length; i ++ ) { + var v = testValues[i]; + var q = new THREE.Quaternion().setFromEuler( v ); + + var v2 = new THREE.Euler().setFromQuaternion( q, v.order ); + var q2 = new THREE.Quaternion().setFromEuler( v2 ); + ok( q.equals( q2 ), "Passed!" ); + } + }); + + + test( "Matrix4.setFromEuler/Euler.fromRotationMatrix", function() { + var testValues = [ eulerZero, eulerAxyz, eulerAzyx ]; + for( var i = 0; i < testValues.length; i ++ ) { + var v = testValues[i]; + var m = new THREE.Matrix4().makeRotationFromEuler( v ); + + var v2 = new THREE.Euler().setFromRotationMatrix( m, v.order ); + var m2 = new THREE.Matrix4().makeRotationFromEuler( v2 ); + ok( matrixEquals4( m, m2 ), "Passed!" ); + } + }); + + test( "reorder", function() { + var testValues = [ eulerZero, eulerAxyz, eulerAzyx ]; + for( var i = 0; i < testValues.length; i ++ ) { + var v = testValues[i]; + var q = new THREE.Quaternion().setFromEuler( v ); + + v.reorder( 'YZX' ); + var q2 = new THREE.Quaternion().setFromEuler( v ); + ok( q.equals( q2 ), "Passed!" ); + + v.reorder( 'ZXY' ); + var q3 = new THREE.Quaternion().setFromEuler( v ); + ok( q.equals( q3 ), "Passed!" ); + } + }); + + // -------------------------------------------- Frustum + var unit3 = new THREE.Vector3( 1, 0, 0 ); var planeEquals = function ( a, b, tolerance ) { @@ -873,6 +1002,7 @@ ok( b.planes[0].equals( p0 ), "Passed!" ); }); + // -------------------------------------------- Line3 test( "constructor/equals", function() { var a = new THREE.Line3(); @@ -925,7 +1055,6 @@ // nearby the ray ok( a.closestPointToPointParameter( zero3.clone(), false ) == -1, "Passed!" ); var b2 = a.closestPointToPoint( zero3.clone(), false ); - console.log( b2 ); ok( b2.distanceTo( new THREE.Vector3( 1, 1, 0 ) ) < 0.0001, "Passed!" ); // nearby the ray @@ -939,7 +1068,7 @@ ok( c.distanceTo( one3.clone() ) < 0.0001, "Passed!" ); }); - + // -------------------------------------------- Matrix3 var matrixEquals3 = function( a, b, tolerance? ) { tolerance = tolerance || 0.0001; @@ -1081,15 +1210,13 @@ var identity = new THREE.Matrix4(); var a = new THREE.Matrix4(); var b = new THREE.Matrix3( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - //var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); ok( ! matrixEquals3( a, b ), "Passed!" ); b.getInverse( a, false ); ok( matrixEquals3( b, new THREE.Matrix3() ), "Passed!" ); - try { + try { b.getInverse( c, true ); ok( false, "Passed!" ); // should never get here. } @@ -1106,7 +1233,7 @@ new THREE.Matrix4().makeRotationZ( -0.3 ), new THREE.Matrix4().makeScale( 1, 2, 3 ), new THREE.Matrix4().makeScale( 1/8, 1/2, 1/3 ) - ]; + ]; for( var i = 0, il = testMatrices.length; i < il; i ++ ) { var m = testMatrices[i]; @@ -1131,9 +1258,9 @@ b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); var c = b.clone().transpose(); - ok( ! matrixEquals3( b, c ), "Passed!" ); + ok( ! matrixEquals3( b, c ), "Passed!" ); c.transpose(); - ok( matrixEquals3( b, c ), "Passed!" ); + ok( matrixEquals3( b, c ), "Passed!" ); }); test( "clone", function() { @@ -1147,8 +1274,10 @@ ok( ! matrixEquals3( a, b ), "Passed!" ); }); - var matrixEquals4 = function( a, b, tolerance? ) { - tolerance = tolerance || 0.0001; + // -------------------------------------------- Matrix4 + + var matrixEquals4 = function (a, b) { + var tolerance = 0.0001; if( a.elements.length != b.elements.length ) { return false; } @@ -1310,7 +1439,7 @@ b.getInverse( a, false ); ok( matrixEquals4( b, new THREE.Matrix4() ), "Passed!" ); - try { + try { b.getInverse( c, true ); ok( false, "Passed!" ); // should never get here. } @@ -1330,15 +1459,21 @@ new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 1000 ), new THREE.Matrix4().makeFrustum( -16, 16, -9, 9, 0.1, 10000 ), new THREE.Matrix4().makeTranslation( 1, 2, 3 ) - ]; + ]; for( var i = 0, il = testMatrices.length; i < il; i ++ ) { var m = testMatrices[i]; var mInverse = new THREE.Matrix4().getInverse( m ); + var mSelfInverse = m.clone(); + mSelfInverse.getInverse( mSelfInverse ); + + + // self-inverse should the same as inverse + ok( matrixEquals4( mSelfInverse, mInverse ), "Passed!" ); // the determinant of the inverse should be the reciprocal - ok( Math.abs( m.determinant() * mInverse.determinant() - 1 ) < 0.0001, "Passed!" ); + ok( Math.abs( m.determinant() * mInverse.determinant() - 1 ) < 0.0001, "Passed!" ); var mProduct = new THREE.Matrix4().multiplyMatrices( m, mInverse ); @@ -1355,9 +1490,9 @@ b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); var c = b.clone().transpose(); - ok( ! matrixEquals4( b, c ), "Passed!" ); + ok( ! matrixEquals4( b, c ), "Passed!" ); c.transpose(); - ok( matrixEquals4( b, c ), "Passed!" ); + ok( matrixEquals4( b, c ), "Passed!" ); }); test( "clone", function() { @@ -1372,10 +1507,75 @@ }); + test( "compose/decompose", function() { + var tValues = [ + new THREE.Vector3(), + new THREE.Vector3( 3, 0, 0 ), + new THREE.Vector3( 0, 4, 0 ), + new THREE.Vector3( 0, 0, 5 ), + new THREE.Vector3( -6, 0, 0 ), + new THREE.Vector3( 0, -7, 0 ), + new THREE.Vector3( 0, 0, -8 ), + new THREE.Vector3( -2, 5, -9 ), + new THREE.Vector3( -2, -5, -9 ) + ]; + + var sValues = [ + new THREE.Vector3( 1, 1, 1 ), + new THREE.Vector3( 2, 2, 2 ), + new THREE.Vector3( 1, -1, 1 ), + new THREE.Vector3( -1, 1, 1 ), + new THREE.Vector3( 1, 1, -1 ), + new THREE.Vector3( 2, -2, 1 ), + new THREE.Vector3( -1, 2, -2 ), + new THREE.Vector3( -1, -1, -1 ), + new THREE.Vector3( -2, -2, -2 ) + ]; + + var rValues = [ + new THREE.Quaternion(), + new THREE.Quaternion().setFromEuler( new THREE.Euler( 1, 1, 0 ) ), + new THREE.Quaternion().setFromEuler( new THREE.Euler( 1, -1, 1 ) ), + new THREE.Quaternion( 0, 0.9238795292366128, 0, 0.38268342717215614 ) + ]; + + + for( var ti = 0; ti < tValues.length; ti ++ ) { + for( var si = 0; si < sValues.length; si ++ ) { + for( var ri = 0; ri < rValues.length; ri ++ ) { + var t = tValues[ti]; + var s = sValues[si]; + var r = rValues[ri]; + + var m = new THREE.Matrix4().compose( t, r, s ); + var t2 = new THREE.Vector3(); + var r2 = new THREE.Quaternion(); + var s2 = new THREE.Vector3(); + + m.decompose( t2, r2, s2 ); + + var m2 = new THREE.Matrix4().compose( t2, r2, s2 ); + + var matrixIsSame = matrixEquals4( m, m2 ); + /* debug code + if( ! matrixIsSame ) { + console.log( t, s, r ); + console.log( t2, s2, r2 ); + console.log( m, m2 ); + }*/ + ok( matrixEquals4( m, m2 ), "Passed!" ); + + } + } + } + }); + + // -------------------------------------------- Plane + var comparePlane = function ( a, b, threshold? ) { threshold = threshold || 0.0001; return ( a.normal.distanceTo( b.normal ) < threshold && - Math.abs( a.constant - b.constant ) < threshold ); + Math.abs( a.constant - b.constant ) < threshold ); }; @@ -1564,6 +1764,8 @@ ok( comparePlane( a.clone().applyMatrix4( m ), a.clone().translate( new THREE.Vector3( 1, 1, 1 ) ) ), "Passed!" ); }); + // -------------------------------------------- Quaternion + var orders = [ 'XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY' ]; var eulerAngles = new THREE.Euler( 0.1, -0.3, 0.25 ); @@ -1658,12 +1860,9 @@ // ensure euler conversion to/from Quaternion matches. for( var i = 0; i < orders.length; i ++ ) { for( var j = 0; j < angles.length; j ++ ) { - var eulers2 = new THREE.Euler().setFromQuaternion( - new THREE.Quaternion().setFromEuler(new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i])), - orders[i] - ); - var v = new THREE.Vector3().applyEuler(eulers2); - ok( v.distanceTo( angles[j] ) < 0.001, "Passed!" ); + var eulers2 = new THREE.Euler().setFromQuaternion( new THREE.Quaternion().setFromEuler( new THREE.Euler( angles[j].x, angles[j].y, angles[j].z, orders[i] ) ), orders[i] ); + var newAngle = new THREE.Vector3( eulers2.x, eulers2.y, eulers2.z ); + ok( newAngle.distanceTo( angles[j] ) < 0.001, "Passed!" ); } } @@ -1673,7 +1872,7 @@ // ensure euler conversion for Quaternion matches that of Matrix4 for( var i = 0; i < orders.length; i ++ ) { - var q = new THREE.Quaternion().setFromEuler( eulerAngles ); + var q = new THREE.Quaternion().setFromEuler( eulerAngles, false ); var m = new THREE.Matrix4().makeRotationFromEuler( eulerAngles ); var q2 = new THREE.Quaternion().setFromRotationMatrix( m ); @@ -1716,17 +1915,17 @@ test( "multiplyQuaternions/multiply", function() { - var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; + var angles = [ new THREE.Euler( 1, 0, 0 ), new THREE.Euler( 0, 1, 0 ), new THREE.Euler( 0, 0, 1 ) ]; - var q1 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); - var q2 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); - var q3 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); + var q1 = new THREE.Quaternion().setFromEuler( angles[0], false ); + var q2 = new THREE.Quaternion().setFromEuler( angles[1], false ); + var q3 = new THREE.Quaternion().setFromEuler( angles[2], false ); var q = new THREE.Quaternion().multiplyQuaternions( q1, q2 ).multiply( q3 ); - var m1 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); - var m2 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); - var m3 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); + var m1 = new THREE.Matrix4().makeRotationFromEuler( angles[0] ); + var m2 = new THREE.Matrix4().makeRotationFromEuler( angles[1] ); + var m3 = new THREE.Matrix4().makeRotationFromEuler( angles[2] ); var m = new THREE.Matrix4().multiplyMatrices( m1, m2 ).multiply( m3 ); @@ -1737,13 +1936,13 @@ test( "multiplyVector3", function() { - var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; + var angles = [ new THREE.Euler( 1, 0, 0 ), new THREE.Euler( 0, 1, 0 ), new THREE.Euler( 0, 0, 1 ) ]; // ensure euler conversion for Quaternion matches that of Matrix4 for( var i = 0; i < orders.length; i ++ ) { for( var j = 0; j < angles.length; j ++ ) { - var q = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); - var m = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); + var q = new THREE.Quaternion().setFromEuler( angles[j], false ); + var m = new THREE.Matrix4().makeRotationFromEuler( angles[j] ); var v0 = new THREE.Vector3(1, 0, 0); var qv = v0.clone().applyQuaternion( q ); @@ -1773,6 +1972,7 @@ ok( b.equals( a ), "Passed!" ); }); + // -------------------------------------------- Ray test( "constructor/equals", function() { var a = new THREE.Ray(); @@ -1834,25 +2034,33 @@ test( "closestPointToPoint", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - // nearby the ray + // behind the ray var b = a.closestPointToPoint( zero3 ); - ok( b.equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + ok( b.equals( one3 ), "Passed!" ); + + // front of the ray + var c = a.closestPointToPoint( new THREE.Vector3( 0, 0, 50 ) ); + ok( c.equals( new THREE.Vector3( 1, 1, 50 ) ), "Passed!" ); // exactly on the ray - var c = a.closestPointToPoint( one3 ); - ok( c.equals( one3 ), "Passed!" ); + var d = a.closestPointToPoint( one3 ); + ok( d.equals( one3 ), "Passed!" ); }); test( "distanceToPoint", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - // nearby the ray + // behind the ray var b = a.distanceToPoint( zero3 ); - ok( b == Math.sqrt( 2 ), "Passed!" ); + ok( b === Math.sqrt( 3 ), "Passed!" ); + + // front of the ray + var c = a.distanceToPoint( new THREE.Vector3( 0, 0, 50 ) ); + ok( c === Math.sqrt( 2 ), "Passed!" ); // exactly on the ray - var c = a.distanceToPoint( one3 ); - ok( c == 0, "Passed!" ); + var d = a.distanceToPoint( one3 ); + ok( d === 0, "Passed!" ); }); test( "isIntersectionSphere", function() { @@ -1864,16 +2072,75 @@ var f = new THREE.Sphere( two3, 1 ); ok( ! a.isIntersectionSphere( b ), "Passed!" ); - ok( a.isIntersectionSphere( c ), "Passed!" ); + ok( ! a.isIntersectionSphere( c ), "Passed!" ); ok( a.isIntersectionSphere( d ), "Passed!" ); ok( ! a.isIntersectionSphere( e ), "Passed!" ); ok( ! a.isIntersectionSphere( f ), "Passed!" ); }); + test( "intersectSphere", function() { + + var TOL = 0.0001; + + // ray a0 origin located at ( 0, 0, 0 ) and points outward in negative-z direction + var a0 = new THREE.Ray( zero3.clone(), new THREE.Vector3( 0, 0, -1 ) ); + // ray a1 origin located at ( 1, 1, 1 ) and points left in negative-x direction + var a1 = new THREE.Ray( one3.clone(), new THREE.Vector3( -1, 0, 0 ) ); + + // sphere (radius of 2) located behind ray a0, should result in null + var b = new THREE.Sphere( new THREE.Vector3( 0, 0, 3 ), 2 ); + ok( a0.intersectSphere( b ) === null, "Passed!" ); + + // sphere (radius of 2) located in front of, but too far right of ray a0, should result in null + var b = new THREE.Sphere( new THREE.Vector3( 3, 0, -1 ), 2 ); + ok( a0.intersectSphere( b ) === null, "Passed!" ); + + // sphere (radius of 2) located below ray a1, should result in null + var b = new THREE.Sphere( new THREE.Vector3( 1, -2, 1 ), 2 ); + ok( a1.intersectSphere( b ) === null, "Passed!" ); + + // sphere (radius of 1) located to the left of ray a1, should result in intersection at 0, 1, 1 + var b = new THREE.Sphere( new THREE.Vector3( -1, 1, 1 ), 1 ); + ok( a1.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 1, 1 ) ) < TOL, "Passed!" ); + + // sphere (radius of 1) located in front of ray a0, should result in intersection at 0, 0, -1 + var b = new THREE.Sphere( new THREE.Vector3( 0, 0, -2 ), 1 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -1 ) ) < TOL, "Passed!" ); + + // sphere (radius of 2) located in front & right of ray a0, should result in intersection at 0, 0, -1, or left-most edge of sphere + var b = new THREE.Sphere( new THREE.Vector3( 2, 0, -1 ), 2 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -1 ) ) < TOL, "Passed!" ); + + // same situation as above, but move the sphere a fraction more to the right, and ray a0 should now just miss + var b = new THREE.Sphere( new THREE.Vector3( 2.01, 0, -1 ), 2 ); + ok( a0.intersectSphere( b ) === null, "Passed!" ); + + // following tests are for situations where the ray origin is inside the sphere + + // sphere (radius of 1) center located at ray a0 origin / sphere surrounds the ray origin, so the first intersect point 0, 0, 1, + // is behind ray a0. Therefore, second exit point on back of sphere will be returned: 0, 0, -1 + // thus keeping the intersection point always in front of the ray. + var b = new THREE.Sphere( zero3.clone(), 1 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -1 ) ) < TOL, "Passed!" ); + + // sphere (radius of 4) center located behind ray a0 origin / sphere surrounds the ray origin, so the first intersect point 0, 0, 5, + // is behind ray a0. Therefore, second exit point on back of sphere will be returned: 0, 0, -3 + // thus keeping the intersection point always in front of the ray. + var b = new THREE.Sphere( new THREE.Vector3( 0, 0, 1 ), 4 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -3 ) ) < TOL, "Passed!" ); + + // sphere (radius of 4) center located in front of ray a0 origin / sphere surrounds the ray origin, so the first intersect point 0, 0, 3, + // is behind ray a0. Therefore, second exit point on back of sphere will be returned: 0, 0, -5 + // thus keeping the intersection point always in front of the ray. + var b = new THREE.Sphere( new THREE.Vector3( 0, 0, -1 ), 4 ); + ok( a0.intersectSphere( b ).distanceTo( new THREE.Vector3( 0, 0, -5 ) ) < TOL, "Passed!" ); + + }); + test( "isIntersectionPlane", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - // parallel plane behind + // parallel plane in front of the ray var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, -1 ) ) ); ok( a.isIntersectionPlane( b ), "Passed!" ); @@ -1881,9 +2148,9 @@ var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 0 ) ) ); ok( a.isIntersectionPlane( c ), "Passed!" ); - // parallel plane infront + // parallel plane behind the ray var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 1 ) ) ); - ok( a.isIntersectionPlane( d ), "Passed!" ); + ok( ! a.isIntersectionPlane( d ), "Passed!" ); // perpendical ray that overlaps exactly var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); @@ -1899,15 +2166,15 @@ // parallel plane behind var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, -1 ) ); - ok( a.intersectPlane( b ).equals( new THREE.Vector3( 1, 1, -1 ) ), "Passed!" ); + ok( a.intersectPlane( b ) === null, "Passed!" ); // parallel plane coincident with origin var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, 0 ) ); - ok( a.intersectPlane( c ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + ok( a.intersectPlane( c ) === null, "Passed!" ); // parallel plane infront var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, 1 ) ); - ok( a.intersectPlane( d ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); + ok( a.intersectPlane( d ).equals( a.origin ), "Passed!" ); // perpendical ray that overlaps exactly var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); @@ -1915,21 +2182,21 @@ // perpendical ray that doesn't overlap var f = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), zero3 ); - ok( a.intersectPlane( f ) === undefined, "Passed!" ); + ok( a.intersectPlane( f ) === null, "Passed!" ); }); test( "applyMatrix4", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - var m = new THREE.Matrix4().identity(); + var m = new THREE.Matrix4(); ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); a = new THREE.Ray( zero3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - m.makeRotationAxis( new THREE.Vector3( 0, 0, 1 ), Math.PI ); + m.makeRotationZ( Math.PI ); ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); - m.identity().makeRotationX( Math.PI ); + m.makeRotationX( Math.PI ); var b = a.clone(); b.direction.negate(); var a2 = a.clone().applyMatrix4( m ); @@ -1944,6 +2211,80 @@ }); + test( "distanceSqToSegment", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + var ptOnLine = new THREE.Vector3(); + var ptOnSegment = new THREE.Vector3(); + + //segment in front of the ray + var v0 = new THREE.Vector3( 3, 5, 50 ); + var v1 = new THREE.Vector3( 50, 50, 50 ); // just a far away point + var distSqr = a.distanceSqToSegment( v0, v1, ptOnLine, ptOnSegment ); + + ok( ptOnSegment.distanceTo( v0 ) < 0.0001, "Passed!" ); + ok( ptOnLine.distanceTo( new THREE.Vector3(1, 1, 50) ) < 0.0001, "Passed!" ); + // ((3-1) * (3-1) + (5-1) * (5-1) = 4 + 16 = 20 + ok( Math.abs( distSqr - 20 ) < 0.0001, "Passed!" ); + + //segment behind the ray + v0 = new THREE.Vector3( -50, -50, -50 ); // just a far away point + v1 = new THREE.Vector3( -3, -5, -4 ); + distSqr = a.distanceSqToSegment( v0, v1, ptOnLine, ptOnSegment ); + + ok( ptOnSegment.distanceTo( v1 ) < 0.0001, "Passed!" ); + ok( ptOnLine.distanceTo( one3 ) < 0.0001, "Passed!" ); + // ((-3-1) * (-3-1) + (-5-1) * (-5-1) + (-4-1) + (-4-1) = 16 + 36 + 25 = 77 + ok( Math.abs( distSqr - 77 ) < 0.0001, "Passed!" ); + + //exact intersection between the ray and the segment + v0 = new THREE.Vector3( -50, -50, -50 ); + v1 = new THREE.Vector3( 50, 50, 50 ); + distSqr = a.distanceSqToSegment( v0, v1, ptOnLine, ptOnSegment ); + + ok( ptOnSegment.distanceTo( one3 ) < 0.0001, "Passed!" ); + ok( ptOnLine.distanceTo( one3 ) < 0.0001, "Passed!" ); + ok( distSqr < 0.0001, "Passed!" ); + }); + + test( "intersectBox", function() { + + var TOL = 0.0001; + + var box = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ); + + var a = new THREE.Ray( new THREE.Vector3( -2, 0, 0 ), new THREE.Vector3( 1, 0, 0) ); + //ray should intersect box at -1,0,0 + ok( a.isIntersectionBox(box) === true, "Passed!" ); + ok( a.intersectBox(box).distanceTo( new THREE.Vector3( -1, 0, 0 ) ) < TOL, "Passed!" ); + + var b = new THREE.Ray( new THREE.Vector3( -2, 0, 0 ), new THREE.Vector3( -1, 0, 0) ); + //ray is point away from box, it should not intersect + ok( b.isIntersectionBox(box) === false, "Passed!" ); + ok( b.intersectBox(box) === null, "Passed!" ); + + var c = new THREE.Ray( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0) ); + // ray is inside box, should return exit point + ok( c.isIntersectionBox(box) === true, "Passed!" ); + ok( c.intersectBox(box).distanceTo( new THREE.Vector3( 1, 0, 0 ) ) < TOL, "Passed!" ); + + var d = new THREE.Ray( new THREE.Vector3( 0, 2, 1 ), new THREE.Vector3( 0, -1, -1).normalize() ); + //tilted ray should intersect box at 0,1,0 + ok( d.isIntersectionBox(box) === true, "Passed!" ); + ok( d.intersectBox(box).distanceTo( new THREE.Vector3( 0, 1, 0 ) ) < TOL, "Passed!" ); + + var e = new THREE.Ray( new THREE.Vector3( 1, -2, 1 ), new THREE.Vector3( 0, 1, 0).normalize() ); + //handle case where ray is coplanar with one of the boxes side - box in front of ray + ok( e.isIntersectionBox(box) === true, "Passed!" ); + ok( e.intersectBox(box).distanceTo( new THREE.Vector3( 1, -1, 1 ) ) < TOL, "Passed!" ); + + var f = new THREE.Ray( new THREE.Vector3( 1, -2, 0 ), new THREE.Vector3( 0, -1, 0).normalize() ); + //handle case where ray is coplanar with one of the boxes side - box behind ray + ok( f.isIntersectionBox(box) === false, "Passed!" ); + ok( f.intersectBox(box) == null, "Passed!" ); + + }); + + // -------------------------------------------- Sphere test( "constructor", function() { var a = new THREE.Sphere(); ok( a.center.equals( zero3 ), "Passed!" ); @@ -2040,6 +2381,8 @@ ok( a.center.equals( zero3 ), "Passed!" ); }); + // -------------------------------------------- Triangle + test( "constructor", function() { var a = new THREE.Triangle(); ok( a.a.equals( zero3 ), "Passed!" ); @@ -2195,7 +2538,7 @@ ok( ! a.containsPoint( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); }); - + // -------------------------------------------- Vector2 test( "constructor", function() { var a = new THREE.Vector2(); ok( a.x == 0, "Passed!" ); @@ -2316,6 +2659,32 @@ c.clamp( b, a ); ok( c.x == -x, "Passed!" ); ok( c.y == y, "Passed!" ); + + c.set(-2*x, 2*x); + c.clampScalar( -x, x ); + equal( c.x, -x, "scalar clamp x" ); + equal( c.y, x, "scalar clamp y" ); + }); + + test( "rounding", function() { + deepEqual( new THREE.Vector2( -0.1, 0.1 ).floor(), new THREE.Vector2( -1, 0 ), "floor .1" ); + deepEqual( new THREE.Vector2( -0.5, 0.5 ).floor(), new THREE.Vector2( -1, 0 ), "floor .5" ); + deepEqual( new THREE.Vector2( -0.9, 0.9 ).floor(), new THREE.Vector2( -1, 0 ), "floor .9" ); + + deepEqual( new THREE.Vector2( -0.1, 0.1 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .1" ); + deepEqual( new THREE.Vector2( -0.5, 0.5 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .5" ); + deepEqual( new THREE.Vector2( -0.9, 0.9 ).ceil(), new THREE.Vector2( 0, 1 ), "ceil .9" ); + + deepEqual( new THREE.Vector2( -0.1, 0.1 ).round(), new THREE.Vector2( 0, 0 ), "round .1" ); + deepEqual( new THREE.Vector2( -0.5, 0.5 ).round(), new THREE.Vector2( 0, 1 ), "round .5" ); + deepEqual( new THREE.Vector2( -0.9, 0.9 ).round(), new THREE.Vector2( -1, 1 ), "round .9" ); + + deepEqual( new THREE.Vector2( -0.1, 0.1 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .1" ); + deepEqual( new THREE.Vector2( -0.5, 0.5 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .5" ); + deepEqual( new THREE.Vector2( -0.9, 0.9 ).roundToZero(), new THREE.Vector2( 0, 0 ), "roundToZero .9" ); + deepEqual( new THREE.Vector2( -1.1, 1.1 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.1" ); + deepEqual( new THREE.Vector2( -1.5, 1.5 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.5" ); + deepEqual( new THREE.Vector2( -1.9, 1.9 ).roundToZero(), new THREE.Vector2( -1, 1 ), "roundToZero 1.9" ); }); test( "negate", function() { @@ -2427,7 +2796,7 @@ ok( b.equals( a ), "Passed!" ); }); - + // -------------------------------------------- Vector3 test( "constructor", function() { var a = new THREE.Vector3(); ok( a.x == 0, "Passed!" ); @@ -2700,18 +3069,19 @@ }); test( "reflect", function() { - var a = new THREE.Vector3( 1, 0, 0 ); - var normal = new THREE.Vector3( 1, 0, 0 ); - var b = new THREE.Vector3( 0, 0, 0 ); + var a = new THREE.Vector3(); + var normal = new THREE.Vector3( 0, 1, 0 ); + var b = new THREE.Vector3(); - ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); + a.set( 0, -1, 0 ); + ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); a.set( 1, -1, 0 ); ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); a.set( 1, -1, 0 ); normal.set( 0, -1, 0 ); - ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( -1, -1, 0 ) ), "Passed!" ); + ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); }); test( "angleTo", function() { @@ -2768,7 +3138,7 @@ ok( b.equals( a ), "Passed!" ); }); - + // -------------------------------------------- Vector4 test( "constructor", function() { var a = new THREE.Vector4(); ok( a.x == 0, "Passed!" ); @@ -2897,9 +3267,9 @@ b.multiplyScalar( -2 ); ok( b.x == 2*x, "Passed!" ); - ok( b.y == 2*y, "Passed!" ); - ok( b.z == 2*z, "Passed!" ); - ok( b.w == 2*w, "Passed!" ); + ok( b.y == 2*y, "Passed!" ); + ok( b.z == 2*z, "Passed!" ); + ok( b.w == 2*w, "Passed!" ); a.divideScalar( -2 ); ok( a.x == x, "Passed!" ); @@ -3008,26 +3378,26 @@ }); /* - test( "distanceTo/distanceToSquared", function() { - var a = new THREE.Vector4( x, 0, 0, 0 ); - var b = new THREE.Vector4( 0, -y, 0, 0 ); - var c = new THREE.Vector4( 0, 0, z, 0 ); - var d = new THREE.Vector4( 0, 0, 0, -w ); - var e = new THREE.Vector4(); - - ok( a.distanceTo( e ) == x, "Passed!" ); - ok( a.distanceToSquared( e ) == x*x, "Passed!" ); + test( "distanceTo/distanceToSquared", function() { + var a = new THREE.Vector4( x, 0, 0, 0 ); + var b = new THREE.Vector4( 0, -y, 0, 0 ); + var c = new THREE.Vector4( 0, 0, z, 0 ); + var d = new THREE.Vector4( 0, 0, 0, -w ); + var e = new THREE.Vector4(); - ok( b.distanceTo( e ) == y, "Passed!" ); - ok( b.distanceToSquared( e ) == y*y, "Passed!" ); + ok( a.distanceTo( e ) == x, "Passed!" ); + ok( a.distanceToSquared( e ) == x*x, "Passed!" ); - ok( c.distanceTo( e ) == z, "Passed!" ); - ok( c.distanceToSquared( e ) == z*z, "Passed!" ); + ok( b.distanceTo( e ) == y, "Passed!" ); + ok( b.distanceToSquared( e ) == y*y, "Passed!" ); - ok( d.distanceTo( e ) == w, "Passed!" ); - ok( d.distanceToSquared( e ) == w*w, "Passed!" ); - }); - */ + ok( c.distanceTo( e ) == z, "Passed!" ); + ok( c.distanceToSquared( e ) == z*z, "Passed!" ); + + ok( d.distanceTo( e ) == w, "Passed!" ); + ok( d.distanceToSquared( e ) == w*w, "Passed!" ); + }); + */ test( "setLength", function() { diff --git a/threejs/tests/webgl/webgl_animation_skinning_morph.ts b/threejs/tests/webgl/webgl_animation_skinning_morph.ts new file mode 100644 index 000000000..ab588fad3 --- /dev/null +++ b/threejs/tests/webgl/webgl_animation_skinning_morph.ts @@ -0,0 +1,297 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_sprites.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var material: THREE.SpriteMaterial; + var geometry: THREE.JSonLoaderResultGeometry; + var dat:any; + // ------- + + var SCREEN_WIDTH = window.innerWidth; + var SCREEN_HEIGHT = window.innerHeight; + var FLOOR = -250; + + var container,stats; + + var camera, scene; + var renderer; + + var mesh, helper; + + var mouseX = 0, mouseY = 0; + + var windowHalfX = window.innerWidth / 2; + var windowHalfY = window.innerHeight / 2; + + var clock = new THREE.Clock(); + + document.addEventListener( 'mousemove', onDocumentMouseMove, false ); + + init(); + animate(); + + function init() { + + container = document.getElementById( 'container' ); + + camera = new THREE.PerspectiveCamera( 30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); + camera.position.z = 2200; + + scene = new THREE.Scene(); + + scene.fog = new THREE.Fog( 0xffffff, 2000, 10000 ); + + scene.add( camera ); + + // GROUND + + var groundMaterial = new THREE.MeshPhongMaterial( { emissive: 0xbbbbbb } ); + var planeGeometry = new THREE.PlaneGeometry( 16000, 16000 ); + + var ground = new THREE.Mesh( planeGeometry, groundMaterial ); + ground.position.set( 0, FLOOR, 0 ); + ground.rotation.x = -Math.PI/2; + scene.add( ground ); + + ground.receiveShadow = true; + + + // LIGHTS + + var ambient = new THREE.AmbientLight( 0x222222 ); + scene.add( ambient ); + + + var light = new THREE.DirectionalLight( 0xebf3ff, 1.6 ); + light.position.set( 0, 140, 500 ).multiplyScalar( 1.1 ); + scene.add( light ); + + light.castShadow = true; + + light.shadowMapWidth = 2048; + light.shadowMapHeight = 2048; + + var d = 390; + + light.shadowCameraLeft = -d * 2; + light.shadowCameraRight = d * 2; + light.shadowCameraTop = d * 1.5; + light.shadowCameraBottom = -d; + + light.shadowCameraFar = 3500; + //light.shadowCameraVisible = true; + + // + + var light = new THREE.DirectionalLight( 0x497f13, 1 ); + light.position.set( 0, -1, 0 ); + scene.add( light ); + + // RENDERER + + renderer = new THREE.WebGLRenderer( { antialias: true } ); + renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); + renderer.domElement.style.position = "relative"; + + renderer.setClearColor( scene.fog.color, 1 ); + + container.appendChild( renderer.domElement ); + + renderer.gammaInput = true; + renderer.gammaOutput = true; + + renderer.shadowMapEnabled = true; + + + // STATS + + stats = new Stats(); + container.appendChild( stats.domElement ); + + // + + var loader = new THREE.JSONLoader(); + loader.load( "models/skinned/knight.js", function ( geometry, materials ) { + + createScene( geometry, materials, 0, FLOOR, -300, 60 ) + + } ); + + // GUI + + initGUI(); + + // + + window.addEventListener( 'resize', onWindowResize, false ); + + } + + function onWindowResize() { + + windowHalfX = window.innerWidth / 2; + windowHalfY = window.innerHeight / 2; + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize( window.innerWidth, window.innerHeight ); + + } + + function ensureLoop( animation ) { + + for ( var i = 0; i < animation.hierarchy.length; i ++ ) { + + var bone = animation.hierarchy[ i ]; + + var first = bone.keys[ 0 ]; + var last = bone.keys[ bone.keys.length - 1 ]; + + last.pos = first.pos; + last.rot = first.rot; + last.scl = first.scl; + + } + + } + + function createScene( geometry, materials, x, y, z, s ) { + + ensureLoop( geometry.animation ); + + geometry.computeBoundingBox(); + var bb = geometry.boundingBox; + + var path = "textures/cube/Park2/"; + var format = '.jpg'; + var urls = [ + path + 'posx' + format, path + 'negx' + format, + path + 'posy' + format, path + 'negy' + format, + path + 'posz' + format, path + 'negz' + format + ]; + + + //var envMap = THREE.ImageUtils.loadTextureCube( urls ); + + //var map = THREE.ImageUtils.loadTexture( "textures/UV_Grid_Sm.jpg" ); + + //var bumpMap = THREE.ImageUtils.generateDataTexture( 1, 1, new THREE.Color() ); + //var bumpMap = THREE.ImageUtils.loadTexture( "textures/water.jpg" ); + + for ( var i = 0; i < materials.length; i ++ ) { + + var m = materials[ i ]; + m.skinning = true; + m.morphTargets = true; + + m.specular.setHSL( 0, 0, 0.1 ); + + m.color.setHSL( 0.6, 0, 0.6 ); + m.ambient.copy( m.color ); + + //m.map = map; + //m.envMap = envMap; + //m.bumpMap = bumpMap; + //m.bumpScale = 2; + + //m.combine = THREE.MixOperation; + //m.reflectivity = 0.75; + + m.wrapAround = true; + + } + + mesh = new THREE.SkinnedMesh( geometry, new THREE.MeshFaceMaterial( materials ) ); + mesh.position.set( x, y - bb.min.y * s, z ); + mesh.scale.set( s, s, s ); + scene.add( mesh ); + + mesh.castShadow = true; + mesh.receiveShadow = true; + + helper = new THREE.SkeletonHelper( mesh ); + helper.material.linewidth = 3; + helper.visible = false; + scene.add( helper ); + + var animation = new THREE.Animation( mesh, geometry.animation ); + animation.play(); + + } + + function initGUI() { + + var API = { + 'show model' : true, + 'show skeleton' : false + }; + + var gui = new dat.GUI(); + + gui.add( API, 'show model' ).onChange( function() { mesh.visible = API[ 'show model' ]; } ); + + gui.add( API, 'show skeleton' ).onChange( function() { helper.visible = API[ 'show skeleton' ]; } ); + + } + + function onDocumentMouseMove( event ) { + + mouseX = ( event.clientX - windowHalfX ); + mouseY = ( event.clientY - windowHalfY ); + + } + + // + + function animate() { + + requestAnimationFrame( animate ); + + render(); + stats.update(); + + } + + function render() { + + var delta = 0.75 * clock.getDelta(); + + camera.position.x += ( mouseX - camera.position.x ) * .05; + camera.position.y = THREE.Math.clamp( camera.position.y + ( - mouseY - camera.position.y ) * .05, 0, 1000 ); + + camera.lookAt( scene.position ); + + // update skinning + + THREE.AnimationHandler.update( delta ); + + if ( helper !== undefined ) helper.update(); + + // update morphs + + if ( mesh ) { + + var time = Date.now() * 0.001; + + // mouth + + mesh.morphTargetInfluences[ 1 ] = ( 1 + Math.sin( 4 * time ) ) / 2; + + // frown ? + + mesh.morphTargetInfluences[ 2 ] = ( 1 + Math.sin( 2 * time ) ) / 2; + + // eyes + + mesh.morphTargetInfluences[ 3 ] = ( 1 + Math.cos( 4 * time ) ) / 2; + + } + + renderer.render( scene, camera ); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_buffergeometry.ts b/threejs/tests/webgl/webgl_buffergeometry.ts index f8d455932..de4ad2aee 100644 --- a/threejs/tests/webgl/webgl_buffergeometry.ts +++ b/threejs/tests/webgl/webgl_buffergeometry.ts @@ -49,11 +49,6 @@ var geometry = new THREE.BufferGeometry(); - geometry.addAttribute('index', new Uint16Array(triangles * 3), 1); - geometry.addAttribute('position', new Float32Array(triangles * 3 * 3), 3); - geometry.addAttribute('normal', new Float32Array(triangles * 3 * 3), 3); - geometry.addAttribute('color', new Float32Array(triangles * 3 * 3), 3); - // break geometry into // chunks of 21,845 triangles (3 unique vertices per triangle) // for indices to fit into 16 bit integer number @@ -61,7 +56,7 @@ var chunkSize = 21845; - var indices = geometry.getAttribute('index').array; + var indices = new Uint16Array( triangles * 3 ); for (var i = 0; i < indices.length; i++) { @@ -69,9 +64,9 @@ } - var positions = geometry.getAttribute('position').array; - var normals = geometry.getAttribute('normal').array; - var colors = geometry.getAttribute('color').array; + var positions = new Float32Array( triangles * 3 * 3 ); + var normals = new Float32Array( triangles * 3 * 3 ); + var colors = new Float32Array( triangles * 3 * 3 ); var color = new THREE.Color(); @@ -167,6 +162,11 @@ } + geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) ); + geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + var offsets = triangles / chunkSize; for (var i = 0; i < offsets; i++) { diff --git a/threejs/tests/webgl/webgl_camera.ts b/threejs/tests/webgl/webgl_camera.ts index 4bf35883c..531d97fc4 100644 --- a/threejs/tests/webgl/webgl_camera.ts +++ b/threejs/tests/webgl/webgl_camera.ts @@ -85,7 +85,7 @@ } - var particles = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial({ color: 0x888888 })); + var particles = new THREE.PointCloud( geometry, new THREE.PointCloudMaterial( { color: 0x888888 } ) ); scene.add(particles); // diff --git a/threejs/tests/webgl/webgl_interactive_raycasting_pointcloud.ts b/threejs/tests/webgl/webgl_interactive_raycasting_pointcloud.ts new file mode 100644 index 000000000..330abd001 --- /dev/null +++ b/threejs/tests/webgl/webgl_interactive_raycasting_pointcloud.ts @@ -0,0 +1,335 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_sprites.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var material: THREE.SpriteMaterial; + var intersection: THREE.Intersection; + var container: HTMLElement; + var pcBuffer: THREE.PointCloud; + var v: any; + // ------- + + if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); + + var renderer, scene, camera, stats; + var pointclouds; + var projector, raycaster, intersects; + var mouse = { x: 1, y: 1 }; + var vector = new THREE.Vector3(); + intersection = null; + var spheres = []; + var spheresIndex = 0; + var clock; + + var threshold = 0.1; + var pointSize = 0.01; + var width = 150; + var length = 150; + var rotateY = new THREE.Matrix4().makeRotationY( 0.005 ); + + init(); + animate(); + + function generatePointCloudGeometry( color, width, length ){ + + var geometry = new THREE.BufferGeometry(); + var numPoints = width*length; + + var positions = new Float32Array( numPoints*3 ); + var colors = new Float32Array( numPoints*3 ); + + var k = 0; + + for( var i = 0; i < width; i++ ) { + + for( var j = 0; j < length; j++ ) { + + var u = i / width; + var v = j / length; + var x = u - 0.5; + var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8 ) ) / 20; + var z = v - 0.5; + + positions[ 3 * k ] = x; + positions[ 3 * k + 1 ] = y; + positions[ 3 * k + 2 ] = z; + + var intensity = ( y + 0.1 ) * 5; + colors[ 3 * k ] = color.r * intensity; + colors[ 3 * k + 1 ] = color.g * intensity; + colors[ 3 * k + 2 ] = color.b * intensity; + + k++; + + } + + } + + geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); + geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) ); + geometry.computeBoundingBox(); + + return geometry; + + } + + function generatePointcloud( color, width, length ) { + + var geometry = generatePointCloudGeometry( color, width, length ); + + var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); + var pointcloud = new THREE.PointCloud( geometry, material ); + + return pointcloud; + + } + + function generateIndexedPointcloud( color, width, length ) { + + var geometry = generatePointCloudGeometry( color, width, length ); + var numPoints = width * length; + var indices = new Uint16Array( numPoints ); + + var k = 0; + + for( var i = 0; i < width; i++ ) { + + for( var j = 0; j < length; j++ ) { + + indices[ k ] = k; + k++; + + } + + } + + geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + + var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); + var pointcloud = new THREE.PointCloud( geometry, material ); + + return pointcloud; + + } + + function generateIndexedWithOffsetPointcloud( color, width, length ){ + + var geometry = generatePointCloudGeometry( color, width, length ); + var numPoints = width * length; + var indices = new Uint16Array( numPoints ); + + var k = 0; + + for( var i = 0; i < width; i++ ){ + + for( var j = 0; j < length; j++ ) { + + indices[ k ] = k; + k++; + + } + + } + + geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) ); + + var offset = { start: 0, count: indices.length, index: 0 }; + geometry.offsets.push( offset ); + + var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); + var pointcloud = new THREE.PointCloud( geometry, material ); + + return pointcloud; + + } + + function generateRegularPointcloud( color, width, length ) { + + var geometry = new THREE.Geometry(); + var numPoints = width * length; + + var colors = []; + + var k = 0; + + for( var i = 0; i < width; i++ ) { + + for( var j = 0; j < length; j++ ) { + + var u = i / width; + v = j / length; + var x = u - 0.5; + var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8) ) / 20; + var z = v - 0.5; + v = new THREE.Vector3( x,y,z ); + + var intensity = ( y + 0.1 ) * 7; + colors[ 3 * k ] = color.r * intensity; + colors[ 3 * k + 1 ] = color.g * intensity; + colors[ 3 * k + 2 ] = color.b * intensity; + + geometry.vertices.push( v ); + colors[ k ] = ( color.clone().multiplyScalar( intensity ) ); + + k++; + + } + + } + + geometry.colors = colors; + geometry.computeBoundingBox(); + + var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } ); + var pointcloud = new THREE.PointCloud( geometry, material ); + + return pointcloud; + + } + + function init() { + + container = document.getElementById( 'container' ); + + scene = new THREE.Scene(); + + clock = new THREE.Clock(); + + camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); + camera.applyMatrix( new THREE.Matrix4().makeTranslation( 0,0,20 ) ); + camera.applyMatrix( new THREE.Matrix4().makeRotationX( -0.5 ) ); + + // + + pcBuffer = generatePointcloud( new THREE.Color( 1,0,0 ), width, length ); + pcBuffer.scale.set( 10,10,10 ); + pcBuffer.position.set( -5,0,5 ); + scene.add( pcBuffer ); + + var pcIndexed = generateIndexedPointcloud( new THREE.Color( 0,1,0 ), width, length ); + pcIndexed.scale.set( 10,10,10 ); + pcIndexed.position.set( 5,0,5 ); + scene.add( pcIndexed ); + + var pcIndexedOffset = generateIndexedWithOffsetPointcloud( new THREE.Color( 0,1,1 ), width, length ); + pcIndexedOffset.scale.set( 10,10,10 ); + pcIndexedOffset.position.set( 5,0,-5 ); + scene.add( pcIndexedOffset ); + + var pcRegular = generateRegularPointcloud( new THREE.Color( 1,0,1 ), width, length ); + pcRegular.scale.set( 10,10,10 ); + pcRegular.position.set( -5,0,-5 ); + scene.add( pcRegular ); + + pointclouds = [ pcBuffer, pcIndexed, pcIndexedOffset, pcRegular ]; + + // + + var sphereGeometry = new THREE.SphereGeometry( 0.1, 32, 32 ); + var sphereMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, shading: THREE.FlatShading } ); + + for ( var i = 0; i < 40; i++ ) { + + var sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); + scene.add( sphere ); + spheres.push( sphere ); + + } + + // + + renderer = new THREE.WebGLRenderer(); + renderer.setSize( window.innerWidth, window.innerHeight ); + + container.appendChild( renderer.domElement ); + + // + + projector = new THREE.Projector(); + raycaster = new THREE.Raycaster(); + raycaster.params.PointCloud.threshold = threshold; + + // + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild( stats.domElement ); + + // + + window.addEventListener( 'resize', onWindowResize, false ); + document.addEventListener( 'mousemove', onDocumentMouseMove, false ); + + } + + function onDocumentMouseMove( event ) { + + event.preventDefault(); + + mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; + mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize( window.innerWidth, window.innerHeight ); + + } + + function animate() { + + requestAnimationFrame( animate ); + + render(); + stats.update(); + + } + + var toggle = 0; + + function render() { + + camera.applyMatrix( rotateY ); + camera.updateMatrixWorld( true ); + + vector.set( mouse.x, mouse.y, 0.1 ); + + projector.unprojectVector( vector, camera ); + + raycaster.ray.set( camera.position, vector.sub( camera.position ).normalize() ); + + var intersections = raycaster.intersectObjects( pointclouds ); + intersection = ( intersections.length ) > 0 ? intersections[ 0 ] : null; + + if ( toggle > 0.02 && intersection !== null) { + + spheres[ spheresIndex ].position.copy( intersection.point ); + spheres[ spheresIndex ].scale.set( 1, 1, 1 ); + spheresIndex = ( spheresIndex + 1 ) % spheres.length; + + toggle = 0; + + } + + for ( var i = 0; i < spheres.length; i++ ) { + + var sphere = spheres[ i ]; + sphere.scale.multiplyScalar( 0.98 ); + sphere.scale.clampScalar( 0.01, 1 ); + + } + + toggle += clock.getDelta(); + + renderer.render( scene, camera ); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_lensflares.ts b/threejs/tests/webgl/webgl_lensflares.ts index c8e1bfed4..bb99d701c 100644 --- a/threejs/tests/webgl/webgl_lensflares.ts +++ b/threejs/tests/webgl/webgl_lensflares.ts @@ -116,7 +116,7 @@ lensFlare.add(textureFlare3, 70, 1.0, THREE.AdditiveBlending); lensFlare.customUpdateCallback = lensFlareUpdateCallback; - lensFlare.position = light.position; + lensFlare.position.copy( light.position ); scene.add(lensFlare); diff --git a/threejs/tests/webgl/webgl_materials.ts b/threejs/tests/webgl/webgl_materials.ts index 1f1dab70c..da1c311da 100644 --- a/threejs/tests/webgl/webgl_materials.ts +++ b/threejs/tests/webgl/webgl_materials.ts @@ -12,7 +12,7 @@ var container, stats; var camera, scene, renderer, objects; - var particleLight, pointLight; + var particleLight; var materials = []; @@ -130,8 +130,8 @@ scene.add(directionalLight); - pointLight = new THREE.PointLight(0xffffff, 1); - scene.add(pointLight); + var pointLight = new THREE.PointLight(0xffffff, 1); + particleLight.add(pointLight); // @@ -228,10 +228,6 @@ particleLight.position.y = Math.cos(timer * 5) * 400; particleLight.position.z = Math.cos(timer * 3) * 300; - pointLight.position.x = particleLight.position.x; - pointLight.position.y = particleLight.position.y; - pointLight.position.z = particleLight.position.z; - renderer.render(scene, camera); } diff --git a/threejs/tests/webgl/webgl_particles_billboards.ts b/threejs/tests/webgl/webgl_particles_billboards.ts index 8e786303d..a2f62fc6a 100644 --- a/threejs/tests/webgl/webgl_particles_billboards.ts +++ b/threejs/tests/webgl/webgl_particles_billboards.ts @@ -42,10 +42,10 @@ } - material = new THREE.ParticleSystemMaterial({ size: 35, sizeAttenuation: false, map: sprite, transparent: true }); + material = new THREE.PointCloudMaterial({ size: 35, sizeAttenuation: false, map: sprite, transparent: true }); material.color.setHSL(1.0, 0.3, 0.7); - particles = new THREE.ParticleSystem(geometry, material); + particles = new THREE.PointCloud(geometry, material); particles.sortParticles = true; scene.add(particles); diff --git a/threejs/tests/webgl/webgl_postprocessing.ts b/threejs/tests/webgl/webgl_postprocessing.ts index e3aaff31a..707804c28 100644 --- a/threejs/tests/webgl/webgl_postprocessing.ts +++ b/threejs/tests/webgl/webgl_postprocessing.ts @@ -80,8 +80,6 @@ requestAnimationFrame(animate); - var time = Date.now(); - object.rotation.x += 0.005; object.rotation.y += 0.01; diff --git a/threejs/three-tests.ts b/threejs/three-tests.ts index 4ff78b618..46a563a6d 100644 --- a/threejs/three-tests.ts +++ b/threejs/three-tests.ts @@ -26,12 +26,14 @@ THE SOFTWARE. // webGL renderer test. /// +/// /// /// /// /// /// /// +/// /// /// /// @@ -54,3 +56,4 @@ THE SOFTWARE. /// /// /// + diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 748900166..41a07f32b 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,4 +1,4 @@ -// Type definitions for three.js r67 +// Type definitions for three.js r68 // Project: http://mrdoob.github.com/three.js/ // Definitions by: Kon , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -174,6 +174,15 @@ declare module THREE { clone(camera?: Camera): Camera; } + export class CubeCamera extends Object3D { + constructor( near?: number, far?: number, cubeResolution?: number); + + renderTarget: WebGLRenderTargetCube; + + updateCubeMap( renderer: Renderer, scene: Scene ): void; + + } + /** * Camera with orthographic projection * @@ -326,43 +335,64 @@ declare module THREE { // Core /////////////////////////////////////////////////////////////////////////////////////////////// export class BufferAttribute { - constructor(); + constructor(array: any, itemSize: number); - set(value: number): void; - setX(index: number, x: number): void; - setY(index: number, y: number): void; - setZ(index: number, z: number): void; - setXY(index: number, x: number, y: number): void; - setXYZ(index: number, x: number, y: number, z: number): void; - setXYZW(index: number, x: number, y: number, z: number, w: number): void; + array: any; + itemSize: number; + length: number; + + set(value: number): BufferAttribute; + setX(index: number, x: number): BufferAttribute; + setY(index: number, y: number): BufferAttribute; + setZ(index: number, z: number): BufferAttribute; + setXY(index: number, x: number, y: number): BufferAttribute; + setXYZ(index: number, x: number, y: number, z: number): BufferAttribute; + setXYZW(index: number, x: number, y: number, z: number, w: number): BufferAttribute; } + // deprecated export class Int8Attribute extends BufferAttribute{ - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Uint8Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Uint8ClampedAttribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Int16Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Uint16Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Int32Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Uint32Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Float32Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } + + // deprecated export class Float64Attribute extends BufferAttribute { - constructor(size: number, itemSize: number); + constructor(data: any[], itemSize: number); } /** @@ -401,6 +431,8 @@ declare module THREE { */ applyMatrix(matrix: Matrix4): void; + fromGeometry( geometry: Geometry, settings?: any ): BufferGeometry; + /** * Computes bounding box of the geometry, updating Geometry.boundingBox attribute. * Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null. @@ -639,7 +671,7 @@ declare module THREE { export interface MorphColor { name: string; - color: Color[]; + colors: Color[]; } export interface MorphNormals { @@ -758,6 +790,11 @@ declare module THREE { */ skinIndices: number[]; + /** + * + */ + lineDistances: number[]; + /** * Bounding box. */ @@ -823,13 +860,18 @@ declare module THREE { /** * */ - lineDistances: number[]; + groupsNeedUpdate: boolean; /** * Bakes matrix transform directly into vertex coordinates. */ applyMatrix(matrix: Matrix4): void; + /** + * + */ + center(): Vector3; + /** * Computes face normals. */ @@ -899,6 +941,11 @@ declare module THREE { */ id: number; + /** + * + */ + uuid: number; + /** * Optional name of the object (doesn't need to be unique). */ @@ -914,6 +961,11 @@ declare module THREE { */ children: Object3D[]; + /** + * Up direction. + */ + up: Vector3; + /** * Object's local position. */ @@ -925,10 +977,9 @@ declare module THREE { rotation: Euler; /** - * Order of axis for Euler angles. + * Global rotation. */ - eulerOrder: string; - // eulerOrder:EulerOrder; + quaternion: Quaternion; /** * Object's local scale. @@ -936,9 +987,14 @@ declare module THREE { scale: Vector3; /** - * Up direction. + * Override depth-sorting order if non null. */ - up: Vector3; + renderDepth: number; + + /** + * When this is set, then the rotationMatrix gets calculated every frame. + */ + rotationAutoUpdate: boolean; /** * Local transform. @@ -946,19 +1002,19 @@ declare module THREE { matrix: Matrix4; /** - * Global rotation. + * The global transform of the object. If the Object3d has no parent, then it's identical to the local transform. */ - quaternion: Quaternion; + matrixWorld: Matrix4; /** - * Use quaternion instead of Euler angles for specifying local rotation. + * When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. */ - useQuaternion: boolean; + matrixAutoUpdate: boolean; /** - * Override depth-sorting order if non null. + * When this is set, it calculates the matrixWorld in that frame and resets this property to false. */ - renderDepth: number; + matrixWorldNeedsUpdate: boolean; /** * Object gets rendered if true. @@ -980,54 +1036,95 @@ declare module THREE { */ frustumCulled: boolean; - /** - * When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. - */ - matrixAutoUpdate: boolean; - - /** - * When this is set, it calculates the matrixWorld in that frame and resets this property to false. - */ - matrixWorldNeedsUpdate: boolean; - - /** - * When this is set, then the rotationMatrix gets calculated every frame. - */ - rotationAutoUpdate: boolean; - /** * An object that can be used to store custom data about the Object3d. It should not hold references to functions as these will not be cloned. */ userData: any; /** - * The global transform of the object. If the Object3d has no parent, then it's identical to the local transform. + * */ - matrixWorld: Matrix4; + static DefaultUp: Vector3; + /** + * Order of axis for Euler angles. + */ + eulerOrder: string; + // eulerOrder:EulerOrder; + + /** + * Use quaternion instead of Euler angles for specifying local rotation. + */ + useQuaternion: boolean; + /** * This updates the position, rotation and scale with the matrix. */ applyMatrix(matrix: Matrix4): void; + /** + * + */ + setRotationFromAxisAngle(axis: Vector3, angle: number): void; + + /** + * + */ + setRotationFromEuler(euler: Euler ): void; + + /** + * + */ + setRotationFromMatrix(m: Matrix4): void; + + /** + * + */ + setRotationFromQuaternion( q: Quaternion ): void; + + /** + * + * @param angle + */ + rotateX(angle: number): Object3D; + + /** + * + * @param angle + */ + rotateY(angle: number): Object3D; + + /** + * + * @param angle + */ + rotateZ(angle: number): Object3D; + + /** + * + * @param distance + * @param axis + */ + translate( distance: number, axis: Vector3 ): Object3D; + /** * Translates object along x axis by distance. * @param distance Distance. */ - translateX(distance: number): void; + translateX(distance: number): Object3D; /** * Translates object along y axis by distance. * @param distance Distance. */ - translateY(distance: number): void; + translateY(distance: number): Object3D; /** * Translates object along z axis by distance. * @param distance Distance. */ - translateZ(distance: number): void; + translateZ(distance: number): Object3D; /** * Updates the vector from local space to world space. @@ -1057,6 +1154,11 @@ declare module THREE { */ remove(object: Object3D): void; + /** + * + */ + raycast(raycaster: Raycaster, intersects: any): void; + /** * Translates object along arbitrary axis by distance. * @param distance Distance. @@ -1065,10 +1167,22 @@ declare module THREE { traverse(callback: (object: Object3D) => any): void; /** - * Searches whole subgraph recursively to add all objects in the array. - * @param array optional argument that returns the the array with descendants. + * Searches through the object's children and returns the first with a matching id, optionally recursive. + * @param id Unique number of the object instance + * @param recursive Boolean whether to search through the children's children. Default is false. */ - getDescendants(array?: Object3D[]): Object3D[]; + getObjectById(id: string, recursive: boolean): Object3D; + + + /** + * Searches through the object's children and returns the first with a matching name, optionally recursive. + * @param name String to match to the children's Object3d.name property. + * @param recursive Boolean whether to search through the children's children. Default is false. + */ + getObjectByName(name: string, recursive: boolean): Object3D; + + + getChildByName( name: string, recursive: boolean ): Object3D; /** * Updates local transform. @@ -1080,22 +1194,13 @@ declare module THREE { */ updateMatrixWorld(force: boolean): void; + /** + * + * @param object + * @param recursive + */ clone(object?: Object3D, recursive?: boolean): Object3D; - /** - * Searches through the object's children and returns the first with a matching name, optionally recursive. - * @param name String to match to the children's Object3d.name property. - * @param recursive Boolean whether to search through the children's children. Default is false. - */ - getObjectByName(name: string, recursive: boolean): Object3D; - - /** - * Searches through the object's children and returns the first with a matching id, optionally recursive. - * @param id Unique number of the object instance - * @param recursive Boolean whether to search through the children's children. Default is false. - */ - getObjectById(id: string, recursive: boolean): Object3D; - /** * @param axis A normalized vector in object space. * @param distance The distance to translate. @@ -1148,12 +1253,22 @@ declare module THREE { object: Object3D; } + export interface RaycasterParameters { + Sprite?: any; + Mesh?: any; + PointCloud?: any; + LOD?: any; + Line?: any; + } + export class Raycaster { constructor(origin?: Vector3, direction?: Vector3, near?: number, far?: number); ray: Ray; near: number; far: number; + params: RaycasterParameters; precision: number; + linePrecision: number; set(origin: Vector3, direction: Vector3): void; intersectObject(object: Object3D, recursive?: boolean): Intersection[]; intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[]; @@ -1609,17 +1724,34 @@ declare module THREE { initMaterials(materials: Material[], texturePath: string): Material[]; extractUrlBase(url: string): string; addStatusElement(): HTMLElement; + + static Handlers:LoaderHandler; + } + + export interface LoaderHandler{ + handlers:any[]; + add(regex:string, loader:Loader):void; + get(file: string):Loader; } export class BufferGeometryLoader { constructor(manager?: LoadingManager); - load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void): void; + load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; setCrossOrigin(crossOrigin: string): void; parse(json: any): BufferGeometry; } + export class GeometryLoader { + constructor(manager?: LoadingManager); + + load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + setCrossOrigin(crossOrigin: string): void; + parse(json: any): Geometry; + + } + export class Cache{ constructor(); @@ -1659,12 +1791,16 @@ declare module THREE { * @param callback. This function will be called with the loaded model as an instance of geometry when the load is completed. * @param texturePath If not specified, textures will be assumed to be in the same folder as the Javascript model file. */ - load(url: string, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string): void; + load(url: string, callback: (geometry: JSonLoaderResultGeometry, materials: Material[]) => void , texturePath?: string): void; parse(json:string, texturePath:string): any; loadAjaxJSON(context: JSONLoader, url: string, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string, callbackProgress?: (progress: Progress) => void ): void; } + export class JSonLoaderResultGeometry extends Geometry { + animation: AnimationData; + } + /** * Handles and keeps track of loaded and pending data. */ @@ -1713,76 +1849,6 @@ declare module THREE { parseObject(data: any, geometries: any[], materials: Material[]): T; } - interface SceneLoaderResult{ - scene: Scene; - geometries: {[id:string]:Geometry;}; - face_materials: {[id:string]:Material;}; - materials: {[id:string]:Material;}; - textures: {[id:string]:Texture;}; - objects: {[id:string]:Object3D;}; - cameras: {[id:string]:Camera;}; - lights: {[id:string]:Light;}; - fogs: {[id:string]:IFog;}; - empties: {[id:string]:any;}; - groups: {[id:string]:any;}; - } - - interface SceneLoaderProgress{ - totalModels: number; - totalTextures: number; - loadedModels: number; - loadedTextures: number; - } - - /** - * A loader for loading a complete scene out of a JSON file. - */ - export class SceneLoader { - constructor(); - - /** - * Will be called when load starts. - * The default is a function with empty body. - */ - onLoadStart: () => void; - - /** - * Will be called while load progresses. - * The default is a function with empty body. - */ - onLoadProgress: () => void; - - /** - * Will be called when each element in the scene completes loading. - * The default is a function with empty body. - */ - onLoadComplete: () => void; - - /** - * Will be called when load completes. - * The default is a function with empty body. - */ - callbackSync: (result: SceneLoaderResult) => void; - - /** - * Will be called as load progresses. - * The default is a function with empty body. - */ - callbackProgress: (progress: SceneLoaderProgress, result: SceneLoaderResult) => void; - hierarchyHandlers: any; - geometryHandlers: any; - - /** - * @param url - * @param callbackFinished This function will be called with the loaded model as an instance of scene when the load is completed. - */ - load(url: string, onLoad: (result: SceneLoaderResult) => void): void; - setCrossOrigin(crossOrigin: string): void; - addHierarchyHandler(typeID: string, loaderClass: any): void; - parse(json: any, callbackFinished: (result: SceneLoaderResult) => void, url: string): void; - addGeometryHandler(typeID: string, loaderClass: any): void; - } - /** * Class for loading a texture. * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. @@ -1804,9 +1870,11 @@ declare module THREE { cache: Cache; crossOrigin: string; + responseType: string; load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; setCrossOrigin(crossOrigin: string): void; + setResponseType(responseType: string): void; } // Materials ////////////////////////////////////////////////////////////////////////////////// @@ -1977,6 +2045,7 @@ declare module THREE { fog?: boolean; lightMap?: Texture; specularMap?: Texture; + alphaMap?: Texture; envMap?: Texture; skinning?: boolean; morphTargets?: boolean; @@ -1999,6 +2068,7 @@ declare module THREE { fog: boolean; lightMap: Texture; specularMap: Texture; + alphaMap: Texture; envMap: Texture; skinning: boolean; morphTargets: boolean; @@ -2044,6 +2114,7 @@ declare module THREE { map?: Texture; lightMap?: Texture; specularMap?: Texture; + alphaMap?: Texture; envMap?: Texture; reflectivity?: number; refractionRatio?: number; @@ -2070,6 +2141,7 @@ declare module THREE { map: Texture; lightMap: Texture; specularMap: Texture; + alphaMap: Texture; envMap: Texture; reflectivity: number; refractionRatio: number; @@ -2116,6 +2188,7 @@ declare module THREE { map?: Texture; lightMap?: Texture; specularMap?: Texture; + alphaMap?: Texture; envMap?: Texture; reflectivity?: number; refractionRatio?: number; @@ -2150,6 +2223,7 @@ declare module THREE { map: Texture; lightMap: Texture; specularMap: Texture; + alphaMap: Texture; envMap: Texture; reflectivity: number; refractionRatio: number; @@ -2169,17 +2243,17 @@ declare module THREE { clone(): MeshPhongMaterial; } - export interface ParticleSystemMaterialParameters { + export interface PointCloudMaterialParameters { color?: number; map?: Texture; size?: number; sizeAttenuation?: boolean; - vertexColors?: boolean; + vertexColors?: Colors; fog?: boolean; } - export class ParticleSystemMaterial extends Material { - constructor(parameters?: ParticleSystemMaterialParameters); + export class PointCloudMaterial extends Material { + constructor(parameters?: PointCloudMaterialParameters); color: Color; map: Texture; size: number; @@ -2187,7 +2261,17 @@ declare module THREE { vertexColors: boolean; fog: boolean; - clone(): ParticleSystemMaterial; + clone(): PointCloudMaterial; + } + + // deprecated + export class ParticleBasicMaterial extends PointCloudMaterial{ + + } + + // deprecated + export class ParticleSystemMaterial extends PointCloudMaterial{ + } export class RawShaderMaterial extends ShaderMaterial { @@ -2337,6 +2421,7 @@ declare module THREE { distanceToPoint(point: Vector3): number; containsPoint(point: Vector3): boolean; setFromCenterAndSize(center: Vector3, size: number): Box3; + setFromObject(object: Object3D): Box3; } export interface HSL { @@ -2466,6 +2551,157 @@ declare module THREE { clone(): Color; } + export class ColorKeywords { + static test2: string; + static aliceblue: string; + static antiquewhite: string; + static aqua: string; + static aquamarine: string; + static azure: string; + static beige: string; + static bisque: string; + static black: string; + static blanchedalmond: string; + static blue: string; + static blueviolet: string; + static brown: string; + static burlywood: string; + static cadetblue: string; + static chartreuse: string; + static chocolate: string; + static coral: string; + static cornflowerblue: string; + static cornsilk: string; + static crimson: string; + static cyan: string; + static darkblue: string; + static darkcyan: string; + static darkgoldenrod: string; + static darkgray: string; + static darkgreen: string; + static darkgrey: string; + static darkkhaki: string; + static darkmagenta: string; + static darkolivegreen: string; + static darkorange: string; + static darkorchid: string; + static darkred: string; + static darksalmon: string; + static darkseagreen: string; + static darkslateblue: string; + static darkslategray: string; + static darkslategrey: string; + static darkturquoise: string; + static darkviolet: string; + static deeppink: string; + static deepskyblue: string; + static dimgray: string; + static dimgrey: string; + static dodgerblue: string; + static firebrick: string; + static floralwhite: string; + static forestgreen: string; + static fuchsia: string; + static gainsboro: string; + static ghostwhite: string; + static gold: string; + static goldenrod: string; + static gray: string; + static green: string; + static greenyellow: string; + static grey: string; + static honeydew: string; + static hotpink: string; + static indianred: string; + static indigo: string; + static ivory: string; + static khaki: string; + static lavender: string; + static lavenderblush: string; + static lawngreen: string; + static lemonchiffon: string; + static lightblue: string; + static lightcoral: string; + static lightcyan: string; + static lightgoldenrodyellow: string; + static lightgray: string; + static lightgreen: string; + static lightgrey: string; + static lightpink: string; + static lightsalmon: string; + static lightseagreen: string; + static lightskyblue: string; + static lightslategray: string; + static lightslategrey: string; + static lightsteelblue: string; + static lightyellow: string; + static lime: string; + static limegreen: string; + static linen: string; + static magenta: string; + static maroon: string; + static mediumaquamarine: string; + static mediumblue: string; + static mediumorchid: string; + static mediumpurple: string; + static mediumseagreen: string; + static mediumslateblue: string; + static mediumspringgreen: string; + static mediumturquoise: string; + static mediumvioletred: string; + static midnightblue: string; + static mintcream: string; + static mistyrose: string; + static moccasin: string; + static navajowhite: string; + static navy: string; + static oldlace: string; + static olive: string; + static olivedrab: string; + static orange: string; + static orangered: string; + static orchid: string; + static palegoldenrod: string; + static palegreen: string; + static paleturquoise: string; + static palevioletred: string; + static papayawhip: string; + static peachpuff: string; + static peru: string; + static pink: string; + static plum: string; + static powderblue: string; + static purple: string; + static red: string; + static rosybrown: string; + static royalblue: string; + static saddlebrown: string; + static salmon: string; + static sandybrown: string; + static seagreen: string; + static seashell: string; + static sienna: string; + static silver: string; + static skyblue: string; + static slateblue: string; + static slategray: string; + static slategrey: string; + static snow: string; + static springgreen: string; + static steelblue: string; + static tan: string; + static teal: string; + static thistle: string; + static tomato: string; + static turquoise: string; + static violet: string; + static wheat: string; + static white: string; + static whitesmoke: string; + static yellow: string; + static yellowgreen: string; + } + export class Euler { constructor(x?: number, y?: number, z?: number, order?: string); @@ -2701,17 +2937,10 @@ declare module THREE { * m.multiply( m3 ); */ export class Matrix4 implements Matrix { - - /** - * Creates an identity matrix. - */ - constructor(); - - /** * Initialises the matrix with the supplied n11..n44 values. */ - constructor(n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number); + constructor(n11?: number, n12?: number, n13?: number, n14?: number, n21?: number, n22?: number, n23?: number, n24?: number, n31?: number, n32?: number, n33?: number, n34?: number, n41?: number, n42?: number, n43?: number, n44?: number); /** * Float32Array with matrix values. @@ -2936,11 +3165,11 @@ declare module THREE { * Copies values of q to this quaternion. */ copy(q: Quaternion): Quaternion; - setFromEuler(euler: Euler, update?: boolean): Quaternion; + /** * Sets this quaternion from rotation specified by Euler angles. */ - setFromEuler(v: Vector3, order: string): Quaternion; + setFromEuler(euler: Euler, update?: boolean): Quaternion; /** * Sets this quaternion from rotation specified by axis and angle. @@ -2997,6 +3226,8 @@ declare module THREE { equals(v: Quaternion): boolean; + dot(v: Vector3): number; + lengthSq(): number; fromArray(n: number[]): Quaternion; @@ -3021,10 +3252,12 @@ declare module THREE { equals(ray: Ray): boolean; intersectBox(box: Box3, optionalTarget?: Vector3): Vector3; intersectPlane(plane: Plane, optionalTarget?: Vector3): Vector3; + intersectSphere(sphere: Sphere, optionalTarget?: Vector3): Vector3; intersectTriangle(a: Vector3, b: Vector3, c: Vector3, backfaceCulling: boolean, optionalTarget?: Vector3): Vector3; isIntersectionBox(box: Box3): boolean; isIntersectionPlane(plane: Plane): boolean; isIntersectionSphere(sphere: Sphere): boolean; + recast(t: number): Ray; set(origin: Vector3, direction: Vector3): Ray; } @@ -3296,6 +3529,8 @@ declare module THREE { */ negate(): Vector2; + + /** * Computes dot product of this vector and v. */ @@ -3715,14 +3950,13 @@ declare module THREE { export class Bone extends Object3D { constructor(belongsToSkin: SkinnedMesh); - skinMatrix: Matrix4; skin: SkinnedMesh; accumulatedRotWeight: number; accumulatedPosWeight: number; accumulatedSclWeight: number; - update(parentSkinMatrix?: Matrix4, forceUpdate?: boolean): void; + update(forceUpdate?: boolean): void; } export class Line extends Object3D { @@ -3733,8 +3967,10 @@ declare module THREE { constructor(geometry?: BufferGeometry, material?: LineBasicMaterial, type?: number); constructor(geometry?: BufferGeometry, material?: ShaderMaterial, type?: number); geometry: Geometry; - material: Material; + material: LineBasicMaterial; type: LineType; + + raycast(raycaster: Raycaster, intersects: any): void; clone(object?: Line): Line; } @@ -3748,6 +3984,7 @@ declare module THREE { objects: any[]; addLevel(object: Object3D, distance?: number): void; getObjectForDistance(distance: number): Object3D; + raycast(raycaster: Raycaster, intersects: any): void; update(camera: Camera): void; clone(): LOD; } @@ -3761,6 +3998,7 @@ declare module THREE { getMorphTargetIndexByName(name: string): number; updateMorphTargets(): void; + raycast(raycaster: Raycaster, intersects: any): void; clone(object?: Mesh): Mesh; } @@ -3791,7 +4029,7 @@ declare module THREE { parseAnimations(): void; updateAnimation(delta: number): void; setAnimationLabel(label: string, start: number, end: number): void; - + interpolateTargets( a: number, b: number, t: number ): void; clone(object?: MorphAnimMesh): MorphAnimMesh; } @@ -3800,15 +4038,15 @@ declare module THREE { * * @see src/objects/ParticleSystem.js */ - export class ParticleSystem extends Object3D { + export class PointCloud extends Object3D { /** * @param geometry An instance of Geometry. * @param material An instance of Material (optional). */ - constructor(geometry: Geometry, material?: ParticleSystemMaterial); + constructor(geometry: Geometry, material?: PointCloudMaterial); constructor(geometry: Geometry, material?: ShaderMaterial); - constructor(geometry: BufferGeometry, material?: ParticleSystemMaterial); + constructor(geometry: BufferGeometry, material?: PointCloudMaterial); constructor(geometry: BufferGeometry, material?: ShaderMaterial); /** @@ -3821,24 +4059,21 @@ declare module THREE { */ material: Material; - /** - * Specifies whether the particle system will be culled if it's outside the camera's frustum. By default this is set to false. - */ - frustrumCulled: boolean; - sortParticles: boolean; - clone(object?: ParticleSystem): ParticleSystem; + raycast(raycaster: Raycaster, intersects: any): void; + clone(object?: PointCloud): PointCloud; } export class Skeleton extends Mesh { - constructor(boneList: Bone[], useVertexTexture: boolean); + constructor(bones: Bone[], boneInverses?: Matrix4[], useVertexTexture?: boolean); bones: Bone[]; useVertexTexture: boolean; boneMatrices: Float32Array; - addBone(bone: Bone): Bone; calculateInverses(bone: Bone): void; + pose(): void; + update(): void; } export class SkinnedMesh extends Mesh { @@ -3850,10 +4085,14 @@ declare module THREE { constructor(geometry?: Geometry, material?: MeshPhongMaterial, useVertexTexture?: boolean); constructor(geometry?: Geometry, material?: ShaderMaterial, useVertexTexture?: boolean); - identityMatrix: Matrix4; + bindMode: string; + bindMatrix: Matrix4; + bindMatrixInverse: Matrix4; + bind( skeleton: Skeleton, bindMatrix?: Matrix4 ): void; pose(): void; normalizeSkinWeights(): void; + updateMatrixWorld(force?: boolean): void; clone(object?: SkinnedMesh): SkinnedMesh; } @@ -3863,6 +4102,7 @@ declare module THREE { geometry: BufferGeometry; material: SpriteMaterial; + raycast(raycaster: Raycaster, intersects: any): void; updateMatrix(): void; clone(object?: Sprite): Sprite; } @@ -3899,6 +4139,8 @@ declare module THREE { supportsVertexTextures(): void; setSize(width: number, height: number, updateStyle?: boolean): void; setClearColorHex(hex: number, alpha?: number): void; + getClearColor(): Color; + getClearAlpha(): number; setViewport(x: number, y: number, width: number, height: number): void; } @@ -4319,6 +4561,7 @@ declare module THREE { copy(vertex: RenderableVertex): void; } + // Renderers / Shaders ///////////////////////////////////////////////////////////////////// // Renderers / Shaders ///////////////////////////////////////////////////////////////////// export interface ShaderChunk { [name: string]: string; @@ -4514,6 +4757,24 @@ declare module THREE { clone(): CompressedTexture; } + export class CubeTexture extends Texture { + constructor( + images: any[], // HTMLImageElement or HTMLCanvasElement + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + images: any[]; + + clone(texture?: CubeTexture): CubeTexture; + } + export class DataTexture extends Texture { constructor( data: ImageData, @@ -4601,6 +4862,9 @@ declare module THREE { clone(): Texture; dispose(): void; + + DEFAULT_IMAGE: any; + DEFAULT_MAPPING: any; } // Extras ///////////////////////////////////////////////////////////////////// @@ -4634,12 +4898,11 @@ declare module THREE { export var GeometryUtils: { // DEPRECATED merge(geometry1: Geometry, object2: Mesh, materialIndexOffset?: number): void; + // DEPRECATED merge(geometry1: Geometry, object2: Geometry, materialIndexOffset?: number): void; - randomPointInTriangle(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): Vector3; - randomPointInFace(face: Face3, geometry: Geometry, useCachedAreas: boolean): Vector3; - randomPointsInGeometry(geometry: Geometry, points: number): Vector3; - triangleArea(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): number; + + // DEPRECATED center(geometry: Geometry): Vector3; }; @@ -4647,12 +4910,9 @@ declare module THREE { crossOrigin: string; generateDataTexture(width: number, height: number, color: Color): DataTexture; - parseDDS(buffer: ArrayBuffer, loadMipmaps: boolean): { mipmaps: { data: Uint8Array; width: number; height: number; }[]; width: number; height: number; format: number; mipmapCount: number; }; - loadCompressedTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; loadTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; - getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; - loadCompressedTextureCube(array: string[], mapping?: Mapping, onLoad?: () => void, onError?: (message: string) => void): Texture; loadTextureCube(array: string[], mapping?: Mapping, onLoad?: () => void , onError?: (message: string) => void ): Texture; + getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; }; export var SceneUtils: { @@ -4684,7 +4944,7 @@ declare module THREE { } export class Animation { - constructor(root: Mesh, name: string); + constructor(root: Mesh, data: AnimationData); root: Mesh; data: AnimationData; @@ -4692,37 +4952,37 @@ declare module THREE { currentTime: number; timeScale: number; isPlaying: boolean; - isPaused: boolean; loop: boolean; weight: number; - interpolationType: AnimationInterpolation; keyTypes: string[]; play(startTime?: number, weight?: number): void; - pause(): void; stop(): void; reset(): void; update(deltaTimeMS: number): void; - interpolateCatmullRom(points: Vector3[], scale: number): Vector3[]; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number, t2: number, t3: number): number; - getNextKeyWith(type: string, h: number, key: number): KeyFrame; // ???? + getNextKeyWith(type: string, h: number, key: number): KeyFrame; getPrevKeyWith(type: string, h: number, key: number): KeyFrame; } - export class AnimationInterpolation { } - export var AnimationHandler: { - CATMULLROM: AnimationInterpolation; - CATMULLROM_FORWARD: AnimationInterpolation; - LINEAR: AnimationInterpolation; + LINEAR: number; + CATMULLROM: number; + CATMULLROM_FORWARD: number; - remove(name: string): void; - removeFromUpdate(animation: Animation): void; - get(name: string): AnimationData; - update(deltaTimeMS: number): void; + animations: any[]; + + init(data: Animation): void; parse(root: Mesh): Object3D[]; + play(animation: Animation): void; + stop(animation: Animation): void; + update(deltaTimeMS: number): void; + + // deprecated add(data: AnimationData): void; - addToUpdate(animation: Animation): void; + // deprecated + get(name: string): AnimationData; + // deprecated + remove(name: string): void; }; export class MorphAnimation { @@ -4741,7 +5001,7 @@ declare module THREE { } export class KeyFrameAnimation { - constructor(root: Mesh, data: any, JITCompile?: boolean); + constructor(data: any); root: Mesh; data: Object; @@ -4753,55 +5013,13 @@ declare module THREE { loop: number; JITCompile: boolean; - play(loop?: number, startTimeMS?: number): void; - pause(): void; + play(startTime?: number): void; stop(): void; - update(deltaTimeMS: number): void; - interpolateCatmullRom(points: Vector3[], scale: number): Vector3[]; - getNextKeyWith(type: string, h: number, key: number): KeyFrame; // ???? + update(delta: number): void; + getNextKeyWith(type: string, h: number, key: number): KeyFrame; getPrevKeyWith(type: string, h: number, key: number): KeyFrame; } - // Extras / Cameras ///////////////////////////////////////////////////////////////////// - - export class CombinedCamera extends Camera { - constructor(width: number, height: number, fov: number, near: number, far: number, orthoNear: number, orthoFar: number); - - fov: number; - right: number; - bottom: number; - cameraP: PerspectiveCamera; - top: number; - zoom: number; - far: number; - near: number; - inPerspectiveMode: boolean; - cameraO: OrthographicCamera; - inOrthographicMode: boolean; - left: number; - - toBottomView(): void; - setFov(fov: number): void; - toBackView(): void; - setZoom(zoom: number): void; - setLens(focalLength: number, frameHeight?: number): number; - toFrontView(): void; - toLeftView(): void; - updateProjectionMatrix(): void; - toTopView(): void; - toOrthographic(): void; - setSize(width: number, height: number): void; - toPerspective(): void; - toRightView(): void; - } - - export class CubeCamera extends Object3D { - constructor(near: number, far: number, cubeResolution: number); - - renderTarget: WebGLRenderTargetCube; - updateCubeMap(renderer: Renderer, scene: Scene): void; - } - // Extras / Curves ///////////////////////////////////////////////////////////////////// export class ArcCurve extends EllipseCurve { constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); @@ -5310,11 +5528,13 @@ declare module THREE { } export class SkeletonHelper extends Line { - constructor(bone: Bone); + constructor(bone: Object3D); - skeleton: Skeleton; + bones: Bone[]; + root: Object3D; + matrixWorld: Matrix4; matrixAutoUpdate: boolean; - + getBoneList(object: Object3D): Bone[]; update(): void; } From 1086c1fac6fcbd8f7455aa78d4e7e66d6c1e9051 Mon Sep 17 00:00:00 2001 From: Evgenus Date: Sun, 3 Aug 2014 15:16:57 +0300 Subject: [PATCH 100/167] definitions for BigInt by Baird Leemon. distribution source: https://github.com/Evgenus/BigInt original source: http://www.leemon.com/crypto/BigInt.html --- CONTRIBUTORS.md | 1 + bigint/bigint-tests.ts | 81 ++++++++++++++ bigint/bigint.d.ts | 245 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 bigint/bigint-tests.ts create mode 100644 bigint/bigint.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..eab14f2c5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -31,6 +31,7 @@ All definitions files include a header with the author and editors, so at some p * [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm)) * [big.js](https://github.com/MikeMcl/big.js) (by [Steve Ognibene](https://github.com/nycdotnet)) +* [BigInt](https://github.com/Evgenus/BigInt) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [BigInteger](https://github.com/peterolson/BigInteger.js) (by [Ingo Bürk](https://github.com/Airblader)) * [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg)) * [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds)) diff --git a/bigint/bigint-tests.ts b/bigint/bigint-tests.ts new file mode 100644 index 000000000..8ccf2ba4b --- /dev/null +++ b/bigint/bigint-tests.ts @@ -0,0 +1,81 @@ +/// + +var bi: BigInt.BigInt; +var num: number; +var str: string; +var b: boolean; + +BigInt.setRandom(() => { return 0; }); + +bi = BigInt.add(bi, bi); +bi = BigInt.addInt(bi, num); +str = BigInt.bigInt2str(bi, num); +str = BigInt.bigInt2str(bi, str); +num = BigInt.bitSize(bi); +bi = BigInt.dup(bi); +b = BigInt.equals(bi, bi); +b = BigInt.equalsInt(bi, num); +bi = BigInt.expand(bi, num); +var nums: number[] = BigInt.findPrimes(num); +bi = BigInt.GCD(bi, bi); +b = BigInt.greater(bi, bi); +b = BigInt.greaterShift(bi, bi, num); +bi = BigInt.int2bigInt(0); +bi = BigInt.int2bigInt(0, 0); +bi = BigInt.int2bigInt(0, 0, 0); +bi = BigInt.inverseMod(bi, bi); +bi = BigInt.inverseModInt(num, num); +b = BigInt.isZero(bi); +b = BigInt.millerRabin(bi, bi); +b = BigInt.millerRabinInt(num, num); +bi = BigInt.mod(bi, bi); +num = BigInt.modInt(bi, num); +bi = BigInt.mult(bi, bi); +bi = BigInt.multMod(bi, bi, bi); +b = BigInt.negative(bi); +bi = BigInt.powMod(bi, bi, bi); +bi = BigInt.randBigInt(num, num); +bi = BigInt.randTruePrime(num); +bi = BigInt.randProbPrime(num); +bi = BigInt.str2bigInt(str, num); +bi = BigInt.str2bigInt(str, num, 0); +bi = BigInt.str2bigInt(str, num, 0, 0); +bi = BigInt.str2bigInt(str, str); +bi = BigInt.str2bigInt(str, str, 0); +bi = BigInt.str2bigInt(str, str, 0, 0); +bi = BigInt.sub(bi, bi); +bi = BigInt.trim(bi, num); + +BigInt.addInt_(bi, num); +BigInt.add_(bi, bi); +BigInt.copy_(bi, bi); +num = BigInt.copyInt_(bi, num); +BigInt.GCD_(bi, bi); +b = BigInt.inverseMod_(bi, bi); +BigInt.mod_(bi, bi); +BigInt.mult_(bi, bi); +BigInt.multMod_(bi, bi, bi); +BigInt.powMod_(bi, bi, bi); +BigInt.randBigInt_(bi, num, num); +BigInt.randTruePrime_(bi, num); +BigInt.sub_(bi, bi); +BigInt.addShift_(bi, bi, num); +BigInt.carry_(bi); +BigInt.divide_(bi, bi, bi, bi); +num = BigInt.divInt_(bi, num); +BigInt.eGCD_(bi, bi, bi, bi, bi); +BigInt.halve_(bi); +BigInt.leftShift_(bi, num); +BigInt.linComb_(bi, bi, num, num); +BigInt.linCombShift_(bi, bi, num, num); +BigInt.mont_(bi, bi, bi, num); +BigInt.multInt_(bi, num); +BigInt.rightShift_(bi, num); +BigInt.squareMod_(bi, bi); +BigInt.subShift_(bi, bi, num); + +function someRandomRealCode() { + bi = BigInt.int2bigInt(22, 5); + bi = BigInt.str2bigInt("FFFFFFFFFFFFFFFFC90FDAA2", 16); + str = BigInt.bigInt2str(bi, 16); +} diff --git a/bigint/bigint.d.ts b/bigint/bigint.d.ts new file mode 100644 index 000000000..61543b1c6 --- /dev/null +++ b/bigint/bigint.d.ts @@ -0,0 +1,245 @@ +// Type definitions for BigInt v5.5.1 +// Project: https://github.com/Evgenus/BigInt +// Definitions by: Eugene Chernyshov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module BigInt { + export interface BigInt extends Array { + } + + export interface IRandom { + (): number; + } + + export function setRandom(random: IRandom): void; + + // bigInt add(x,y) + // return (x+y) for bigInts x and y. + export function add(x: BigInt, y: BigInt): BigInt; + + // bigInt addInt(x,n) + // return (x+n) where x is a bigInt and n is an integer. + export function addInt(x: BigInt, n: number): BigInt; + + // string bigInt2str(x,base) + // return a string form of bigInt x in a given base, with 2 <= base <= 95 + export function bigInt2str(x: BigInt, base: number): string; + export function bigInt2str(x: BigInt, base: string): string; + + // int bitSize(x) + // return how many bits long the bigInt x is, not counting leading zeros + export function bitSize(x: BigInt): number; + + // bigInt dup(x) + // return a copy of bigInt x + export function dup(x: BigInt): BigInt; + + // boolean equals(x,y) + // is the bigInt x equal to the bigint y? + export function equals(x: BigInt, y: BigInt): boolean; + + // boolean equalsInt(x,y) + // is bigint x equal to integer y? + export function equalsInt(x: BigInt, y: number): boolean; + + // bigInt expand(x,n) + // return a copy of x with at least n elements, adding leading zeros if needed + export function expand(value: BigInt, n: number): BigInt; + + // Array findPrimes(n) + // return array of all primes less than integer n + export function findPrimes(n: number): number[]; + + // bigInt GCD(x,y) + // return greatest common divisor of bigInts x and y (each with same number of elements). + export function GCD(x: BigInt, y: BigInt): BigInt; + + // boolean greater(x,y) + // is x>y? (x and y are nonnegative bigInts) + export function greater(x: BigInt, y: BigInt): boolean; + + // boolean greaterShift(x,y,shift) + // is (x <<(shift*bpe)) > y? + export function greaterShift(x: BigInt, y: BigInt, shift: number): boolean; + + // bigInt int2bigInt(t,n,m) + // return a bigInt equal to integer t, with at least n bits and m array elements + export function int2bigInt(t: number, n?: number, m?: number): BigInt; + + // bigInt inverseMod(x,n) + // return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null + export function inverseMod(x: BigInt, n: BigInt): BigInt; + + // int inverseModInt(x,n) + // return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse + export function inverseModInt(x: number, n: number): BigInt; + + // boolean isZero(x) + // is the bigInt x equal to zero? + export function isZero(x: BigInt): boolean; + + // boolean millerRabin(x,b) + // does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1=1). If s=1, then the most significant of those n bits is set to 1. + export function randBigInt(n: number, s: number): BigInt; + + // bigInt randTruePrime(k) + // return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + export function randTruePrime(k: number): BigInt; + + // bigInt randProbPrime(k) + // return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). + export function randProbPrime(k: number): BigInt; + + // bigInt str2bigInt(s,b,n,m) + // return a bigInt for number represented in string s in base b with at least n bits and m array elements + export function str2bigInt(s: string, b: number, n?: number, m?: number): BigInt; + export function str2bigInt(s: string, b: string, n?: number, m?: number): BigInt; + + // bigInt sub(x,y) + // return (x-y) for bigInts x and y. Negative answers will be 2s complement + export function sub(x: BigInt, y: BigInt): BigInt; + + // bigInt trim(x,k) + // return a copy of x with exactly k leading zero elements + export function trim(x: BigInt, k: number): BigInt; + + // void addInt_(x,n) + // do x=x+n where x is a bigInt and n is an integer + export function addInt_(x: BigInt, n: number): void; + + // void add_(x,y) + // do x=x+y for bigInts x and y + export function add_(x: BigInt, y: BigInt): void; + + // void copy_(x,y) + // do x=y on bigInts x and y + export function copy_(x: BigInt, y: BigInt): void; + + // void copyInt_(x,n) + // do x=n on bigInt x and integer n + export function copyInt_(x: BigInt, n: number): number; + + // void GCD_(x,y) + // set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + export function GCD_(x: BigInt, y: BigInt): void; + + // boolean inverseMod_(x,n) + // do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist + export function inverseMod_(x: BigInt, n: BigInt): boolean; + + // void mod_(x,n) + // do x=x mod n for bigInts x and n. (This never overflows its array). + export function mod_(x: BigInt, n: BigInt): void; + + // void mult_(x,y) + // do x=x*y for bigInts x and y. + export function mult_(x: BigInt, y: BigInt): void; + + // void multMod_(x,y,n) + // do x=x*y mod n for bigInts x,y,n. + export function multMod_(x: BigInt, y: BigInt, n: BigInt): void; + + // void powMod_(x,y,n) + // do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. + export function powMod_(x: BigInt, y: BigInt, n: BigInt): void; + + // void randBigInt_(b,n,s) + // do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. + export function randBigInt_(b: BigInt, n: number, s: number): void; + + // void randTruePrime_(ans,k) + // do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. + export function randTruePrime_(ans: BigInt, k: number): void; + + // void sub_(x,y) + // do x=x-y for bigInts x and y. Negative answers will be 2s complement. + export function sub_(x: BigInt, y: BigInt): void; + + // void addShift_(x,y,ys) + // do x=x+(y<<(ys*bpe)) + export function addShift_(x: BigInt, y: BigInt, ys: number): void; + + // void carry_(x) + // do carries and borrows so each element of the bigInt x fits in bpe bits. + export function carry_(x: BigInt): void; + + // void divide_(x,y,q,r) + // divide x by y giving quotient q and remainder r + export function divide_(x: BigInt, y: BigInt, q: BigInt, r: BigInt): void; + + // int divInt_(x,n) + // do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). + export function divInt_(x: BigInt, n: number): number; + + // void eGCD_(x,y,d,a,b) + // sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y + export function eGCD_(x: BigInt, y: BigInt, d: BigInt, a: BigInt, b: BigInt): void; + + // void halve_(x) + // do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). + export function halve_(x: BigInt): void; + + // void leftShift_(x,n) + // left shift bigInt x by n bits. n Date: Sun, 3 Aug 2014 15:43:21 +0300 Subject: [PATCH 101/167] definitions for Stanford Javascript Crypto Library --- CONTRIBUTORS.md | 1 + sjcl/sjcl-tests.ts | 267 ++++++++++++++++++++++ sjcl/sjcl.d.ts | 556 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 824 insertions(+) create mode 100644 sjcl/sjcl-tests.ts create mode 100644 sjcl/sjcl.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..bf47e04a9 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -306,6 +306,7 @@ All definitions files include a header with the author and editors, so at some p * [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) * [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame)) * [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u)) +* [sjcl](http://crypto.stanford.edu/sjcl/) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin)) * [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com)) * [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) diff --git a/sjcl/sjcl-tests.ts b/sjcl/sjcl-tests.ts new file mode 100644 index 000000000..4ff603203 --- /dev/null +++ b/sjcl/sjcl-tests.ts @@ -0,0 +1,267 @@ +/// + +var b: boolean; +var n: number; +var s: string; +var bn: sjcl.BigNumber; +var ba: sjcl.BitArray; + +function testBigNumber() { + bn = new sjcl.bn(); + bn = new sjcl.bn(0); + bn = new sjcl.bn("0"); + bn = new sjcl.bn(bn); + + bn = bn.initWith(0); + bn = bn.initWith("0"); + bn = bn.initWith(bn); + + bn = bn.addM(0); + bn = bn.addM("0"); + bn = bn.addM(bn); + + bn = bn.subM(0); + bn = bn.subM("0"); + bn = bn.subM(bn); + + bn = bn.mod(0); + bn = bn.mod("0"); + bn = bn.mod(bn); + + bn = bn.inverseMod(0); + bn = bn.inverseMod("0"); + bn = bn.inverseMod(bn); + + bn = bn.add(0); + bn = bn.add("0"); + bn = bn.add(bn); + + bn = bn.sub(0); + bn = bn.sub("0"); + bn = bn.sub(bn); + + bn = bn.mul(0); + bn = bn.mul("0"); + bn = bn.mul(bn); + + bn = bn.mulmod(0, 0); + bn = bn.mulmod(0, "0"); + bn = bn.mulmod(0, bn); + bn = bn.mulmod("0", 0); + bn = bn.mulmod("0", "0"); + bn = bn.mulmod("0", bn); + bn = bn.mulmod(bn, 0); + bn = bn.mulmod(bn, "0"); + bn = bn.mulmod(bn, bn); + + bn = bn.powermod(0, 0); + bn = bn.powermod(0, "0"); + bn = bn.powermod(0, bn); + bn = bn.powermod("0", 0); + bn = bn.powermod("0", "0"); + bn = bn.powermod("0", bn); + bn = bn.powermod(bn, 0); + bn = bn.powermod(bn, "0"); + bn = bn.powermod(bn, bn); + + bn = bn.copy(); + + b = bn.equals(0); + b = bn.equals(bn); + + b = bn.greaterEquals(0); + b = bn.greaterEquals(bn); + + n = bn.getLimb(0); + + s = bn.toString(); + + bn = bn.doubleM(); + + bn = bn.halveM(); + + bn = bn.square(); + + bn = bn.power(1); + bn = bn.power([1, 1]); + bn = bn.power(bn); + + bn = bn.trim(); + + bn = bn.reduce(); + + bn = bn.fullReduce(); + + bn = bn.normalize(); + + bn = bn.cnormalize(); + + ba = bn.toBits(); + ba = bn.toBits(1); + + n = bn.bitLength(); + + bn = sjcl.bn.fromBits(ba); +} + +function testBitArray() { + ba = sjcl.bitArray.bitSlice(ba, 0, 1); + + n = sjcl.bitArray.extract(ba, 0, 1); + + ba = sjcl.bitArray.concat(ba, ba); + + n = sjcl.bitArray.bitLength(ba); + + ba = sjcl.bitArray.clamp(ba, 0); + + n = sjcl.bitArray.partial(1, 1); + n = sjcl.bitArray.partial(1, 1, 0); + + n = sjcl.bitArray.getPartial(0); + + b = sjcl.bitArray.equal(ba, ba); + + ba = sjcl.bitArray._shiftRight(ba, 0); + ba = sjcl.bitArray._shiftRight(ba, 0, 0); + ba = sjcl.bitArray._shiftRight(ba, 0, 0, ba); +} + +function testCodecs() { + s = sjcl.codec.base64.fromBits(ba); + ba = sjcl.codec.base64.toBits(s); + + s = sjcl.codec.base64url.fromBits(ba); + ba = sjcl.codec.base64url.toBits(s); + + s = sjcl.codec.hex.fromBits(ba); + ba = sjcl.codec.hex.toBits(s); + + s = sjcl.codec.utf8String.fromBits(ba); + ba = sjcl.codec.utf8String.toBits(s); + + var bytes: number[] = sjcl.codec.bytes.fromBits(ba); + ba = sjcl.codec.bytes.toBits(bytes); +} + +function testHashes() { + var hash: sjcl.SjclHash; + ba = hash.reset().update("xxx").update(ba).finalize(); + + hash = new sjcl.hash.sha1(); + hash = new sjcl.hash.sha1(hash); + ba = sjcl.hash.sha1.hash(ba); + ba = sjcl.hash.sha1.hash("xxx"); + + hash = new sjcl.hash.sha256(); + hash = new sjcl.hash.sha256(hash); + ba = sjcl.hash.sha256.hash(ba); + ba = sjcl.hash.sha256.hash("xxx"); + + hash = new sjcl.hash.sha512(); + hash = new sjcl.hash.sha512(hash); + ba = sjcl.hash.sha512.hash(ba); + ba = sjcl.hash.sha512.hash("xxx"); +} + +function testSymetric() { + var aes = new sjcl.cipher.aes([0, 0, 0, 0]); + + ba = sjcl.mode.cbc.encrypt(aes, ba, ba); + ba = sjcl.mode.cbc.encrypt(aes, ba, ba, ba); + + ba = sjcl.mode.gcm.encrypt(aes, ba, ba); + ba = sjcl.mode.gcm.encrypt(aes, ba, ba, ba); + ba = sjcl.mode.gcm.encrypt(aes, ba, ba, ba, 128); + + ba = sjcl.mode.ccm.encrypt(aes, ba, ba); + ba = sjcl.mode.ccm.encrypt(aes, ba, ba, ba); + ba = sjcl.mode.ccm.encrypt(aes, ba, ba, ba, 128); + + ba = sjcl.mode.ocb2.encrypt(aes, ba, ba); + ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba); + ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba, 128); + ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba, 128, false); +} + +function testHmacPbdkf2() { + ba = sjcl.misc.pbkdf2("xxx", "xxx"); + ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000); + ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000, 12); + ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000, 12, sjcl.misc.hmac); + + ba = sjcl.misc.pbkdf2("xxx", ba); + ba = sjcl.misc.pbkdf2("xxx", ba, 1000); + ba = sjcl.misc.pbkdf2("xxx", ba, 1000, 12); + ba = sjcl.misc.pbkdf2("xxx", ba, 1000, 12, sjcl.misc.hmac); + + ba = sjcl.misc.pbkdf2(ba, "xxx"); + ba = sjcl.misc.pbkdf2(ba, "xxx", 1000); + ba = sjcl.misc.pbkdf2(ba, "xxx", 1000, 12); + ba = sjcl.misc.pbkdf2(ba, "xxx", 1000, 12, sjcl.misc.hmac); + + ba = sjcl.misc.pbkdf2(ba, ba); + ba = sjcl.misc.pbkdf2(ba, ba, 1000); + ba = sjcl.misc.pbkdf2(ba, ba, 1000, 12); + ba = sjcl.misc.pbkdf2(ba, ba, 1000, 12, sjcl.misc.hmac); + + var hmac: sjcl.SjclHmac; + hmac = new sjcl.misc.hmac(ba); + hmac = new sjcl.misc.hmac(ba, sjcl.hash.sha512); + + ba = hmac.mac("xxx"); + ba = hmac.mac(ba); + + ba = hmac.encrypt("xxx"); + ba = hmac.encrypt(ba); + + hmac.reset(); + + hmac.update("xxx"); + hmac.update(ba); + + ba = hmac.digest(); +} + +function testECC() { + var keys = sjcl.ecc.elGamal.generateKeys(192, 0); + + var ciphertext = sjcl.encrypt(keys.pub, "hello world"); + var plaintext = sjcl.decrypt(keys.sec, ciphertext); + + // TODO: Maybe deeper testing required. Let me know +} + +function testRandom() { + b = sjcl.random.isReady(); + ba = sjcl.random.randomWords(8); + ba = sjcl.random.randomWords(8, 6); + + var rnd = new sjcl.prng(1); + ba = rnd.randomWords(16); + ba = rnd.randomWords(16, 6); +} + +function testSRP() { + var group = sjcl.keyexchange.srp.knownGroup(1024); + ba = sjcl.codec.hex.toBits(s); + ba = sjcl.keyexchange.srp.makeX(s, s, ba); + ba = sjcl.keyexchange.srp.makeVerifier(s, s, ba, group); +} + +function testConvenince() { + var x: sjcl.SjclCipherEncrypted; + x = sjcl.encrypt("xxx", "text"); + s = sjcl.decrypt(ba, x); + + x = sjcl.encrypt("xxx", "text", { iv: ba, salt: ba }); + s = sjcl.decrypt(ba, x, { iv: ba, salt: ba }); + + var y: sjcl.SjclCipherDecrypted; + + sjcl.encrypt("xxx", "text", { iv: ba, salt: ba, mode: "gcm" }, x); + s = sjcl.decrypt(ba, x, { iv: ba, salt: ba, mode: "gcm" }, y); + + sjcl.encrypt("xxx", "text", { iv: ba, salt: ba, mode: "gcm", iter: 200 }, x); + s = sjcl.decrypt(ba, x, { iv: ba, salt: ba, mode: "gcm", iter: 200 }, y); +} \ No newline at end of file diff --git a/sjcl/sjcl.d.ts b/sjcl/sjcl.d.ts new file mode 100644 index 000000000..8413edb2f --- /dev/null +++ b/sjcl/sjcl.d.ts @@ -0,0 +1,556 @@ +// Type definitions for sjcl v1.0.1 +// Project: http://crypto.stanford.edu/sjcl/ +// Definitions by: Eugene Chernyshov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module sjcl { + + export var bn: BigNumberStatic; + export var bitArray: BitArrayStatic; + export var codec: SjclCodecs; + export var hash: SjclHashes; + export var exception: SjclExceptions; + export var cipher: SjclCiphers; + export var mode: SjclModes; + export var misc: SjclMisc; + export var ecc: SjclEllipticCurveCryptography; + export var random: SjclRandom; + export var prng: SjclRandomStatic; + export var keyexchange: SjclKeyExchange; + export var json: SjclJson; + export var encrypt: SjclConveninceEncryptor; + export var decrypt: SjclConveninceDecryptor; + + // ________________________________________________________________________ + + interface BigNumber { + radix: number; + maxMul: number; + + copy(): BigNumber; + + /// Initializes this with it, either as a bn, a number, or a hex string. + initWith: TypeHelpers.BigNumberBinaryOperator; + + /// Returns true if "this" and "that" are equal. Calls fullReduce(). + /// Equality test is in constant time. + equals(that: number): boolean; + equals(that: BigNumber): boolean; + + /// Get the i'th limb of this, zero if i is too large. + getLimb(index: number): number; + + /// Constant time comparison function. + /// Returns 1 if this >= that, or zero otherwise. + greaterEquals(that: number): boolean; + greaterEquals(that: BigNumber): boolean; + + /// Convert to a hex string. + toString(): string; + + /// this += that. Does not normalize. + addM: TypeHelpers.BigNumberBinaryOperator; + + /// this *= 2. Requires normalized; ends up normalized. + doubleM(): BigNumber; + + /// this /= 2, rounded down. Requires normalized; ends up normalized. + halveM(): BigNumber; + + /// this -= that. Does not normalize. + subM: TypeHelpers.BigNumberBinaryOperator; + + mod: TypeHelpers.BigNumberBinaryOperator; + + /// return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. + inverseMod: TypeHelpers.BigNumberBinaryOperator; + + /// this + that. Does not normalize. + add: TypeHelpers.BigNumberBinaryOperator; + + /// this - that. Does not normalize. + sub: TypeHelpers.BigNumberBinaryOperator; + + /// this * that. Normalizes and reduces. + mul: TypeHelpers.BigNumberBinaryOperator; + + /// this ^ 2. Normalizes and reduces. + square(): BigNumber; + + /// this ^ n. Uses square-and-multiply. Normalizes and reduces. + power(n: number): BigNumber; + power(n: BigNumber): BigNumber; + power(a: number[]): BigNumber; + + /// this * that mod N + mulmod: TypeHelpers.BigNumberTrinaryOperator; + + /// this ^ x mod N + powermod: TypeHelpers.BigNumberTrinaryOperator; + + trim(): BigNumber; + + /// Reduce mod a modulus. Stubbed for subclassing. + reduce(): BigNumber; + + /// Reduce and normalize. + fullReduce(): BigNumber; + + /// Propagate carries. + normalize(): BigNumber; + + /// Constant-time normalize. Does not allocate additional space. + cnormalize(): BigNumber; + + /// Serialize to a bit array + toBits(len?: number): BitArray; + + /// Return the length in bits, rounded up to the nearest byte. + bitLength(): number; + } + + interface BigNumberStatic { + new (): BigNumber; + new (n: string): BigNumber; + new (n: number): BigNumber; + new (n: BigNumber): BigNumber; + + fromBits(bits: BitArray): BigNumber; + random: TypeHelpers.Bind1; + prime: { + p127: PseudoMersennePrimeStatic; + // Bernstein's prime for Curve25519 + p25519: PseudoMersennePrimeStatic; + // Koblitz primes + p192k: PseudoMersennePrimeStatic; + p224k: PseudoMersennePrimeStatic; + p256k: PseudoMersennePrimeStatic; + // NIST primes + p192: PseudoMersennePrimeStatic; + p224: PseudoMersennePrimeStatic; + p256: PseudoMersennePrimeStatic; + p384: PseudoMersennePrimeStatic; + p521: PseudoMersennePrimeStatic; + }; + + pseudoMersennePrime(exponent: number, coeff: number[][]): PseudoMersennePrimeStatic; + } + + interface PseudoMersennePrime extends BigNumber { + reduce(): PseudoMersennePrime; + fullReduce(): PseudoMersennePrime; + inverse(): PseudoMersennePrime; + } + + interface PseudoMersennePrimeStatic extends BigNumberStatic { + new (): PseudoMersennePrime; + new (n: string): PseudoMersennePrime; + new (n: number): PseudoMersennePrime; + new (n: BigNumber): PseudoMersennePrime; + } + + // ________________________________________________________________________ + + interface BitArray extends Array { + } + + interface BitArrayStatic { + /// Array slices in units of bits. + bitSlice(a: BitArray, bstart: number, bend: number): BitArray; + + /// Extract a number packed into a bit array. + extract(a: BitArray, bstart: number, blenth: number): number; + + /// Concatenate two bit arrays. + concat(a1: BitArray, a2: BitArray): BitArray + + /// Find the length of an array of bits. + bitLength(a: BitArray): number; + + /// Truncate an array. + clamp(a: BitArray, len: number): BitArray; + + /// Make a partial word for a bit array. + partial(len: number, x: number, _end?: number): number; + + /// Get the number of bits used by a partial word. + getPartial(x: number): number; + + /// Compare two arrays for equality in a predictable amount of time. + equal(a: BitArray, b: BitArray): boolean; + + /// Shift an array right. + _shiftRight(a: BitArray, shift: number, carry?: number, out?: BitArray): BitArray; + + /// xor a block of 4 words together. + _xor4(x: number[], y: number[]): number[]; + } + + // ________________________________________________________________________ + + interface SjclCodec { + fromBits(bits: BitArray): T; + toBits(value: T): BitArray; + } + + interface SjclCodecs { + utf8String: SjclCodec; + hex: SjclCodec; + bytes: SjclCodec; + base64: SjclCodec; + base64url: SjclCodec; + } + + // ________________________________________________________________________ + + interface SjclHash { + reset(): SjclHash; + update(data: string): SjclHash; + update(data: BitArray): SjclHash; + finalize(): BitArray; + } + + interface SjclHashStatic { + new (hash?: SjclHash): SjclHash; + hash(data: string): BitArray; + hash(data: BitArray): BitArray; + } + + interface SjclHashes { + sha1: SjclHashStatic; + sha256: SjclHashStatic; + sha512: SjclHashStatic; + } + + // ________________________________________________________________________ + + interface SjclExceptions { + corrupt: SjclExceptionFactory; + invalid: SjclExceptionFactory; + bug: SjclExceptionFactory; + notReady: SjclExceptionFactory; + } + + interface SjclExceptionFactory { + new (message: string): Error; + } + + // ________________________________________________________________________ + + interface SjclCiphers { + aes: SjclCipherStatic; + } + + interface SjclCipher { + encrypt(data: number[]): number[]; + decrypt(data: number[]): number[]; + } + + interface SjclCipherStatic { + new (key: number[]): SjclCipher; + } + + // ________________________________________________________________________ + + interface SjclModes { + gcm: SjclGCMMode; + ccm: SjclCCMMode; + ocb2: SjclOCB2Mode; + cbc: SjclCBCMode; + } + + interface SjclGCMMode { + encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + } + + interface SjclCCMMode { + encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + } + + interface SjclOCB2Mode { + encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean): BitArray; + decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean): BitArray; + pmac(prp: SjclCipher, adata: BitArray): number[]; + } + + interface SjclCBCMode { + encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray): BitArray; + decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray): BitArray; + } + + // ________________________________________________________________________ + + interface Pbkdf2Params { + iter?: number; + salt?: BitArray; + } + + interface SjclMisc { + pbkdf2(password: string, salt: string, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray; + pbkdf2(password: BitArray, salt: string, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray; + pbkdf2(password: BitArray, salt: BitArray, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray; + pbkdf2(password: string, salt: BitArray, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray; + hmac: SjclHmacStatic; + cachedPbkdf2(password: string, obj?: Pbkdf2Params): { + key: BitArray; + salt: BitArray; + }; + } + + class SjclPseudorandomFunctionFamily { + encrypt(data: string): BitArray; + encrypt(data: BitArray): BitArray; + } + + interface SjclHmac extends SjclPseudorandomFunctionFamily { + mac(data: string): BitArray; + mac(data: BitArray): BitArray; + reset(): void; + update(data: string): void; + update(data: BitArray): void; + digest(): BitArray; + } + + interface SjclPseudorandomFunctionFamilyStatic { + new (key: BitArray): SjclPseudorandomFunctionFamily; + } + + interface SjclHmacStatic { + new (key: BitArray, Hash?: SjclHashStatic): SjclHmac; + } + + // ________________________________________________________________________ + + interface SjclEllipticCurveCryptography { + point: SjclEllipticalPointStatic; + pointJac: SjclPointJacobianStatic; + curve: SjclEllipticalCurveStatic; + curves: { + c192: SjclEllipticalCurve; + c224: SjclEllipticalCurve; + c256: SjclEllipticalCurve; + c384: SjclEllipticalCurve; + k192: SjclEllipticalCurve; + k224: SjclEllipticalCurve; + k256: SjclEllipticalCurve; + }; + basicKey: SjclECCBasic; + elGamal: SjclElGamal; + ecdsa: SjclEcdsa; + } + + interface SjclEllipticalPoint { + toJac(): SjclPointJacobian; + mult(k: BigNumber): SjclEllipticalPoint; + mult2(k: BigNumber, k2: BigNumber, affine2: SjclEllipticalPoint): SjclEllipticalPoint; + multiples(): Array; + isValid(): boolean; + toBits(): BitArray; + } + + interface SjclEllipticalPointStatic { + new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber): SjclEllipticalPoint; + } + + interface SjclPointJacobian { + add(T: SjclEllipticalPoint): SjclPointJacobian; + doubl(): SjclPointJacobian; + toAffine(): SjclEllipticalPoint; + mult(k: BigNumber, affine: SjclEllipticalPoint): SjclPointJacobian; + mult2(k1: BigNumber, affine: SjclEllipticalPoint, k2: BigNumber, affine2: SjclEllipticalPoint): SjclPointJacobian; + isValid(): boolean; + } + + interface SjclPointJacobianStatic { + new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber, z?: BigNumber):SjclPointJacobian; + } + + interface SjclEllipticalCurve { + fromBits(bits: BitArray): SjclEllipticalPoint; + } + + interface SjclEllipticalCurveStatic { + new (Field: BigNumber, r: BigNumber, a: BigNumber, b: BigNumber, x: BigNumber, y: BigNumber): SjclEllipticalCurve; + } + + interface SjclKeyPair

{ + pub: P; + sec: S; + } + + interface SjclKeysGenerator

{ + (curve: SjclEllipticalCurve, paranoia: number, sec?: BigNumber): SjclKeyPair; + (curve: number, paranoia: number, sec?: BigNumber): SjclKeyPair; + } + + interface SjclECCPublicKeyData { + x: BitArray; + y: BitArray; + } + + class SjclECCPublicKey { + get(): SjclECCPublicKeyData; + } + + class SjclECCSecretKey { + get(): BitArray; + } + + interface SjclECCPublicKeyFactory { + new (curve: SjclEllipticalCurve, point: SjclEllipticalPoint): T; + new (curve: SjclEllipticalCurve, point: BitArray): T; + } + + interface SjclECCSecretKeyFactory { + new (curve: SjclEllipticalCurve, exponent: BigNumber): T; + } + + interface SjclECCBasic { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys(cn: string): SjclKeysGenerator; + } + + class SjclElGamalPublicKey extends SjclECCPublicKey { + kem(paranoia: number): { + key: BitArray; + tag: BitArray; + }; + } + + class SjclElGamalSecretKey extends SjclECCSecretKey { + unkem(tag: BitArray): BitArray; + dh(pk: SjclECCPublicKey): BitArray; + } + + interface SjclElGamal { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys: SjclKeysGenerator; + } + + class SjclEcdsaPublicKey extends SjclECCPublicKey { + verify(hash: BitArray, rs: BitArray, fakeLegacyVersion: boolean): boolean; + } + + class SjclEcdsaSecretKey extends SjclECCSecretKey { + sign(hash: BitArray, paranoia: number, fakeLegacyVersion: boolean, fixedKForTesting?: BigNumber): BitArray; + } + + interface SjclEcdsa { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys: SjclKeysGenerator; + } + + // ________________________________________________________________________ + + interface SjclRandom { + randomWords(nwords: number, paranoia?: number): BitArray; + setDefaultParanoia(paranoia: number, allowZeroParanoia: string): void; + addEntropy(data: number, estimatedEntropy: number, source: string): void; + addEntropy(data: number[], estimatedEntropy: number, source: string): void; + addEntropy(data: string, estimatedEntropy: number, source: string): void; + isReady(paranoia?: number): boolean; + getProgress(paranoia?: number): number; + startCollectors(): void; + stopCollectors(): void; + addEventListener(name: string, cb: Function): void; + removeEventListener(name: string, cb: Function): void; + } + + interface SjclRandomStatic { + new (defaultParanoia: number): SjclRandom; + } + + // ________________________________________________________________________ + + interface SjclKeyExchange { + srp: SecureRemotePassword; + } + + interface SjclSRPGroup { + N: BigNumber; + g: BigNumber; + } + + interface SecureRemotePassword { + makeVerifier(username: string, password: string, salt: BitArray, group: SjclSRPGroup): BitArray; + makeX(username: string, password: string, salt: BitArray): BitArray; + knownGroup(i: string): SjclSRPGroup; + knownGroup(i: number): SjclSRPGroup; + } + + // ________________________________________________________________________ + + interface SjclCipherParams { + v?: number; + iter?: number; + ks?: number; + ts?: number; + mode?: string; + adata?: string; + cipher?: string; + } + + interface SjclCipherEncryptParams extends SjclCipherParams { + salt: BitArray; + iv: BitArray; + } + + interface SjclCipherDecryptParams extends SjclCipherParams { + salt?: BitArray; + iv?: BitArray; + } + + interface SjclCipherEncrypted extends SjclCipherEncryptParams { + kemtag?: BitArray; + ct: BitArray; + } + + interface SjclCipherDecrypted extends SjclCipherEncrypted { + key: BitArray; + } + + interface SjclConveninceEncryptor { + (password: string, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted; + (password: BitArray, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted; + (password: SjclElGamalPublicKey, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted; + } + + interface SjclConveninceDecryptor { + (password: string, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string; + (password: BitArray, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string; + (password: SjclElGamalSecretKey, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string; + } + + interface SjclJson { + encrypt: SjclConveninceEncryptor; + decrypt: SjclConveninceDecryptor; + encode(obj: Object): string; + decode(obj: string): Object; + } + + // ________________________________________________________________________ + + module TypeHelpers { + interface One { + (value: T): BigNumber; + } + + interface BigNumberBinaryOperator extends One, One, One { + } + + interface Two { + (x: T1, N: T2): BigNumber; + } + + interface Bind1 extends Two, Two, Two { + } + + interface BigNumberTrinaryOperator extends Bind1, Bind1, Bind1 { + } + } +} From b8ce2bd4c01526630b8402af303824bf5341a572 Mon Sep 17 00:00:00 2001 From: Will Johnston Date: Sun, 3 Aug 2014 16:41:25 -0500 Subject: [PATCH 102/167] updated mysql definitions and tests --- mysql/mysql-tests.ts | 381 +++++++++++++++++++++++++++++++++ mysql/mysql.d.ts | 488 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 869 insertions(+) create mode 100644 mysql/mysql-tests.ts create mode 100644 mysql/mysql.d.ts diff --git a/mysql/mysql-tests.ts b/mysql/mysql-tests.ts new file mode 100644 index 000000000..81f1e7766 --- /dev/null +++ b/mysql/mysql-tests.ts @@ -0,0 +1,381 @@ +/// + +import mysql = require('mysql'); + +/// Connections +var connection = mysql.createConnection({ + host: 'localhost', + user: 'me', + password: 'secret' +}); + +connection.connect(); + +connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { + if (err) throw err; + + console.log('The solution is: ', rows[0].solution); +}); + +connection.end(); + +connection = mysql.createConnection({ + host: 'example.org', + user: 'bob', + password: 'secret' +}); + +connection.connect(function (err) { + if (err) { + console.error('error connecting: ' + err.stack); + return; + } + + console.log('connected as id ' + connection.threadId); +}); + +connection.query('SELECT 1', function (err, rows) { + // connected! (unless `err` is set) +}); + +connection = mysql.createConnection({ + host: 'localhost', + ssl: { + ca: '' + } +}); + +connection = mysql.createConnection({ + host: 'localhost', + ssl: { + // DO NOT DO THIS + // set up your ca correctly to trust the connection + rejectUnauthorized: false + } +}); + +connection.end(function (err) { + // The connection is terminated now +}); + +connection.destroy(); + +connection.changeUser({ user: 'john' }, function (err) { + if (err) throw err; +}); + +var userId = 'some user provided value'; +var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId); +connection.query(sql, function (err, results) { + // ... +}); +connection.query('SELECT * FROM users WHERE id = ?', [userId], function (err, results) { + // ... +}); + +var post = { id: 1, title: 'Hello MySQL' }; +var query = connection.query('INSERT INTO posts SET ?', post, function (err, result) { + // Neat! +}); +console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' + +var queryStr = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL"); + +console.log(queryStr); // SELECT * FROM posts WHERE title='Hello MySQL' + +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter); +connection.query(sql, function (err, results) { + // ... +}); + +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter); +connection.query(sql, function (err, results) { + // ... +}); + +var userIdNum = 1; +var columns = ['username', 'email']; +var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userIdNum], function (err, results) { + // ... +}); + +console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1 + +var sql = "SELECT * FROM ?? WHERE ?? = ?"; +var inserts = ['users', 'id', userId]; +sql = mysql.format(sql, inserts); + +connection.config.queryFormat = function (query, values) { + if (!values) return query; + return query.replace(/\:(\w+)/g, function (txt, key) { + if (values.hasOwnProperty(key)) { + return this.escape(values[key]); + } + return txt; + }.bind(this)); +}; + +connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" }); + +connection.query('INSERT INTO posts SET ?', { title: 'test' }, function (err, result) { + if (err) throw err; + + console.log(result.insertId); +}); + +connection.query('DELETE FROM posts WHERE title = "wrong"', function (err, result) { + if (err) throw err; + + console.log('deleted ' + result.affectedRows + ' rows'); +}); + +connection.query('UPDATE posts SET ...', function (err, result) { + if (err) throw err; + + console.log('changed ' + result.changedRows + ' rows'); +}); + +connection.connect(function (err) { + if (err) throw err; + console.log('connected as id ' + connection.threadId); +}); + +/// Pools + +var poolConfig = { + connectionLimit: 10, + host: 'example.org', + user: 'bob', + password: 'secret' +}; + +var pool = mysql.createPool(poolConfig); + +pool.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { + if (err) throw err; + + console.log('The solution is: ', rows[0].solution); +}); + +pool = mysql.createPool({ + host: 'example.org', + user: 'bob', + password: 'secret' +}); + +pool.getConnection(function (err, connection) { + // connected! (unless `err` is set) +}); + +pool.on('connection', function (connection) { + connection.query('SET SESSION auto_increment_increment=1') +}); + +pool.getConnection(function (err, connection: mysql.IConnection) { + // Use the connection + connection.query('SELECT something FROM sometable', function (err, rows) { + // And done with the connection. + connection.release(); + + // Don't use the connection here, it has been returned to the pool. + }); +}); + +/// PoolClusters + +// create +var poolCluster = mysql.createPoolCluster(); + +poolCluster.add(poolConfig); // anonymous group +poolCluster.add('MASTER', poolConfig); +poolCluster.add('SLAVE1', poolConfig); +poolCluster.add('SLAVE2', poolConfig); + +// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default) +poolCluster.getConnection(function (err, connection) { }); + +// Target Group : MASTER, Selector : round-robin +poolCluster.getConnection('MASTER', function (err, connection) { }); + +// Target Group : SLAVE1-2, Selector : order +// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster) +poolCluster.on('remove', function (nodeId) { + console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 +}); + +poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) { }); + +// of namespace : of(pattern, selector) +poolCluster.of('*').getConnection(function (err, connection) { }); + +var pool = poolCluster.of('SLAVE*', 'RANDOM'); +pool.getConnection(function (err, connection) { }); +pool.getConnection(function (err, connection) { }); + +// destroy +poolCluster.end(); + +/// Queries + +var query = connection.query('SELECT * FROM posts'); +query + .on('error', function (err) { + // Handle error, an 'end' event will be emitted after this as well + }) + .on('fields', function (fields) { + // the field packets for the rows to follow + }) + .on('result', function (row) { + // Pausing the connnection is useful if your processing involves I/O + connection.pause(); + + var processRow = (row: any, cb: () => void) => { + cb(); + }; + + processRow(row, function () { + connection.resume(); + }); + }) + .on('end', function () { + // all rows have been received + }); + +connection.query('SELECT * FROM posts') + .stream({ highWaterMark: 5 }) + .pipe(() => { }); + +connection = mysql.createConnection({ multipleStatements: true }); + +connection.query('SELECT 1; SELECT 2', function (err, results) { + if (err) throw err; + + // `results` is an array with one element for every statement in the query: + console.log(results[0]); // [{1: 1}] + console.log(results[1]); // [{2: 2}] +}); + +var query = connection.query('SELECT 1; SELECT 2'); + +query + .on('fields', function (fields, index) { + // the fields for the result rows that follow + }) + .on('result', function (row, index) { + // index refers to the statement this result belongs to (starts at 0) + }); + +var options = { sql: '...', nestTables: true }; + +connection.query(options, function (err, results) { + /* results will be an array like this now: + [{ + table1: { + fieldA: '...', + fieldB: '...', + }, + table2: { + fieldA: '...', + fieldB: '...', + }, + }, ...] + */ +}); + +connection.beginTransaction(function (err) { + var title = 'title'; + + if (err) { throw err; } + connection.query('INSERT INTO posts SET title=?', title, function (err, result) { + if (err) { + connection.rollback(function () { + throw err; + }); + } + + var log = 'Post ' + result.insertId + ' added'; + + connection.query('INSERT INTO log SET data=?', log, function (err, result) { + if (err) { + connection.rollback(function () { + throw err; + }); + } + connection.commit(function (err) { + if (err) { + connection.rollback(function () { + throw err; + }); + } + console.log('success!'); + }); + }); + }); +}); + +// Kill query after 60s +connection.query({ sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000 }, function (err, rows) { + if (err && err.code === 'PROTOCOL_SEQUENCE_TIMEOUT') { + throw new Error('too long to count table rows!'); + } + + if (err) { + throw err; + } + + console.log(rows[0].count + ' rows'); +}); + +connection = mysql.createConnection({ + port: 84943, // WRONG PORT +}); + +connection.connect(function (err) { + console.log(err.code); // 'ECONNREFUSED' + console.log(err.fatal); // true +}); + +connection.query('SELECT 1', function (err) { + console.log(err.code); // 'ECONNREFUSED' + console.log(err.fatal); // true +}); + +connection.query('USE name_of_db_that_does_not_exist', function (err, rows) { + console.log(err.code); // 'ER_BAD_DB_ERROR' +}); + +connection.query('SELECT 1', function (err, rows) { + console.log(err); // null + console.log(rows.length); // 1 +}); + +connection.on('error', function (err) { + console.log(err.code); // 'ER_BAD_DB_ERROR' +}); + +connection.query('USE name_of_db_that_does_not_exist'); + +// I am Chuck Norris: +connection.on('error', function () { }); + +connection = mysql.createConnection({ typeCast: false }); + +var query = connection.query({ sql: '...', typeCast: false }, function (err, results) { + +}); + +connection.query({ + sql: '...', + typeCast: function (field, next) { + if (field.type == 'TINY' && field.length == 1) { + return (field.string() == '1'); // 1 = true, 0 = false + } + return next(); + } +}); + +connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS"); +connection = mysql.createConnection({ debug: true }); +connection = mysql.createConnection({ debug: ['ComQueryPacket', 'RowDataPacket'] }); diff --git a/mysql/mysql.d.ts b/mysql/mysql.d.ts new file mode 100644 index 000000000..3df338e47 --- /dev/null +++ b/mysql/mysql.d.ts @@ -0,0 +1,488 @@ +// Type definitions for node-mysql +// Project: https://github.com/felixge/node-mysql +// Definitions by: William Johnston +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module mysql { + export interface IMySql { + createConnection(connectionUri: string): IConnection; + createConnection(config: IConnectionConfig): IConnection; + + createPool(config: IPoolConfig): IPool; + + createPoolCluster(config?: IPoolClusterConfig): IPoolCluster; + + escape(value: any): string; + + format(sql: string): string; + format(sql: string, values: Array): string; + } + + export interface IConnectionStatic { + createQuery(sql: string): IQuery; + createQuery(sql: string, callback: (err: IError, ...args: any[]) => void): IQuery; + createQuery(sql: string, values: Array): IQuery; + createQuery(sql: string, values: Array, callback: (err: IError, ...args: any[]) => void): IQuery; + } + + export interface IConnection { + config: IConnectionConfig; + + threadId: number; + + beginTransaction(callback: (err: IError) => void): void; + + connect(): void; + connect(callback: (err: IError, ...args: any[]) => void): void; + connect(options: any, callback?: (err: IError, ...args: any[]) => void): void; + + commit(callback: (err: IError) => void): void; + + changeUser(options: IConnectionOptions): void; + changeUser(options: IConnectionOptions, callback: (err: IError) => void): void; + + query: IQueryFunction; + + end(): void; + end(options: any): void; + end(callback: (err: IError, ...args: any[]) => void): void; + end(options: any, callback: (err: IError, ...args: any[]) => void): void; + + destroy(): void; + + pause(): void; + + release(): void; + resume(): void; + + escape(value: any): string; + + escapeId(value: string): string; + escapeId(values: Array): string; + + format(sql: string): string; + format(sql: string, values: Array): string; + + on(ev: string, callback: (...args: any[]) => void): IConnection; + on(ev: 'error', callback: (err: IError) => void): IConnection; + + rollback(callback: () => void): void; + } + + export interface IPool { + config: IPoolConfig; + + getConnection(callback: (err: IError, connection: IConnection) => void): void; + + query: IQueryFunction; + + on(ev: string, callback: (...args: any[]) => void): IPool; + on(ev: 'connection', callback: (connection: IConnection) => void): IPool; + on(ev: 'error', callback: (err: IError) => void): IPool; + } + + export interface IPoolCluster { + config: IPoolClusterConfig; + + add(config: IPoolConfig): void; + add(group: string, config: IPoolConfig): void; + + end(): void; + + getConnection(callback: (err: IError, connection: IConnection) => void): void; + getConnection(group: string, callback: (err: IError, connection: IConnection) => void): void; + getConnection(group: string, selector: string, callback: (err: IError, connection: IConnection) => void): void; + + of(pattern: string): IPool; + of(pattern: string, selector: string): IPool; + + on(ev: string, callback: (...args: any[]) => void): IPoolCluster; + on(ev: 'remove', callback: (nodeId: number) => void): IPoolCluster; + on(ev: 'connection', callback: (connection: IConnection) => void): IPoolCluster; + on(ev: 'error', callback: (err: IError) => void): IPoolCluster; + } + + export interface IQuery { + /** + * The SQL for a constructed query + */ + sql: string; + + /** + * Emits a query packet to start the query + */ + start(): void; + + /** + * Determines the packet class to use given the first byte of the packet. + * + * @param firstByte The first byte of the packet + * @param parser The packet parser + */ + determinePacket(firstByte: number, parser: any): any; + + /** + * Creates a Readable stream with the given options + * + * @param options The options for the stream. + */ + stream(options: IStreamOptions): IQuery; + + /** + * Pipes a stream downstream, providing automatic pause/resume based on the + * options sent to the stream. + * + * @param options The options for the stream. + */ + pipe(callback: (...args: any[]) => void): IQuery; + + on(ev: string, callback: (...args: any[]) => void): IQuery; + on(ev: 'error', callback: (err: IError) => void): IQuery; + on(ev: 'fields', callback: (fields: any, index: number) => void): IQuery; + on(ev: 'result', callback: (row: any, index: number) => void): IQuery; + on(ev: 'end', callback: () => void): IQuery; + } + + export interface IQueryFunction { + (sql: string): IQuery; + (sql: string, callback: (err: IError, ...args: any[]) => void): IQuery; + (sql: string, values: Array): IQuery; + (sql: string, values: Array, callback: (err: IError, ...args: any[]) => void): IQuery; + (sql: string, values: any): IQuery; + (sql: string, values: any, callback: (err: IError, ...args: any[]) => void): IQuery; + (options: IQueryOptions): IQuery; + (options: IQueryOptions, callback: (err: IError, ...args: any[]) => void): IQuery; + (options: IQueryOptions, values: Array): IQuery; + (options: IQueryOptions, values: Array, callback: (err: IError, ...args: any[]) => void): IQuery; + (options: IQueryOptions, values: any): IQuery; + (options: IQueryOptions, values: any, callback: (err: IError, ...args: any[]) => void): IQuery; + } + + export interface IQueryOptions { + /** + * The SQL for the query + */ + sql: string; + + /** + * Every operation takes an optional inactivity timeout option. This allows you to specify appropriate timeouts for + * operations. It is important to note that these timeouts are not part of the MySQL protocol, and rather timeout + * operations through the client. This means that when a timeout is reached, the connection it occurred on will be + * destroyed and no further operations can be performed. + */ + timeout?: number; + + /** + * Either a boolean or string. If true, tables will be nested objects. If string (e.g. '_'), tables will be + * nested as tableName_fieldName + */ + nestTables?: any; + + /** + * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future) + * to disable type casting, but you can currently do so on either the connection or query level. (Default: true) + * + * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself. + * + * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. + * + * field.string() + * field.buffer() + * field.geometry() + * + * are aliases for + * + * parser.parseLengthCodedString() + * parser.parseLengthCodedBuffer() + * parser.parseGeometryValue() + * + * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast + */ + typeCast?: any; + } + + export interface IStreamOptions { + /** + * Sets the max buffer size in objects of a stream + */ + highWaterMark?: number; + + /** + * The object mode of the stream (Default: true) + */ + objectMode?: any; + } + + export interface IConnectionOptions { + /** + * The MySQL user to authenticate as + */ + user?: string; + + /** + * The password of that MySQL user + */ + password?: string; + + /** + * Name of the database to use for this connection + */ + database?: string; + + /** + * The charset for the connection. This is called "collation" in the SQL-level of MySQL (like utf8_general_ci). + * If a SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used. + * (Default: 'UTF8_GENERAL_CI') + */ + charset?: string; + } + + export interface IConnectionConfig extends IConnectionOptions { + /** + * The hostname of the database you are connecting to. (Default: localhost) + */ + host?: string; + + /** + * The port number to connect to. (Default: 3306) + */ + port?: number; + + /** + * The source IP address to use for TCP connection + */ + localAddress?: string; + + /** + * The path to a unix domain socket to connect to. When used host and port are ignored + */ + socketPath?: string; + + /** + * The timezone used to store local dates. (Default: 'local') + */ + timezone?: string; + + /** + * The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default: 10 seconds) + */ + connectTimeout?: number; + + /** + * Stringify objects instead of converting to values. (Default: 'false') + */ + stringifyObjects?: boolean; + + /** + * Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default: false) + */ + insecureAuth?: boolean; + + /** + * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future) + * to disable type casting, but you can currently do so on either the connection or query level. (Default: true) + * + * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself. + * + * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. + * + * field.string() + * field.buffer() + * field.geometry() + * + * are aliases for + * + * parser.parseLengthCodedString() + * parser.parseLengthCodedBuffer() + * parser.parseGeometryValue() + * + * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast + */ + typeCast?: any; + + /** + * A custom query format function + */ + queryFormat?: (query: string, values: any) => void; + + /** + * When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option + * (Default: false) + */ + supportBigNumbers?: boolean; + + /** + * Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be + * always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving + * bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately + * represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5) + * (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects. + * This option is ignored if supportBigNumbers is disabled. + */ + bigNumberStrings?: boolean; + + /** + * Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript Date + * objects. (Default: false) + */ + dateStrings?: boolean; + + /** + * This will print all incoming and outgoing packets on stdout. + * You can also restrict debugging to packet types by passing an array of types (strings) to debug; + * + * (Default: false) + */ + debug?: any; + + /** + * Generates stack traces on Error to include call site of library entrance ("long stack traces"). Slight + * performance penalty for most calls. (Default: true) + */ + trace?: boolean; + + /** + * Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false) + */ + multipleStatements?: boolean; + + /** + * List of connection flags to use other than the default ones. It is also possible to blacklist default ones + */ + flags?: Array; + + /** + * object with ssl parameters or a string containing name of ssl profile + */ + ssl?: any; + } + + export interface IPoolConfig extends IConnectionConfig { + /** + * The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout, + * because acquiring a pool connection does not always involve making a connection. (Default: 10 seconds) + */ + acquireTimeout?: number; + + /** + * Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue + * the connection request and call it when one becomes available. If false, the pool will immediately call back with an error. + * (Default: true) + */ + waitForConnections?: boolean; + + /** + * The maximum number of connections to create at once. (Default: 10) + */ + connectionLimit?: number; + + /** + * The maximum number of connection requests the pool will queue before returning an error from getConnection. If set to 0, there + * is no limit to the number of queued connection requests. (Default: 0) + */ + queueLimit?: number; + } + + export interface IPoolClusterConfig { + /** + * If true, PoolCluster will attempt to reconnect when connection fails. (Default: true) + */ + canRetry?: boolean; + + /** + * If connection fails, node's errorCount increases. When errorCount is greater than removeNodeErrorCount, + * remove a node in the PoolCluster. (Default: 5) + */ + removeNodeErrorCount?: number; + + /** + * The default selector. (Default: RR) + * RR: Select one alternately. (Round-Robin) + * RANDOM: Select the node by random function. + * ORDER: Select the first node available unconditionally. + */ + defaultSelector?: string; + } + + export interface ISslCredentials { + /** + * A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates + */ + pfx?: string; + + /** + * A string holding the PEM encoded private key + */ + key?: string; + + /** + * A string of passphrase for the private key or pfx + */ + passphrase?: string; + + /** + * A string holding the PEM encoded certificate + */ + cert?: string; + + /** + * Either a string or list of strings of PEM encoded CA certificates to trust. + */ + ca?: Array; + + /** + * Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List) + */ + crl?: Array; + + /** + * A string describing the ciphers to use or exclude + */ + ciphers?: string; + } + + export interface IError extends Error { + /** + * Either a MySQL server error (e.g. 'ER_ACCESS_DENIED_ERROR'), + * a node.js error (e.g. 'ECONNREFUSED') or an internal error + * (e.g. 'PROTOCOL_CONNECTION_LOST'). + */ + code: string; + + /** + * The error number for the error code + */ + errno: number; + + /** + * The sql state marker + */ + sqlStateMarker?: string; + + /** + * The sql state + */ + sqlState?: string; + + /** + * The field count + */ + fieldCount?: number; + + /** + * The stack trace for the error + */ + stack?: string; + + /** + * Boolean, indicating if this error is terminal to the connection object. + */ + fatal: boolean; + } +} + +declare module 'mysql' { + var mysql: mysql.IMySql; + + export = mysql; +} From 4f562b1706cfdae66a74df298d0938151390f7a6 Mon Sep 17 00:00:00 2001 From: Will Johnston Date: Sun, 3 Aug 2014 16:44:58 -0500 Subject: [PATCH 103/167] Fixed mysql tests --- mysql/mysql-tests.ts | 6 +++--- mysql/mysql.d.ts | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/mysql/mysql-tests.ts b/mysql/mysql-tests.ts index 81f1e7766..83fdeb06a 100644 --- a/mysql/mysql-tests.ts +++ b/mysql/mysql-tests.ts @@ -109,7 +109,7 @@ sql = mysql.format(sql, inserts); connection.config.queryFormat = function (query, values) { if (!values) return query; - return query.replace(/\:(\w+)/g, function (txt, key) { + return query.replace(/\:(\w+)/g, function (txt: string, key: string) { if (values.hasOwnProperty(key)) { return this.escape(values[key]); } @@ -173,7 +173,7 @@ pool.on('connection', function (connection) { connection.query('SET SESSION auto_increment_increment=1') }); -pool.getConnection(function (err, connection: mysql.IConnection) { +pool.getConnection(function (err, connection) { // Use the connection connection.query('SELECT something FROM sometable', function (err, rows) { // And done with the connection. @@ -368,7 +368,7 @@ var query = connection.query({ sql: '...', typeCast: false }, function (err, res connection.query({ sql: '...', - typeCast: function (field, next) { + typeCast: function (field: any, next: Function) { if (field.type == 'TINY' && field.length == 1) { return (field.string() == '1'); // 1 = true, 0 = false } diff --git a/mysql/mysql.d.ts b/mysql/mysql.d.ts index 3df338e47..479b05266 100644 --- a/mysql/mysql.d.ts +++ b/mysql/mysql.d.ts @@ -44,7 +44,6 @@ declare module mysql { query: IQueryFunction; end(): void; - end(options: any): void; end(callback: (err: IError, ...args: any[]) => void): void; end(options: any, callback: (err: IError, ...args: any[]) => void): void; From 11737fa5b1cceb4401f7c7435b0da4bdc1c334c6 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Mon, 10 Feb 2014 17:40:59 +0000 Subject: [PATCH 104/167] Update angular.d.ts The listener may take a single event argument. --- angularjs/angular.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..59a33e715 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,6 +337,7 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 783404bd8a37e11559f499ce16465d25d5c88f2f Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Tue, 25 Feb 2014 17:32:17 +0000 Subject: [PATCH 105/167] Update angular-ui-router.d.ts --- angular-ui/angular-ui-router.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 081d35723..889325aa4 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,6 +85,7 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; + $current: IState; params: IStateParamsService; reload(): void; } From 18ef03e31dfc89e937de12d43206f288c72d98b2 Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Tue, 25 Feb 2014 17:37:58 +0000 Subject: [PATCH 106/167] Revert "Update angular.d.ts" This reverts commit 0690841c6b5d33bfcbf91be3b02f13e63c990ed1. --- angularjs/angular.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 59a33e715..e447985fb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,7 +337,6 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 9bdeb5e6c85654a38684cf2a4914d05706da64ce Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:01:21 +0100 Subject: [PATCH 107/167] Revert 783404b..18ef03e This rolls back to commit 783404bd8a37e11559f499ce16465d25d5c88f2f. --- angularjs/angular.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..59a33e715 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,6 +337,7 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 8d1e03ff7791b3f4fc79846ba8995110d917a174 Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:01:40 +0100 Subject: [PATCH 108/167] Revert aec2fa9..9bdeb5e This rolls back to commit aec2fa9e392a883dfa4467ba12a6934f24d50a9e. --- angular-ui/angular-ui-router.d.ts | 1 - angularjs/angular.d.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 889325aa4..081d35723 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,7 +85,6 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; - $current: IState; params: IStateParamsService; reload(): void; } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 59a33e715..e447985fb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,7 +337,6 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From d5ddb0544b0455cf20702f4af36d6c62e400f74e Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:02:13 +0100 Subject: [PATCH 109/167] Revert "Revert aec2fa9..9bdeb5e" This reverts commit 8d1e03ff7791b3f4fc79846ba8995110d917a174. --- angular-ui/angular-ui-router.d.ts | 1 + angularjs/angular.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 081d35723..889325aa4 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,6 +85,7 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; + $current: IState; params: IStateParamsService; reload(): void; } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..59a33e715 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,6 +337,7 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From d17f3145a523e76a876e6d864c708f2d8cfb4dff Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:03:42 +0100 Subject: [PATCH 110/167] Revert "Revert "Revert aec2fa9..9bdeb5e"" This reverts commit d5ddb0544b0455cf20702f4af36d6c62e400f74e. --- angular-ui/angular-ui-router.d.ts | 1 - angularjs/angular.d.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 889325aa4..081d35723 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,7 +85,6 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; - $current: IState; params: IStateParamsService; reload(): void; } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 59a33e715..e447985fb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -337,7 +337,6 @@ declare module ng { $new(isolate?: boolean): IScope; $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - $on(name: string, listener: (event: IAngularEvent, eventArg: any) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; From 24df639f25cd60e06b47cef6887b151ee6849749 Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:21:54 +0100 Subject: [PATCH 111/167] Add grunt.log.warn method --- gruntjs/gruntjs-tests.ts | 43 ++++++++++++++++++++++++++++++++++++++++ gruntjs/gruntjs.d.ts | 5 +++++ 2 files changed, 48 insertions(+) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index 853cac370..fe0f7ace9 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -73,3 +73,46 @@ exports = (grunt: IGrunt) => { fileMaps[0].src.length; fileMaps[0].dest; }; + +// Official grunt task template from +// https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js +exports.exports = function(grunt: IGrunt) { + + // Please see the Grunt documentation for more information regarding task + // creation: http://gruntjs.com/creating-tasks + + grunt.registerMultiTask('taskName', 'task description', function() { + // Merge task-specific and/or target-specific options with these defaults. + var options = this.options({ + punctuation: '.', + separator: ', ' + }); + + // Iterate over all specified file groups. + this.files.forEach(function(f) { + // Concat specified files. + var src = f.src.filter(function(filepath) { + // Warn on and remove invalid source files (if nonull was set). + if (!grunt.file.exists(filepath)) { + grunt.log.warn('Source file "' + filepath + '" not found.'); + return false; + } else { + return true; + } + }).map(function(filepath) { + // Read file source. + return grunt.file.read(filepath); + }).join(grunt.util.normalizelf(options.separator)); + + // Handle options. + src += options.punctuation; + + // Write the destination file. + grunt.file.write(f.dest, src); + + // Print a success message. + grunt.log.writeln('File "' + f.dest + '" created.'); + }); + }); + +}; \ No newline at end of file diff --git a/gruntjs/gruntjs.d.ts b/gruntjs/gruntjs.d.ts index 86923c56e..8efa08ef6 100644 --- a/gruntjs/gruntjs.d.ts +++ b/gruntjs/gruntjs.d.ts @@ -690,6 +690,11 @@ declare module grunt { * Log a list of obj properties (good for debugging flags). */ writeflags(obj: any): T + + /** + * Log an warning with grunt.log.warn + */ + warn(msg: string): T } /** From 10c19f9b75e97ba6706da7aaea938ed411a5dcd9 Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:26:17 +0100 Subject: [PATCH 112/167] Revert "Merge branch 'master' of https://github.com/martinmcwhorter/DefinitelyTyped" This reverts commit 00124520f75bdc8151bc2c1427dd8dd5a2404a1b, reversing changes made to d17f3145a523e76a876e6d864c708f2d8cfb4dff. --- angular-ui/angular-ui-router.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 889325aa4..081d35723 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -85,7 +85,6 @@ declare module ng.ui { get(state: string): IState; get(): IState[]; current: IState; - $current: IState; params: IStateParamsService; reload(): void; } From 78289250ff3fdfd485eb11d55d133283797b906e Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:28:26 +0100 Subject: [PATCH 113/167] Revert old changes --- gruntjs/gruntjs-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index fe0f7ace9..6807cd96e 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -75,6 +75,7 @@ exports = (grunt: IGrunt) => { }; // Official grunt task template from +// Official grunt task template from // https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js exports.exports = function(grunt: IGrunt) { From f2d7f68db344ae9b7490523e22caf525f093306c Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 01:29:07 +0100 Subject: [PATCH 114/167] revert bad changes --- gruntjs/gruntjs-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index 6807cd96e..5fa560d86 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -74,7 +74,6 @@ exports = (grunt: IGrunt) => { fileMaps[0].dest; }; -// Official grunt task template from // Official grunt task template from // https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js exports.exports = function(grunt: IGrunt) { From b32f41a55cbd9a40a0d62c1b6e57fed486df43fa Mon Sep 17 00:00:00 2001 From: Saftpresse99 Date: Mon, 4 Aug 2014 09:58:08 +0200 Subject: [PATCH 115/167] Update angular-translate.d.ts Improvements ITranslateService --- angular-translate/angular-translate.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 313ef8635..4b8da8449 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -33,13 +33,14 @@ declare module ng.translate { } interface ITranslateService { - (key: string, ...params: string[]): ng.IPromise; + (translationId: string, interpolateParams?: any, interpolationId?: string): ng.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string): ng.IPromise<{ [key: string]: string }>; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; fallbackLanguage(langKey?: string[]): string; instant(translationId: string, interpolateParams?: any, interpolationId?: string): string; - instant(translationId: string[], interpolateParams?: any, interpolationId?: string): string; + instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string }; isPostCompilingEnabled(): boolean; preferredLanguage(): string; proposedLanguage(): string; From 86ac984bb0e8019a2c0d583a07a5cbb6f0f18886 Mon Sep 17 00:00:00 2001 From: San Chen Date: Mon, 4 Aug 2014 16:16:54 +0800 Subject: [PATCH 116/167] needle definitions added --- CONTRIBUTORS.md | 1 + needle/needle-tests.ts | 14 ++++++++++++++ needle/needle.d.ts | 16 ++++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 needle/needle-tests.ts create mode 100644 needle/needle.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index aafef048d..2bba0b895 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -249,6 +249,7 @@ All definitions files include a header with the author and editors, so at some p * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) * [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo)) +* [needle](https://github.com/tomas/needle) (by [San Chen](https://github.com/bigsan)) * [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook)) * [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici)) * [Node.js](http://nodejs.org/) (from TypeScript samples) diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts new file mode 100644 index 000000000..70c88933c --- /dev/null +++ b/needle/needle-tests.ts @@ -0,0 +1,14 @@ +/// + +import needle = require("needle"); + +var url = ""; +var options = {}; +var callback = (err, resp) => {}; + +needle.head(url, options, callback); +needle.get(url, options, callback); +needle.post(url, data, options, callback); +needle.put(url, data, options, callback); +needle.delete(url, data, options, callback); +needle.request(method, url, data, options, callback); diff --git a/needle/needle.d.ts b/needle/needle.d.ts new file mode 100644 index 000000000..732f5a059 --- /dev/null +++ b/needle/needle.d.ts @@ -0,0 +1,16 @@ +// Type definitions for needle 0.7.8 +// Project: https://github.com/tomas/needle +// Definitions by: San Chen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface INeedle { + head(url: string): IReadableStream; + head(url: string, callback?: Function): IReadableStream; + head(url: string, options?: any, callback?: Function): IReadableStream; + +} + +declare module "needle" { + var needle: INeedle; + export = needle; +} From 56bb95a53205c4d38436436109bd12255394c662 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Mon, 4 Aug 2014 10:48:11 +0200 Subject: [PATCH 117/167] MomentJs: Fixed some return values and made parameters optional --- moment/moment.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/moment/moment.d.ts b/moment/moment.d.ts index f14c7d4be..344885f1b 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -1,6 +1,6 @@ // Type definitions for Moment.js 2.5.0 // Project: https://github.com/timrwood/moment -// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi +// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink // Definitions: https://github.com/borisyankov/DefinitelyTyped interface MomentInput { @@ -203,9 +203,9 @@ interface Moment { isSame(b: Date, granularity: string): boolean; isSame(b: number[], granularity: string): boolean; - lang(language: string): void; - lang(reset: boolean): void; - lang(): string; + lang(language: string): Moment; + lang(reset: boolean): Moment; + lang(): MomentLanguage; max(date: Date): Moment; max(date: number): Moment; @@ -313,8 +313,8 @@ interface MomentStatic { isMoment(): boolean; isMoment(m: any): boolean; - lang(language: string): any; - lang(language: string, definition: MomentLanguage): any; + lang(language?: string): string; + lang(language?: string, definition?: MomentLanguage): string; longDateFormat: any; relativeTime: any; meridiem: (hour: number, minute: number, isLowercase: boolean) => string; From 5c2007a539bb4f244b6ce61899c4bedd9b58bde8 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Mon, 4 Aug 2014 11:20:14 +0200 Subject: [PATCH 118/167] TypeScript validity --- leaflet/leaflet.d.ts | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 7f7b8dc9a..bc4e7be90 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1244,7 +1244,7 @@ declare module L { enabled(): boolean; } - export class Handler extends Class implements IHandler { + export class Handler extends Class { initialize(map: Map): void; } } @@ -1269,10 +1269,8 @@ declare module L { } declare module L { - export var Mixin: any; - - module Mixin { - export interface LeafletMixinEvents implements IEventPowered { + export module Mixin { + export interface LeafletMixinEvents extends IEventPowered { } export var Events: LeafletMixinEvents; @@ -2418,8 +2416,9 @@ declare module L { * * Default value: true. */ - scrollWheelZoom?: boolean; scrollWheelZoom?: string; + //scrollWheelZoom?: boolean; + //scrollWheelZoom?: string; /** * Whether the map can be zoomed in by double clicking on it and zoomed out @@ -2429,8 +2428,9 @@ declare module L { * * Default value: true. */ - doubleClickZoom?: boolean; doubleClickZoom?: string; + //doubleClickZoom?: boolean; + //doubleClickZoom?: string; /** * Whether the map can be zoomed to a rectangular area specified by dragging @@ -3428,12 +3428,9 @@ declare module L { /** * Returns the content of the popup. */ - getContent(): string; - - /** - * Returns the content of the popup. - */ - getContent(): HTMLElement; + getContent(): any; + //getContent(): string; + //getContent(): HTMLElement; //////////// //////////// From bc1961484a80a021716600123785cedfb1376cc9 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Mon, 4 Aug 2014 13:08:49 +0200 Subject: [PATCH 119/167] [leaflet] small adjustments --- leaflet/leaflet.d.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index bc4e7be90..3332f9000 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -2183,7 +2183,7 @@ declare module L { /** * Closes the popup previously opened with openPopup (or the given one). */ - closePopup(): Map; + closePopup(popup?: Popup): Map; /** * Adds the given control to the map. @@ -2416,7 +2416,7 @@ declare module L { * * Default value: true. */ - scrollWheelZoom?: string; + scrollWheelZoom?: any; //scrollWheelZoom?: boolean; //scrollWheelZoom?: string; @@ -2739,7 +2739,12 @@ declare module L { /** * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). */ - toGeoJSON(popup: Popup, options?: PopupOptions): any; + toGeoJSON(): any; + + /** + * Marker dragging handler (by both mouse and touch). + */ + dragging: IHandler; //////////// //////////// @@ -3428,9 +3433,8 @@ declare module L { /** * Returns the content of the popup. */ - getContent(): any; + getContent(): HTMLElement; //getContent(): string; - //getContent(): HTMLElement; //////////// //////////// From 1cbee878f7753f66ee562789bb5acc9a063b86c2 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Mon, 4 Aug 2014 13:09:19 +0200 Subject: [PATCH 120/167] [leaflet] Brand new test file --- leaflet/leaflet-tests.ts | 301 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 301 insertions(+) create mode 100644 leaflet/leaflet-tests.ts diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts new file mode 100644 index 000000000..c07a651d8 --- /dev/null +++ b/leaflet/leaflet-tests.ts @@ -0,0 +1,301 @@ +/// + +// initialize the map on the "map" div with a given center and zoom + +var div = document.getElementById('map'); + +var map : L.Map = L.map(div, { + center: L.latLng([51.505, -0.09]), + zoom: 13, + minZoom: 3, + maxZoom: 8, + maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]), + dragging: true, + touchZoom: true, + scrollWheelZoom: true, + boxZoom: true, + tap: true, + + tapTolerance: 30, + trackResize: true, + worldCopyJump: false, + closePopupOnClick: true, + bounceAtZoomLimits: true, + + keyboard: true, + keyboardPanOffset: 80, + keyboardZoomOffset: 1, + + inertia: true, + inertiaDeceleration: 3000, + inertiaMaxSpeed: 1500, + inertiaThreshold: 32, + + zoomControl: true, + attributionControl: true, + + fadeAnimation: true, + zoomAnimation: true, + zoomAnimationThreshold: 4, + markerZoomAnimation: true + +}); + +map.dragging.enable(); +map.touchZoom.enable(); +map.scrollWheelZoom.enable(); +map.doubleClickZoom.enable(); +map.boxZoom.enable(); +map.tap.enable(); + +map.setView(new L.LatLng(42, 51)); +map.setView(L.latLng(42, 51)); + +map.setView(L.latLng(42, 51), 12); +map.setView(L.latLng(42, 51), 12, { + reset: true, + pan: { + animate: true, + duration: 0.25, + easeLinearity: 0.25, + noMoveStart: false + }, + zoom: { + animate: true + } +}); + +map.setZoom(50); +map.setZoom(50, {}); + +map.zoomIn(); +map.zoomOut(); + +map.zoomIn(2); +map.zoomOut(2); + +map.zoomIn(2, { animate: true }); +map.zoomOut(2, { animate: true }); + +map.setZoomAround(L.latLng(42, 51), 8, { animate: false }); + +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), { + paddingTopLeft: L.point(20, 20), + paddingBottomRight: L.point(20, 20), + padding: L.point(0, 0), + maxZoom: null +}); + +map.fitWorld(); + +map.fitWorld({ + animate: false +}); + +map.panTo(L.latLng(42, 42)); +map.panTo(L.latLng(42, 42), { + animate: true +}); + +map.invalidateSize(true); +map.invalidateSize({ reset: true }); + +map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); + +map.locate(); +map.locate({ + watch: false, + setView: false, + maxZoom: 18, + timeout: 10000, + maximumAge: 0, + enableHighAccuracy: false +}); + +map.stopLocate(); + +map.remove(); + +var center : L.LatLng = map.getCenter(); +var zoom : number = map.getZoom(); +var minZoom: number = map.getMinZoom(); +var maxZoom: number = map.getMaxZoom(); +var bounds: L.LatLngBounds = map.getBounds(); +var boundsZoom: number = map.getBoundsZoom(bounds, true); +var size: L.Point = map.getSize(); +var pixelBounds: L.Bounds = map.getPixelBounds(); +var pixelOrigin: L.Point = map.getPixelOrigin(); + +var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); + +map.addLayer(layer); +map.addLayer(layer, false); + +map.removeLayer(layer); +map.hasLayer(layer); + +map.openPopup("canard", L.latLng(42, 51)); + +var popup = L.popup({ + autoPan: true +}); + +map.openPopup(popup); +map.closePopup(popup); +map.closePopup(); + +map.addControl(L.control.attribution({position: 'bottomright'})); +map.removeControl(L.control.attribution({ position: 'bottomright' })); + +map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0))); +map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0))); +map.containerPointToLayerPoint(L.point(0, 0)); +map.layerPointToContainerPoint(L.point(0, 0)); + +map.project(map.unproject(L.point(10, 20))); +map.project(map.unproject(L.point(10, 20), 12), 12); + +var mouseEvent: L.LeafletMouseEvent; +map.mouseEventToContainerPoint(mouseEvent); +map.mouseEventToLayerPoint(mouseEvent); +map.mouseEventToLatLng(mouseEvent); + +map.getContainer().classList.add('roger'); +map.getPanes().mapPane.classList.add('roger'); +map.getPanes().markerPane.classList.add('roger'); +map.getPanes().objectsPane.classList.add('roger'); +map.getPanes().overlayPane.classList.add('roger'); +map.getPanes().popupPane.classList.add('roger'); +map.getPanes().shadowPane.classList.add('roger'); +map.getPanes().tilePane.classList.add('roger'); + +map.whenReady((m: L.Map) => { + m.zoomOut(); +}); + +map.on('click', () => { + map.zoomOut(); +}); + +map.off('dblclick', L.Util.falseFn); + +map.once('contextmenu', (e: L.LeafletMouseEvent) => { + map.openPopup('contextmenu', e.latlng); +}); + +var marker = L.marker(L.latLng(42, 51), { + icon: L.icon({ + iconURl: 'roger.png', + iconRetinaUrl: 'roger-retina.png', + iconSize: L.point(40, 40), + iconAnchor: L.point(20, 0), + shadowUrl: 'roger-shadow.png', + shadowRetinaUrl: 'roger-shadow-retina.png', + shadowSize: L.point(44, 44), + shadowAnchor: L.point(22, 0), + popupAnchor: L.point(0, 0), + className: 'roger-icon' + }), + clickable: true, + draggable: false, + keyboard: true, + title: 'this is an icon', + alt: '', + zIndexOffset: 0, + opacity: 1.0, + riseOnHover: false, + riseOffset: 250 +}); + +marker.addTo(map); + +marker.on('click', (e: L.LeafletMouseEvent) => { + map.setView(e.latlng); +}); + +marker.once('mouseover', () => { + marker.openPopup(); +}) + +marker.setLatLng(marker.getLatLng()); + +marker.setIcon(L.icon({})); + +marker.setZIndexOffset(30); +marker.setOpacity(0.8); + +marker.bindPopup(popup); +marker.unbindPopup(); +marker.bindPopup('hello', { + closeOnClick: true +}); + +marker.openPopup(); +marker.closePopup(); +marker.togglePopup(); +marker.togglePopup(); +marker.setPopupContent('hello 3') +marker.getPopup().setContent('hello 2'); +marker.update(); + +marker.toGeoJSON(); + +marker.dragging.enable(); + +popup = L.popup({ + maxWidth: 300, + minWidth: 50, + maxHeight: null, + autoPan: true, + keepInView: false, + closeButton: true, + offset: L.point(0, 6), + autoPanPaddingTopLeft: null, + autoPanPaddingBottomRight: L.point(20, 20), + autoPanPadding: L.point(5, 5), + zoomAnimation: true, + closeOnClick: null, + className: 'roger' +}); + +popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); + +popup.update(); + +var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { + foo: 'bar', + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 17, + tileSize: 256, + subdomains: ['a','b','c'], + errorTileUrl: '', + attribution: '', + tms: false, + continuousWorld: false, + noWrap: false, + zoomOffset: 0, + zoomReverse: false, + opacity: 1.0, + zIndex: null, + unloadInvisibleTiles: false, + updateWhenIdle: false, + detectRetina: true, + reuseTiles: true, + bounds: null +}); + +tileLayer.on('loading', L.Util.falseFn) + .off('loading', L.Util.falseFn) + .once('tileload', L.Util.falseFn); + +tileLayer.addTo(map); + +tileLayer.bringToBack() + .bringToFront() + .setOpacity(0.7) + .setZIndex(9) + .redraw() + .setUrl('http://perdu.com') + .getContainer(); From df1080e63a50158f3a315b9e9d938e27f45e2fb3 Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Mon, 4 Aug 2014 20:54:42 +0800 Subject: [PATCH 121/167] Added htmlparser2 definitions --- htmlparser2/htmlparser2.d.ts | 89 +++++++++++++++++++++++++++++++++ htmlparser2/htmlparser2tests.ts | 24 +++++++++ 2 files changed, 113 insertions(+) create mode 100644 htmlparser2/htmlparser2.d.ts create mode 100644 htmlparser2/htmlparser2tests.ts diff --git a/htmlparser2/htmlparser2.d.ts b/htmlparser2/htmlparser2.d.ts new file mode 100644 index 000000000..77fb0b983 --- /dev/null +++ b/htmlparser2/htmlparser2.d.ts @@ -0,0 +1,89 @@ +// Type definitions for htmlparser2 v3.7.x +// Project: https://github.com/fb55/htmlparser2/ +// Definitions by: James Roland Cabresos +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module "htmlparser2" { + + export interface Handler { + onopentag?:(name:string, attribs:{[type:string]: string}) => void; + onopentagname?:(name:string) => void; + onattribute?:(name:string, value:string) => void; + ontext?:(text:string) => void; + onclosetag?: (text:string) => void; + onprocessinginstruction?:(name:string, data:string) => void; + oncomment?:(data:string) => void; + oncommentend?:() => void; + oncdatastart?:() => void; + oncdataend?:() => void; + onerror?:(error:Error) => void; + onreset?:() => void; + onend?:() => void; + } + + export interface Options { + + /*** + * Indicates whether special tags ("); +parser.end(); \ No newline at end of file From afc1fc3ed4679698884fae628d1b5214af683963 Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Mon, 4 Aug 2014 20:59:50 +0800 Subject: [PATCH 122/167] Added htmlparser2, morgan, and passport-facebook contributor --- CONTRIBUTORS.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..216b74568 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -124,6 +124,7 @@ All definitions files include a header with the author and editors, so at some p * [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) +* [htmlparser2](https://github.com/fb55/htmlparser2/) (by [James Roland Cabresos](https://github.com/staticfunction)) * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) @@ -244,6 +245,7 @@ All definitions files include a header with the author and editors, so at some p * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee)) * [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [morgan](hhttps://github.com/expressjs/morgan) (by [James Roland Cabresos](https://github.com/staticfunction/)) * [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) @@ -267,6 +269,7 @@ All definitions files include a header with the author and editors, so at some p * [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [passport-facebook](https://github.com/jaredhanson/passport-facebook) (by [James Roland Cabresos](https://github.com/staticfunction/)) * [passport-strategy](https://github.com/jaredhanson/passport-strategy) (by [Lior Mualem](https://github.com/liorm)) * [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame)) * [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) From 9a0a71177653bda672905ba6605aa319877dcf8e Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Mon, 4 Aug 2014 21:02:17 +0800 Subject: [PATCH 123/167] fix a typo --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 216b74568..8098540ed 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -245,7 +245,7 @@ All definitions files include a header with the author and editors, so at some p * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee)) * [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) -* [morgan](hhttps://github.com/expressjs/morgan) (by [James Roland Cabresos](https://github.com/staticfunction/)) +* [morgan](https://github.com/expressjs/morgan/) (by [James Roland Cabresos](https://github.com/staticfunction/)) * [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) From 913218129823ae1659d5d539f5df61d9d277add0 Mon Sep 17 00:00:00 2001 From: martinmcwhorter Date: Mon, 4 Aug 2014 15:38:01 +0100 Subject: [PATCH 124/167] added missing type hints --- gruntjs/gruntjs-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index 5fa560d86..6b8607329 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -89,9 +89,9 @@ exports.exports = function(grunt: IGrunt) { }); // Iterate over all specified file groups. - this.files.forEach(function(f) { + this.files.forEach(function(f: grunt.file.IFilesConfig) { // Concat specified files. - var src = f.src.filter(function(filepath) { + var src = f.src.filter(function(filepath: string) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); From e49477e675eee56f171284a75066d58f85b76156 Mon Sep 17 00:00:00 2001 From: Will Johnston Date: Mon, 4 Aug 2014 09:46:50 -0500 Subject: [PATCH 125/167] Updated with mysql contributor --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..c5096509b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -247,6 +247,7 @@ All definitions files include a header with the author and editors, so at some p * [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) +* [mysql](https://github.com/felixge/node-mysql) (by [William Johnston](https://github.com/wjohnsto)) * [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo)) * [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook)) * [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici)) From e3a212a892852cd4b8a5dccd6347ae32f4cfc187 Mon Sep 17 00:00:00 2001 From: Holger Stitz Date: Mon, 4 Aug 2014 17:02:03 +0200 Subject: [PATCH 126/167] Added the nodeSize function to TreeLayout Documentation https://github.com/mbostock/d3/wiki/Tree-Layout#nodeSize --- d3/d3.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 0354bc264..637afcc0c 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1159,6 +1159,19 @@ declare module D3 { */ (size: Array): TreeLayout; }; + /** + * Gets or sets the available node size + */ + nodeSize: { + /** + * Gets the available node size + */ + (): Array; + /** + * Sets the available node size + */ + (size: Array): TreeLayout; + }; } export interface PieLayout { From 7a8afe9eccb19ce169bdfddf05666e90e17d1f20 Mon Sep 17 00:00:00 2001 From: Evgenus Date: Mon, 4 Aug 2014 19:40:22 +0300 Subject: [PATCH 127/167] definitions for Big Integer library by Tom Wu --- CONTRIBUTORS.md | 1 + jsbn/jsbn-tests.ts | 93 +++++++++++++++++ jsbn/jsbn.d.ts | 250 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 344 insertions(+) create mode 100644 jsbn/jsbn-tests.ts create mode 100644 jsbn/jsbn.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index af326634b..8d25e840d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -193,6 +193,7 @@ All definitions files include a header with the author and editors, so at some p * [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds)) * [js-url](https://github.com/websanova/js-url) (by [MIZUNE Pine](https://github.com/pine613)) * [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/)) +* [jsbn](http://www-cs-students.stanford.edu/%7Etjw/jsbn/) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz)) * [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk)) * [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/)) diff --git a/jsbn/jsbn-tests.ts b/jsbn/jsbn-tests.ts new file mode 100644 index 000000000..667f78553 --- /dev/null +++ b/jsbn/jsbn-tests.ts @@ -0,0 +1,93 @@ +/// +var BigInteger = jsbn.BigInteger; + +// constructor tests +var x = new BigInteger("AABB", 16); +x = new BigInteger("75643564363473453456342378564387956906736546456235345"); + +// method tests +var isBigInteger: jsbn.BigInteger; +var isNumber: number; +var isBoolean: boolean; +var isString: string; +var isDivmod: jsbn.BigInteger[]; +var isByteArray: number[]; + +x.copyTo(x); +x.fromInt(0); +x.fromString("CAFEBABE", 16); +x.clamp(); +isString = x.toString(); +isString = x.toString(16); +isBigInteger = x.negate(); +isBigInteger = x.abs(); +isNumber = x.compareTo(x); +isNumber = x.bitLength(); +x.dlShiftTo(0, isBigInteger); +x.drShiftTo(0, isBigInteger); +x.lShiftTo(0, isBigInteger); +x.rShiftTo(0, isBigInteger); +x.subTo(x, isBigInteger); +x.multiplyTo(x, isBigInteger); +x.squareTo(isBigInteger); +x.divRemTo(x, isBigInteger, isBigInteger); +isBigInteger = x.mod(x); +isNumber = x.invDigit(); +isBoolean = x.isEven(); +isBigInteger = x.exp(0, { + convert: (x) => x, + revert: (x) => x, + reduce: (x) => x, + mulTo: (x) => x, + sqrTo: (x) => x +}); +isBigInteger = x.modPowInt(0, x); +isBigInteger = x.clone(); +isNumber = x.intValue(); +isNumber = x.byteValue(); +isNumber = x.shortValue(); +isNumber = x.chunkSize(0); +isNumber = x.signum(); +isString = x.toRadix(10); +x.fromRadix("123", 10); +x.fromNumber(1); +x.fromNumber(1, 2); +x.fromNumber(1, 2, 3); +isByteArray = x.toByteArray(); +isBoolean = x.equals(x); +isBigInteger = x.min(x); +isBigInteger = x.max(x); +x.bitwiseTo(x, (x, y) => x + y, isBigInteger); +isBigInteger = x.and(x); +isBigInteger = x.or(x); +isBigInteger = x.xor(x); +isBigInteger = x.andNot(x); +isBigInteger = x.not(); +isBigInteger = x.shiftLeft(0); +isBigInteger = x.shiftRight(0); +isNumber = x.getLowestSetBit(); +isNumber = x.bitCount(); +isBoolean = x.testBit(0); +isBigInteger = x.changeBit(0, (x, y) => x * y); +isBigInteger = x.setBit(0); +isBigInteger = x.clearBit(0); +isBigInteger = x.flipBit(0); +x.addTo(x, isBigInteger); +isBigInteger = x.add(x); +isBigInteger = x.subtract(x); +isBigInteger = x.multiply(x); +isBigInteger = x.square(); +isBigInteger = x.divide(x); +isBigInteger = x.remainder(x); +isDivmod = x.divideAndRemainder(x); +x.dMultiply(0); +x.dAddOffset(0, 0); +isBigInteger = x.pow(0); +x.multiplyLowerTo(x, 0, isBigInteger); +x.multiplyUpperTo(x, 0, isBigInteger); +isBigInteger = x.modPow(x, x); +isBigInteger = x.gcd(x); +isNumber = x.modInt(0); +isBigInteger = x.modInverse(x); +isBoolean = x.isProbablePrime(0); +isBoolean = x.millerRabin(0); diff --git a/jsbn/jsbn.d.ts b/jsbn/jsbn.d.ts new file mode 100644 index 000000000..bd75bd876 --- /dev/null +++ b/jsbn/jsbn.d.ts @@ -0,0 +1,250 @@ +// Type definitions for jsbn v1.2 +// Project: http://www-cs-students.stanford.edu/%7Etjw/jsbn/ +// Definitions by: Eugene Chernyshov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module jsbn { + + interface RandomGenerator { + nextBytes(bytes: number[]): void; + } + + export class BigInteger { + constructor(a: number, c: RandomGenerator); + constructor(a: number, b: number, c: RandomGenerator); + constructor(a: string, b?: number); + constructor(a: number[], b?: number); + constructor(a: BigInteger); + + s: number; + t: number; + data: number[]; // forge specific + + DB: number; + DM: number; + DV: number; + + FV: number; + F1: number; + F2: number; + + // am: Compute w_j += (x*this_i), propagate carries, + am(i: number, x: number, w: BigInteger, j: number, c: number, n: number): number; + + // (protected) copy this to r + copyTo(r: BigInteger): void; + + // (protected) set from integer value x, -DV <= x < DV + fromInt(x: number): void; + + // (protected) set from string and radix + fromString(x: string, b: number): void; + + // (protected) clamp off excess high words + clamp(): void; + + // (public) return string representation in given radix + toString(b?: number): string; + + // (public) -this + negate(): BigInteger; + + // (public) |this| + abs(): BigInteger; + + // (public) return + if this > a, - if this < a, 0 if equal + compareTo(a: BigInteger): number; + + // (public) return the number of bits in "this" + bitLength(): number; + + // (protected) r = this << n*DB + dlShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this >> n*DB + drShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this << n + lShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this >> n + rShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this - a + subTo(a: BigInteger, r: BigInteger): void; + + // (protected) r = this * a, r != this,a (HAC 14.12) + multiplyTo(a: BigInteger, r: BigInteger): void; + + // (protected) r = this^2, r != this (HAC 14.16) + squareTo(r: BigInteger): void; + + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + divRemTo(m: BigInteger, q: BigInteger, r: BigInteger): void; + + // (public) this mod a + mod(a: BigInteger): BigInteger; + + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + invDigit(): number; + + // (protected) true iff this is even + isEven(): boolean; + + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + exp(e: number, z: Reduction): BigInteger; + + // (public) this^e % m, 0 <= e < 2^32 + modPowInt(e: number, m: BigInteger): BigInteger; + + // (public) + clone(): BigInteger; + + // (public) return value as integer + intValue(): number; + + // (public) return value as byte + byteValue(): number; + + // (public) return value as short (assumes DB>=16) + shortValue(): number; + + // (protected) return x s.t. r^x < DV + chunkSize(r: number): number; + + // (public) 0 if this == 0, 1 if this > 0 + signum(): number; + + // (protected) convert to radix string + toRadix(b: number): string; + + // (protected) convert from radix string + fromRadix(s: string, b: number): void; + + // (protected) alternate constructor + fromNumber(a: number, b?: number, c?: number): void; + + // (public) convert to bigendian byte array + toByteArray(): number[]; + + equals(a: BigInteger): boolean; + + min(a: BigInteger): BigInteger; + + max(a: BigInteger): BigInteger; + + // (protected) r = this op a (bitwise) + bitwiseTo(a: BigInteger, op: (x: number, y: number) => number, r: BigInteger): void; + + // (public) this & a + and(a: BigInteger): BigInteger; + + // (public) this | a + or(a: BigInteger): BigInteger; + + // (public) this ^ a + xor(a: BigInteger): BigInteger; + + // (public) this & ~a + andNot(a: BigInteger): BigInteger; + + // (public) ~this + not(): BigInteger; + + // (public) this << n + shiftLeft(n: number): BigInteger; + + // (public) this >> n + shiftRight(n: number): BigInteger; + + // (public) returns index of lowest 1-bit (or -1 if none) + getLowestSetBit(): number; + + // (public) return number of set bits + bitCount(): number; + + // (public) true iff nth bit is set + testBit(n: number): boolean; + + // (protected) this op (1< number): BigInteger; + + // (protected) this op (1<= 0, 1 < n < DV + dMultiply(n: number): void; + + // (protected) this += n << w words, this >= 0 + dAddOffset(n: number, w: number): void; + + // (public) this^e + pow(e: number): BigInteger; + + // (protected) r = lower n words of "this * a", a.t <= n + multiplyLowerTo(a: BigInteger, n: number, r: BigInteger): void; + + // (protected) r = "this * a" without lower n words, n > 0 + multiplyUpperTo(a: BigInteger, n: number, r: BigInteger): void; + + // (public) this^e % m (HAC 14.85) + modPow(e: BigInteger, m: BigInteger): BigInteger; + + // (public) gcd(this,a) (HAC 14.54) + gcd(a: BigInteger): BigInteger; + + // (protected) this % n, n < 2^26 + modInt(n: number): number; + + // (public) 1/this % m (HAC 14.61) + modInverse(m: BigInteger): BigInteger; + + // (public) test primality with certainty >= 1-.5^t + isProbablePrime(t: number): boolean; + + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + millerRabin(t: number): boolean; + + static ZERO: BigInteger; + static ONE: BigInteger; + } + + interface Reduction { + convert(x: BigInteger): BigInteger; + revert(x: BigInteger): BigInteger; + reduce(x: BigInteger): void; + mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void; + sqrTo(x: BigInteger, r: BigInteger): void; + } +} \ No newline at end of file From 4ea6c8e68519c2f92d4c7fa200bfafb07194d89e Mon Sep 17 00:00:00 2001 From: San Chen Date: Tue, 5 Aug 2014 09:34:14 +0800 Subject: [PATCH 128/167] needle definitions and tests added --- needle/needle-tests.ts | 112 +++++++++++++++++++++++++++++++++++++---- needle/needle.d.ts | 80 +++++++++++++++++++++++++++-- 2 files changed, 178 insertions(+), 14 deletions(-) diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 70c88933c..7283aeaa1 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -2,13 +2,107 @@ import needle = require("needle"); -var url = ""; -var options = {}; -var callback = (err, resp) => {}; +function Usage() { + // using callback + needle.get('http://ifconfig.me/all.json', function (error, response) { + if (!error) + console.log(response.body.ip_addr); // JSON decoding magic. :) + }); -needle.head(url, options, callback); -needle.get(url, options, callback); -needle.post(url, data, options, callback); -needle.put(url, data, options, callback); -needle.delete(url, data, options, callback); -needle.request(method, url, data, options, callback); + // using streams + var out; // = fs.createWriteStream('logo.png'); + needle.get('https://google.com/images/logo.png').pipe(out); +} + +function ResponsePipeline() { + needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) { + console.log(resp.body); // this little guy won't be a Gzipped binary blob + // but a nice object containing all the latest entries + }); + + var options = { + compressed: true, + follow: true, + rejectUnauthorized: true + }; + + // in this case, we'll ask Needle to follow redirects (disabled by default), + // but also to verify their SSL certificates when connecting. + var stream = needle.get('https://backend.server.com/everything.html', options); + + stream.on('readable', function () { + var data; + while (data = this.read()) { + console.log(data.toString()); + } + }); +} + +function API_head() { + var options = { + timeout: 5000 // if we don't get a response in 5 seconds, boom. + }; + + needle.head('https://my.backend.server.com', function (err, resp) { + if (err) { + console.log('Shoot! Something is wrong: ' + err.message); + } + else { + console.log('Yup, still alive.'); + } + }); +} + +function API_get() { + needle.get('google.com/search?q=syd+barrett', function (err, resp) { + // if no http:// is found, Needle will automagically prepend it. + }); +} + +function API_post() { + var options = { + headers: { 'X-Custom-Header': 'Bumbaway atuna' } + }; + + needle.post('https://my.app.com/endpoint', 'foo=bar', options, function (err, resp) { + // you can pass params as a string or as an object. + }); +} + +function API_put() { + var nested = { + params: { + are: { + also: 'supported' + } + } + }; + + needle.put('https://api.app.com/v2', nested, function (err, resp) { + console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella. + }); +} + +function API_delete() { + var options = { + username: 'fidelio', + password: 'x' + }; + + needle.delete('https://api.app.com/messages/123', null, options, function (err, resp) { + // in this case, data may be null, but you need to explicity pass it. + }); +} + +function API_request() { + var data = { + q: 'a very smart query', + page: 2, + format: 'json' + }; + + needle.request('get', 'forum.com/search', data, function (err, resp) { + if (!err && resp.statusCode == 200) + console.log(resp.body); // here you go, mister. + }); +} diff --git a/needle/needle.d.ts b/needle/needle.d.ts index 732f5a059..f4c20408f 100644 --- a/needle/needle.d.ts +++ b/needle/needle.d.ts @@ -3,14 +3,84 @@ // Definitions by: San Chen // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface INeedle { - head(url: string): IReadableStream; - head(url: string, callback?: Function): IReadableStream; - head(url: string, options?: any, callback?: Function): IReadableStream; +/// +declare module Needle { + + interface Callback { + (error: Error, response: any, body: any): void; + } + + interface RequestOptions { + timeout?: number; + follow?: any; // number | string + multipart?: boolean; + proxy?: string; + agent?: string; + headers?: any; + auth?: string; // auto | digest | basic (default) + json?: boolean; + } + + interface ResponseOptions { + decode?: boolean; + parse?: boolean; + output?: any; + } + + interface HttpHeaderOptions { + compressed?: boolean; + username?: string; + password?: string; + accept?: string; + connection?: string; + user_agent?: string; + } + + interface TLSOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: any; + rejectUnauthorized?: boolean; + secureProtocol?: any; + } + + interface NeedleOptions extends RequestOptions, ResponseOptions, HttpHeaderOptions, TLSOptions { + } + + interface NeedleStatic { + defaults(options?: any): void; + + head(url: string): ReadableStream; + head(url: string, callback?: Callback): ReadableStream; + head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + + get(url: string): ReadableStream; + get(url: string, callback?: Callback): ReadableStream; + get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + + post(url: string, data: any): ReadableStream; + post(url: string, data: any, callback?: Callback): ReadableStream; + post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + put(url: string, data: any): ReadableStream; + put(url: string, data: any, callback?: Callback): ReadableStream; + put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + delete(url: string, data: any): ReadableStream; + delete(url: string, data: any, callback?: Callback): ReadableStream; + delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + request(method: string, url: string, data: any): ReadableStream; + request(method: string, url: string, data: any, callback?: Callback): ReadableStream; + request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + } } declare module "needle" { - var needle: INeedle; + var needle: Needle.NeedleStatic; export = needle; } From 53558dd1643bc3a2939a51446c06e5f8c9f2d7a8 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Tue, 5 Aug 2014 11:15:55 +0900 Subject: [PATCH 129/167] Add http-string-parser --- CONTRIBUTORS.md | 1 + http-string-parser/http-string-parser-test.ts | 42 +++++++++++++++++++ http-string-parser/http-string-parser.d.ts | 38 +++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 http-string-parser/http-string-parser-test.ts create mode 100644 http-string-parser/http-string-parser.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index aafef048d..5da07cb74 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -125,6 +125,7 @@ All definitions files include a header with the author and editors, so at some p * [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) +* [http-string-parser](https://github.com/apiaryio/http-string-parser) (by [MIZUNE Pine](https://github.com/pine613)) * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) diff --git a/http-string-parser/http-string-parser-test.ts b/http-string-parser/http-string-parser-test.ts new file mode 100644 index 000000000..9c4116e5d --- /dev/null +++ b/http-string-parser/http-string-parser-test.ts @@ -0,0 +1,42 @@ +/// + +import parser = require("http-string-parser"); + +function test_request(): void { + var result = parser.parseRequest("HTTP/1.1 GET /\r\nHost: www.example.com\r\n\r\n"); + + var body: string = result.body; + var headers: { [key: string]: string } = result.headers; + var method: string = result.method; + var uri: string = result.uri; +} + +function test_response(): void { + var response = parser.parseResponse("HTTP/1.1 200 OK\r\n\r\n"); + + var body: string = response.body; + var headers: { [key: string]: string } = response.headers; + var statusCode: string = response.statusCode; + var statusMessage: string = response.statusMessage; +} + +function test_requestLine(): void { + var result = parser.parseRequestLine("HTTP/1.1 GET /"); + + var method: string = result.method; + var protocol: string = result.protocol; + var uri: string = result.uri; +} + +function test_statusLine(): void { + var result = parser.parseStatusLine("HTTP/1.1 200 OK"); + + var protocol: string = result.protocol; + var statusCode: string = result.statusCode; + var statusMessage: string = result.statusMessage; +} + +function test_headers(): void { + var result: { [key: string]: string } = + parser.parseHeaders("Content-Type: text/html; charset=utf-8\r\nContent-Length: 256\r\n"); +} \ No newline at end of file diff --git a/http-string-parser/http-string-parser.d.ts b/http-string-parser/http-string-parser.d.ts new file mode 100644 index 000000000..893457279 --- /dev/null +++ b/http-string-parser/http-string-parser.d.ts @@ -0,0 +1,38 @@ +// Type definitions for Backbone v0.9.10 +// Project: https://github.com/apiaryio/http-string-parser +// Definitions by: MIZUNE Pine +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "http-string-parser" { + interface ParseRequestResult { + method: string; + uri: string; + headers: { [key: string]: string }; + body: string; + } + + interface ParseResponseResult { + statusCode: string; + statusMessage: string; + headers: { [key: string]: string }; + body: string; + } + + interface ParseRequestLineResult { + method: string; + uri: string; + protocol: string; + } + + interface ParseStatusLineResult { + protocol: string; + statusCode: string; + statusMessage: string; + } + + export function parseRequest(requestString: string): ParseRequestResult; + export function parseResponse(responseString: string): ParseResponseResult; + export function parseRequestLine(requestLineString: string): ParseRequestLineResult; + export function parseStatusLine(statusLine: string): ParseStatusLineResult; + export function parseHeaders(headerLines: string): { [key: string]: string }; +} From e0d5a27525df14b9ba0486f326da549491f026c1 Mon Sep 17 00:00:00 2001 From: MIZUNE Pine Date: Tue, 5 Aug 2014 11:20:19 +0900 Subject: [PATCH 130/167] Fix header --- http-string-parser/http-string-parser.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http-string-parser/http-string-parser.d.ts b/http-string-parser/http-string-parser.d.ts index 893457279..4239cd9df 100644 --- a/http-string-parser/http-string-parser.d.ts +++ b/http-string-parser/http-string-parser.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Backbone v0.9.10 +// Type definitions for http-string-parser // Project: https://github.com/apiaryio/http-string-parser // Definitions by: MIZUNE Pine // Definitions: https://github.com/borisyankov/DefinitelyTyped From a77c6b79f52a74bc0ff1810215d5b32e9d65a06d Mon Sep 17 00:00:00 2001 From: San Chen Date: Tue, 5 Aug 2014 11:06:19 +0800 Subject: [PATCH 131/167] tests passed --- needle/needle-tests.ts | 4 ++-- needle/needle.d.ts | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 7283aeaa1..24d9701b5 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -10,7 +10,7 @@ function Usage() { }); // using streams - var out; // = fs.createWriteStream('logo.png'); + var out: any; // = fs.createWriteStream('logo.png'); needle.get('https://google.com/images/logo.png').pipe(out); } @@ -31,7 +31,7 @@ function ResponsePipeline() { var stream = needle.get('https://backend.server.com/everything.html', options); stream.on('readable', function () { - var data; + var data: any; while (data = this.read()) { console.log(data.toString()); } diff --git a/needle/needle.d.ts b/needle/needle.d.ts index f4c20408f..741cf5fe3 100644 --- a/needle/needle.d.ts +++ b/needle/needle.d.ts @@ -6,6 +6,8 @@ /// declare module Needle { + interface ReadableStream extends NodeJS.ReadableStream { + } interface Callback { (error: Error, response: any, body: any): void; From 982f57d1266842ef4554f639b6adf379c320f8e1 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Tue, 5 Aug 2014 13:10:10 +0200 Subject: [PATCH 132/167] Phonegap: Fixed Filesystem api --- phonegap/phonegap.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 37585887b..7d744346a 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -367,7 +367,7 @@ interface FileUploadResult { interface Flags { create: boolean; - exclusive: boolean; + exclusive?: boolean; } /* From 1ba83dded25175aa1239dd6ad0d6e0c81a3571ab Mon Sep 17 00:00:00 2001 From: Nickolas Westman Date: Tue, 5 Aug 2014 11:43:05 -0700 Subject: [PATCH 133/167] Update underscore.d.ts Template return values not correctly typed - if data is passed it will return a string (no partial templating in underscore) --- underscore/underscore.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 7d9c84f82..9736c2879 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1472,8 +1472,9 @@ interface UnderscoreStatic { * @param settings Settings to use while compiling. * @return Returns the compiled Underscore HTML template. **/ - template(templateString: string, data?: any, settings?: _.TemplateSettings): (...data: any[]) => string; - + template(templateString: string): (...data: any[]) => string; + template(templateString: string, data: any, settings?: _.TemplateSettings): string; + /** * By default, Underscore uses ERB-style template delimiters, change the * following template settings to use alternative delimiters. From f1a45e0d4e2d5260408a5f6f6a5f99269ed133de Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sat, 2 Aug 2014 13:59:17 -0300 Subject: [PATCH 134/167] directive accept classes --- angularjs/angular-tests.ts | 471 ++++++++++++++++++++----------------- angularjs/angular.d.ts | 38 ++- 2 files changed, 279 insertions(+), 230 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index a1577856e..9c1cc0ab4 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -231,11 +231,11 @@ foo.then((x) => { }).then((x) => { // Object is inferred here x.a = 123; - //Try a promise + //Try a promise var y: ng.IPromise; - return y; + return y; }).then((x) => { - // x is infered to be a number, which is the resolved value of a promise + // x is infered to be a number, which is the resolved value of a promise x.toFixed(); }); @@ -281,252 +281,289 @@ test_IAttributes({ $attr: {} }); +class SampleDirective implements ng.IDirective { + public restrict = 'A'; + name = 'doh'; + + compile(templateElement: any) { + return this.link; + } + + static instance():ng.IDirective { + return new SampleDirective(); + } + + link(scope: any) { + + } +} + +class SampleDirective2 implements ng.IDirective { + public restrict = 'EAC'; + + compile(templateElement: any) { + return { + pre: this.link + }; + } + + static instance():ng.IDirective { + return new SampleDirective2(); + } + + link(scope: any) { + + } +} + +angular.module('SameplDirective', []).directive('sampleDirective', SampleDirective.instance).directive('sameplDirective2', SampleDirective2.instance); + // test from https://docs.angularjs.org/guide/directive angular.module('docsSimpleDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - template: 'Name: {{customer.name}} Address: {{customer.address}}' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); angular.module('docsTemplateUrlDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - templateUrl: 'my-customer.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); angular.module('docsRestrictDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - templateUrl: 'my-customer.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); angular.module('docsScopeProblemExample', []) - .controller('NaomiController', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Naomi', - address: '1600 Amphitheatre' - }; - }]) - .controller('IgorController', ['$scope', function($scope: any) { - $scope.customer = { - name: 'Igor', - address: '123 Somewhere' - }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - templateUrl: 'my-customer.html' - }; - }); + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); angular.module('docsIsolateScopeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; - $scope.igor = { name: 'Igor', address: '123 Somewhere' }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - scope: { - customerInfo: '=info' - }, - templateUrl: 'my-customer-iso.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); angular.module('docsIsolationExample', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; - $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; - }]) - .directive('myCustomer', function() { - return { - restrict: 'E', - scope: { - customerInfo: '=info' - }, - templateUrl: 'my-customer-plus-vojta.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); angular.module('docsTimeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.format = 'M/d/yy h:mm:ss a'; - }]) - .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { - return { - link: function(scope: any, element: any, attrs: any) { - var format: any, - timeoutId: any; + return { + link: function(scope: any, element: any, attrs: any) { + var format: any, + timeoutId: any; - function updateTime() { - element.text(dateFilter(new Date(), format)); - } + function updateTime() { + element.text(dateFilter(new Date(), format)); + } - scope.$watch(attrs.myCurrentTime, function (value: any) { - format = value; - updateTime(); - }); + scope.$watch(attrs.myCurrentTime, function (value: any) { + format = value; + updateTime(); + }); - element.on('$destroy', function () { - $interval.cancel(timeoutId); - }); + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); - // start the UI update process; save the timeoutId for canceling - timeoutId = $interval(function () { - updateTime(); // update DOM - }, 1000); - } - }; - }]); + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); angular.module('docsTransclusionDirective', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.name = 'Tobias'; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - templateUrl: 'my-dialog.html' - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); angular.module('docsTransclusionExample', []) - .controller('Controller', ['$scope', function($scope: any) { - $scope.name = 'Tobias'; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - scope: {}, - templateUrl: 'my-dialog.html', - link: function (scope: any, element: any) { - scope.name = 'Jeff'; - } - }; - }); + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: any, element: any) { + scope.name = 'Jeff'; + } + }; + }); angular.module('docsIsoFnBindExample', []) - .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { - $scope.name = 'Tobias'; - $scope.hideDialog = function () { - $scope.dialogIsHidden = true; - $timeout(function () { - $scope.dialogIsHidden = false; - }, 2000); - }; - }]) - .directive('myDialog', function() { - return { - restrict: 'E', - transclude: true, - scope: { - 'close': '&onClose' - }, - templateUrl: 'my-dialog-close.html' - }; - }); + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); angular.module('dragModule', []) - .directive('myDraggable', ['$document', function($document: any) { - return function(scope: any, element: any, attr: any) { - var startX = 0, startY = 0, x = 0, y = 0; + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; - element.css({ - position: 'relative', - border: '1px solid red', - backgroundColor: 'lightgrey', - cursor: 'pointer' - }); + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); - element.on('mousedown', function(event: any) { - // Prevent default dragging of selected content - event.preventDefault(); - startX = event.pageX - x; - startY = event.pageY - y; - $document.on('mousemove', mousemove); - $document.on('mouseup', mouseup); - }); + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); - function mousemove(event: any) { - y = event.pageY - startY; - x = event.pageX - startX; - element.css({ - top: y + 'px', - left: x + 'px' - }); - } + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } - function mouseup() { - $document.off('mousemove', mousemove); - $document.off('mouseup', mouseup); - } - }; - }]); + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); angular.module('docsTabsExample', []) - .directive('myTabs', function() { - return { - restrict: 'E', - transclude: true, - scope: {}, - controller: function($scope: any) { - var panes: any = $scope.panes = []; + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: any) { + var panes: any = $scope.panes = []; - $scope.select = function(pane: any) { - angular.forEach(panes, function(pane: any) { - pane.selected = false; - }); - pane.selected = true; - }; + $scope.select = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; - this.addPane = function(pane: any) { - if (panes.length === 0) { - $scope.select(pane); - } - panes.push(pane); - }; - }, - templateUrl: 'my-tabs.html' - }; - }) - .directive('myPane', function() { - return { - require: '^myTabs', - restrict: 'E', - transclude: true, - scope: { - title: '@' - }, - link: function(scope, element, attrs, tabsCtrl) { - tabsCtrl.addPane(scope); - }, - templateUrl: 'my-pane.html' - }; - }); + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope.select(pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope: any, element: any, attrs: any, tabsCtrl: any) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e447985fb..e66a6c973 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1031,22 +1031,34 @@ declare module ng { (...args: any[]): IDirective; } + interface IDirectiveLinkFn { + ( + scope?: IScope, + instanceElement?: IAugmentedJQuery, + instanceAttributes?: IAttributes, + controller?: any, + transclude?: ITranscludeFunction + ): void; + } - interface IDirective{ - compile?: - (templateElement: IAugmentedJQuery, - templateAttributes: IAttributes, - transclude: ITranscludeFunction - ) => any; + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement?: IAugmentedJQuery, + templateAttributes?: IAttributes, + transclude?: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; controller?: any; controllerAs?: string; - link?: - (scope: IScope, - instanceElement: IAugmentedJQuery, - instanceAttributes: IAttributes, - controller: any, - transclude: ITranscludeFunction - ) => void; + link?: IDirectiveLinkFn; name?: string; priority?: number; replace?: boolean; From 0864d50b8c02b79e8a8f247fa671ba6170773fa5 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 6 Aug 2014 10:35:48 +0200 Subject: [PATCH 135/167] Phonegap: Added StatusBar plugin interface --- phonegap/phonegap.d.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 7d744346a..566594c51 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -575,6 +575,21 @@ interface LocalStorage { } */ +interface StatusBar { + isVisible: boolean; + + overlaysWebView(doOverlay: boolean): void; + styleDefault(): void; + styleLightContent(): void; + styleBlackTranslucent(): void; + styleBlackOpaque(): void; + backgroundColorByName(colorname: string): void; + backgroundColorByHexString(hexString: string): void; + hide(): void; + show(): void; +} +declare var StatusBar: StatusBar; + interface /*PhoneGapNavigator extends*/ Navigator { accelerometer: Accelerometer; camera: Camera; From 62aebaa52148114b7c6be270c034bf1166389915 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 6 Aug 2014 11:06:12 +0200 Subject: [PATCH 136/167] jQuery: Remove JQueryDeferred.state method because it is already defined in JQueryPromise --- jquery/jquery.d.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index e40110c16..1884180fb 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery 1.10.x / 2.0.x // Project: http://jquery.com/ -// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -525,10 +525,6 @@ interface JQueryDeferred extends JQueryPromise { * @param args An optional array of arguments that are passed to the doneCallbacks. */ resolveWith(context: any, ...args: any[]): JQueryDeferred; - /** - * Determine the current state of a Deferred object. - */ - state(): string; /** * Return a Deferred's Promise object. From 3583fdd36d63bd95fdf28ca702ed637ad530e0dc Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 6 Aug 2014 11:12:10 +0200 Subject: [PATCH 137/167] Added DickvdBrink as an author --- phonegap/phonegap.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 566594c51..17aeb1ff0 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -1,6 +1,6 @@ // Type definitions for PhoneGap 2.3 // Project: http://phonegap.com -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , Dick van den Brink // Definitions: https://github.com/borisyankov/DefinitelyTyped interface GeolocationError { From 5f30d6961a2e7db0f1045acbcfcb3ca3d98f3171 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 6 Aug 2014 09:52:35 +0200 Subject: [PATCH 138/167] Phonegap: Added Keyboard plugin --- phonegap/phonegap.d.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 17aeb1ff0..23a9babbe 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -590,6 +590,21 @@ interface StatusBar { } declare var StatusBar: StatusBar; +interface Keyboard { + automaticScrollToTopOnHiding: boolean; + isVisible: boolean; + + onshow: Function; + onhide: Function; + onshowing: Function; + onhiding: Function; + + disableScrollingInShrinkView(disable: boolean): void; + hideFormAccessoryBar(hide: boolean): void; + shrinkView(shrink: boolean): void; +} +declare var Keyboard: Keyboard; + interface /*PhoneGapNavigator extends*/ Navigator { accelerometer: Accelerometer; camera: Camera; From a90450655f562a62fc329378ce323321c80ad6f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20H=C3=A4berle?= Date: Wed, 6 Aug 2014 14:16:51 +0200 Subject: [PATCH 139/167] Added dependency to express --- express-validator/express-validator.d.ts | 318 ++++++++++++----------- 1 file changed, 165 insertions(+), 153 deletions(-) diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index b18b17e96..5a5df2fa0 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,161 +1,173 @@ // Type definitions for express-validator // Project: https://github.com/ctavan/express-validator -// Definitions by: Nathan Ridley +// Definitions by: Nathan Ridley , Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module ExpressValidator { - export interface ValidationError { - msg: string; - param: string; - } +/// - export interface RequestValidation { - check(field: string, message: string): Validator; - assert(field: string, message: string): Validator; - sanitize(field: string): Sanitizer; - onValidationError(func: (msg: string) => void): void; - } - - export interface Validator { - /** - * Alias for regex() - */ - is(): Validator; - /** - * Alias for notRegex() - */ - not(): Validator; - isEmail(): Validator; - /** - * Accepts http, https, ftp - */ - isUrl(): Validator; - /** - * Combines isIPv4 and isIPv6 - */ - isIP(): Validator; - isIPv4(): Validator; - isIPv6(): Validator; - isAlpha(): Validator; - isAlphanumeric(): Validator; - isNumeric(): Validator; - isHexadecimal(): Validator; - /** - * Accepts valid hexcolors with or without # prefix - */ - isHexColor(): Validator; - /** - * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't - */ - isInt(): Validator; - isLowercase(): Validator; - isUppercase(): Validator; - isDecimal(): Validator; - /** - * Alias for isDecimal - */ - isFloat(): Validator; - /** - * Check if length is 0 - */ - notNull(): Validator; - isNull(): Validator; - /** - * Not just whitespace (input.trim().length !== 0) - */ - notEmpty(): Validator; - equals(equals: any): Validator; - contains(str: string): Validator; - notContains(str: string): Validator; - /** - * Usage: regex(/[a-z]/i) or regex('[a-z]','i') - */ - regex(pattern: string, modifiers: string): Validator; - notRegex(pattern: string, modifiers: string): Validator; - /** - * max is optional - */ - len(min: number, max?: number): Validator; - /** - * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier - */ - isUUID(version: number): Validator; - /** - * Alias for isUUID(3) - */ - isUUIDv3(): Validator; - /** - * Alias for isUUID(4) - */ - isUUIDv4(): Validator; - /** - * Alias for isUUID(5) - */ - isUUIDv5(): Validator; - /** - * Uses Date.parse() - regex is probably a better choice - */ - isDate(): Validator; - /** - * Argument is optional and defaults to today. Comparison is non-inclusive - */ - isAfter(date: Date): Validator; - /** - * Argument is optional and defaults to today. Comparison is non-inclusive - */ - isBefore(date: Date): Validator; - isIn(options: string): Validator; - isIn(options: string[]): Validator; - notIn(options: string): Validator; - notIn(options: string[]): Validator; - max(val: string): Validator; - min(val: string): Validator; - /** - * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats - */ - isCreditCard(): Validator; - } - - interface Sanitizer { - /** - * Trim optional `chars`, default is to trim whitespace (\r\n\t ) - */ - trim(...chars: string[]): Sanitizer; - ltrim(...chars: string[]): Sanitizer; - rtrim(...chars: string[]): Sanitizer; - ifNull(replace: any): Sanitizer; - toFloat(): Sanitizer; - toInt(): Sanitizer; - /** - * True unless str = '0', 'false', or str.length == 0 - */ - toBoolean(): Sanitizer; - /** - * False unless str = '1' or 'true' - */ - toBooleanStrict(): Sanitizer; - /** - * Decode HTML entities - */ - entityDecode(): Sanitizer; - entityEncode(): Sanitizer; - /** - * Escape &, <, >, and " - */ - escape(): Sanitizer; - /** - * Remove common XSS attack vectors from user-supplied HTML - */ - xss(): Sanitizer; - /** - * Remove common XSS attack vectors from images - */ - xss(fromImages: boolean): Sanitizer; - } -} - -declare function ExpressValidator(): void; declare module "express-validator" { - export = ExpressValidator; + import express = require('express'); + + module ExpressValidator { + + export interface ValidationError { + msg: string; + param: string; + } + + export interface RequestValidation { + check(field:string, message:string): Validator; + assert(field:string, message:string): Validator; + sanitize(field:string): Sanitizer; + onValidationError(func:(msg:string) => void): void; + validationErrors() : any; + } + + export interface Validator { + /** + * Alias for regex() + */ + is(): Validator; + /** + * Alias for notRegex() + */ + not(): Validator; + isEmail(): Validator; + /** + * Accepts http, https, ftp + */ + isUrl(): Validator; + /** + * Combines isIPv4 and isIPv6 + */ + isIP(): Validator; + isIPv4(): Validator; + isIPv6(): Validator; + isAlpha(): Validator; + isAlphanumeric(): Validator; + isNumeric(): Validator; + isHexadecimal(): Validator; + /** + * Accepts valid hexcolors with or without # prefix + */ + isHexColor(): Validator; + /** + * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't + */ + isInt(): Validator; + isLowercase(): Validator; + isUppercase(): Validator; + isDecimal(): Validator; + /** + * Alias for isDecimal + */ + isFloat(): Validator; + /** + * Check if length is 0 + */ + notNull(): Validator; + isNull(): Validator; + /** + * Not just whitespace (input.trim().length !== 0) + */ + notEmpty(): Validator; + equals(equals:any): Validator; + contains(str:string): Validator; + notContains(str:string): Validator; + /** + * Usage: regex(/[a-z]/i) or regex('[a-z]','i') + */ + regex(pattern:string, modifiers:string): Validator; + notRegex(pattern:string, modifiers:string): Validator; + /** + * max is optional + */ + len(min:number, max?:number): Validator; + /** + * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier + */ + isUUID(version:number): Validator; + /** + * Alias for isUUID(3) + */ + isUUIDv3(): Validator; + /** + * Alias for isUUID(4) + */ + isUUIDv4(): Validator; + /** + * Alias for isUUID(5) + */ + isUUIDv5(): Validator; + /** + * Uses Date.parse() - regex is probably a better choice + */ + isDate(): Validator; + /** + * Argument is optional and defaults to today. Comparison is non-inclusive + */ + isAfter(date:Date): Validator; + /** + * Argument is optional and defaults to today. Comparison is non-inclusive + */ + isBefore(date:Date): Validator; + isIn(options:string): Validator; + isIn(options:string[]): Validator; + notIn(options:string): Validator; + notIn(options:string[]): Validator; + max(val:string): Validator; + min(val:string): Validator; + /** + * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats + */ + isCreditCard(): Validator; + } + + interface Sanitizer { + /** + * Trim optional `chars`, default is to trim whitespace (\r\n\t ) + */ + trim(...chars:string[]): Sanitizer; + ltrim(...chars:string[]): Sanitizer; + rtrim(...chars:string[]): Sanitizer; + ifNull(replace:any): Sanitizer; + toFloat(): Sanitizer; + toInt(): Sanitizer; + /** + * True unless str = '0', 'false', or str.length == 0 + */ + toBoolean(): Sanitizer; + /** + * False unless str = '1' or 'true' + */ + toBooleanStrict(): Sanitizer; + /** + * Decode HTML entities + */ + entityDecode(): Sanitizer; + entityEncode(): Sanitizer; + /** + * Escape &, <, >, and " + */ + escape(): Sanitizer; + /** + * Remove common XSS attack vectors from user-supplied HTML + */ + xss(): Sanitizer; + /** + * Remove common XSS attack vectors from images + */ + xss(fromImages:boolean): Sanitizer; + } + } + + /** + * + * @middlewareOptions see: https://github.com/ctavan/express-validator#middleware-options + */ + function ExpressValidator(middlewareOptions?:any):express.RequestHandler; + + + export = ExpressValidator; } From 8badcfa1b3483d78cffe8740ddf974677a94b7e4 Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Wed, 6 Aug 2014 21:33:04 +0800 Subject: [PATCH 140/167] merge new contributors --- CONTRIBUTORS.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 330bda381..1b2eda33d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -125,11 +125,8 @@ All definitions files include a header with the author and editors, so at some p * [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) -<<<<<<< HEAD * [htmlparser2](https://github.com/fb55/htmlparser2/) (by [James Roland Cabresos](https://github.com/staticfunction)) -======= * [http-string-parser](https://github.com/apiaryio/http-string-parser) (by [MIZUNE Pine](https://github.com/pine613)) ->>>>>>> upstream/master * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) From 4b232a12142f0b4751f1e2da059a2bfebe9a4f78 Mon Sep 17 00:00:00 2001 From: Joe Herman Date: Wed, 6 Aug 2014 12:47:48 -0400 Subject: [PATCH 141/167] async: Corrected APIs from forEach* to each* --- async/async-tests.ts | 5 +++-- async/async.d.ts | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/async/async-tests.ts b/async/async-tests.ts index 9b0c8e7ee..9a563276a 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -26,10 +26,11 @@ async.map(data, asyncProcess, function (err, results) { var openFiles = ['file1', 'file2']; var saveFile = function () { } -async.forEach(openFiles, saveFile, function (err) { }); +async.each(openFiles, saveFile, function (err) { }); +async.eachSeries(openFiles, saveFile, function (err) { }); var documents, requestApi; -async.forEachLimit(documents, 20, requestApi, function (err) { }); +async.eachLimit(documents, 20, requestApi, function (err) { }); async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); diff --git a/async/async.d.ts b/async/async.d.ts index d1d592629..994ed1799 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -34,9 +34,9 @@ interface AsyncQueue { interface Async { // Collections - forEach(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - forEachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - forEachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + each(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + eachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; map(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; mapSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; filter(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; From 53d09fb8068f66a6625580a793a8a4bfddb82c8e Mon Sep 17 00:00:00 2001 From: Evgenus Date: Wed, 6 Aug 2014 23:11:18 +0300 Subject: [PATCH 142/167] comments enhanced to jsDoc format --- bigint/bigint.d.ts | 364 ++++++++++++++++++++++++++++++--------------- 1 file changed, 245 insertions(+), 119 deletions(-) diff --git a/bigint/bigint.d.ts b/bigint/bigint.d.ts index 61543b1c6..b70f20fa4 100644 --- a/bigint/bigint.d.ts +++ b/bigint/bigint.d.ts @@ -13,233 +13,359 @@ declare module BigInt { export function setRandom(random: IRandom): void; - // bigInt add(x,y) - // return (x+y) for bigInts x and y. + /** + * bigInt add(x,y) + * return (x+y) for bigInts x and y. + */ export function add(x: BigInt, y: BigInt): BigInt; - // bigInt addInt(x,n) - // return (x+n) where x is a bigInt and n is an integer. + /** + * bigInt addInt(x,n) + * return (x+n) where x is a bigInt and n is an integer. + */ export function addInt(x: BigInt, n: number): BigInt; - // string bigInt2str(x,base) - // return a string form of bigInt x in a given base, with 2 <= base <= 95 - export function bigInt2str(x: BigInt, base: number): string; - export function bigInt2str(x: BigInt, base: string): string; + interface bigInt2str_T { + /** + * string bigInt2str(x,base) + * return a string form of bigInt x in a given base, with 2 <= base <= 95 + */ + (x: BigInt, base: T): string; + } - // int bitSize(x) - // return how many bits long the bigInt x is, not counting leading zeros + interface bigInt2strSignature extends bigInt2str_T, bigInt2str_T{ + } + + export var bigInt2str: bigInt2strSignature; + + /** + * int bitSize(x) + * return how many bits long the bigInt x is, not counting leading zeros + */ export function bitSize(x: BigInt): number; - // bigInt dup(x) - // return a copy of bigInt x + /** + * bigInt dup(x) + * return a copy of bigInt x + */ export function dup(x: BigInt): BigInt; - // boolean equals(x,y) - // is the bigInt x equal to the bigint y? + /** + * boolean equals(x,y) + * is the bigInt x equal to the bigint y? + */ export function equals(x: BigInt, y: BigInt): boolean; - // boolean equalsInt(x,y) - // is bigint x equal to integer y? + /** + * boolean equalsInt(x,y) + * is bigint x equal to integer y? + */ export function equalsInt(x: BigInt, y: number): boolean; - // bigInt expand(x,n) - // return a copy of x with at least n elements, adding leading zeros if needed + /** + * bigInt expand(x,n) + * return a copy of x with at least n elements, adding leading zeros if needed + */ export function expand(value: BigInt, n: number): BigInt; - // Array findPrimes(n) - // return array of all primes less than integer n + /** + * Array findPrimes(n) + * return array of all primes less than integer n + */ export function findPrimes(n: number): number[]; - // bigInt GCD(x,y) - // return greatest common divisor of bigInts x and y (each with same number of elements). + /** + * bigInt GCD(x,y) + * return greatest common divisor of bigInts x and y (each with same number of elements). + */ export function GCD(x: BigInt, y: BigInt): BigInt; - // boolean greater(x,y) - // is x>y? (x and y are nonnegative bigInts) + /** + * boolean greater(x,y) + * is x>y? (x and y are nonnegative bigInts) + */ export function greater(x: BigInt, y: BigInt): boolean; - // boolean greaterShift(x,y,shift) - // is (x <<(shift*bpe)) > y? + /** + * boolean greaterShift(x,y,shift) + * is (x <<(shift*bpe)) > y? + */ export function greaterShift(x: BigInt, y: BigInt, shift: number): boolean; - // bigInt int2bigInt(t,n,m) - // return a bigInt equal to integer t, with at least n bits and m array elements + /** + * bigInt int2bigInt(t,n,m) + * return a bigInt equal to integer t, with at least n bits and m array elements + */ export function int2bigInt(t: number, n?: number, m?: number): BigInt; - // bigInt inverseMod(x,n) - // return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null + /** + * bigInt inverseMod(x,n) + * return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null + */ export function inverseMod(x: BigInt, n: BigInt): BigInt; - // int inverseModInt(x,n) - // return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse + /** + * int inverseModInt(x,n) + * return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse + */ export function inverseModInt(x: number, n: number): BigInt; - // boolean isZero(x) - // is the bigInt x equal to zero? + /** + * boolean isZero(x) + * is the bigInt x equal to zero? + */ export function isZero(x: BigInt): boolean; - // boolean millerRabin(x,b) - // does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1=1). If s=1, then the most significant of those n bits is set to 1. + /** + * bigInt randBigInt(n,s) + * return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1. + */ export function randBigInt(n: number, s: number): BigInt; - // bigInt randTruePrime(k) - // return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + /** + * bigInt randTruePrime(k) + * return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + */ export function randTruePrime(k: number): BigInt; - // bigInt randProbPrime(k) - // return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). + /** + * bigInt randProbPrime(k) + * return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). + */ export function randProbPrime(k: number): BigInt; - // bigInt str2bigInt(s,b,n,m) - // return a bigInt for number represented in string s in base b with at least n bits and m array elements - export function str2bigInt(s: string, b: number, n?: number, m?: number): BigInt; - export function str2bigInt(s: string, b: string, n?: number, m?: number): BigInt; + interface str2bigInt_T { + /** + * bigInt str2bigInt(s,b,n,m) + * return a bigInt for number represented in string s in base b with at least n bits and m array elements + */ + (s: string, b: T, n?: number, m?: number): BigInt; + } - // bigInt sub(x,y) - // return (x-y) for bigInts x and y. Negative answers will be 2s complement + interface str2bigIntSignature extends str2bigInt_T, str2bigInt_T { + } + + export var str2bigInt: str2bigIntSignature; + + /** + * bigInt sub(x,y) + * return (x-y) for bigInts x and y. Negative answers will be 2s complement + */ export function sub(x: BigInt, y: BigInt): BigInt; - // bigInt trim(x,k) - // return a copy of x with exactly k leading zero elements + /** + * bigInt trim(x,k) + * return a copy of x with exactly k leading zero elements + */ export function trim(x: BigInt, k: number): BigInt; - // void addInt_(x,n) - // do x=x+n where x is a bigInt and n is an integer + /** + * void addInt_(x,n) + * do x=x+n where x is a bigInt and n is an integer + */ export function addInt_(x: BigInt, n: number): void; - // void add_(x,y) - // do x=x+y for bigInts x and y + /** + * void add_(x,y) + * do x=x+y for bigInts x and y + */ export function add_(x: BigInt, y: BigInt): void; - // void copy_(x,y) - // do x=y on bigInts x and y + /** + * void copy_(x,y) + * do x=y on bigInts x and y + */ export function copy_(x: BigInt, y: BigInt): void; - // void copyInt_(x,n) - // do x=n on bigInt x and integer n + /** + * void copyInt_(x,n) + * do x=n on bigInt x and integer n + */ export function copyInt_(x: BigInt, n: number): number; - // void GCD_(x,y) - // set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + /** + * void GCD_(x,y) + * set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + */ export function GCD_(x: BigInt, y: BigInt): void; - // boolean inverseMod_(x,n) - // do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist + /** + * boolean inverseMod_(x,n) + * do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist + */ export function inverseMod_(x: BigInt, n: BigInt): boolean; - // void mod_(x,n) - // do x=x mod n for bigInts x and n. (This never overflows its array). + /** + * void mod_(x,n) + * do x=x mod n for bigInts x and n. (This never overflows its array). + */ export function mod_(x: BigInt, n: BigInt): void; - // void mult_(x,y) - // do x=x*y for bigInts x and y. + /** + * void mult_(x,y) + * do x=x*y for bigInts x and y. + */ export function mult_(x: BigInt, y: BigInt): void; - // void multMod_(x,y,n) - // do x=x*y mod n for bigInts x,y,n. + /** + * void multMod_(x,y,n) + * do x=x*y mod n for bigInts x,y,n. + */ export function multMod_(x: BigInt, y: BigInt, n: BigInt): void; - // void powMod_(x,y,n) - // do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. + /** + * void powMod_(x,y,n) + * do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. + */ export function powMod_(x: BigInt, y: BigInt, n: BigInt): void; - // void randBigInt_(b,n,s) - // do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. + /** + * void randBigInt_(b,n,s) + * do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. + */ export function randBigInt_(b: BigInt, n: number, s: number): void; - // void randTruePrime_(ans,k) - // do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. + /** + * void randTruePrime_(ans,k) + * do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. + */ export function randTruePrime_(ans: BigInt, k: number): void; - // void sub_(x,y) - // do x=x-y for bigInts x and y. Negative answers will be 2s complement. + /** + * void sub_(x,y) + * do x=x-y for bigInts x and y. Negative answers will be 2s complement. + */ export function sub_(x: BigInt, y: BigInt): void; - // void addShift_(x,y,ys) - // do x=x+(y<<(ys*bpe)) + /** + * void addShift_(x,y,ys) + * do x=x+(y<<(ys*bpe)) + */ export function addShift_(x: BigInt, y: BigInt, ys: number): void; - // void carry_(x) - // do carries and borrows so each element of the bigInt x fits in bpe bits. + /** + * void carry_(x) + * do carries and borrows so each element of the bigInt x fits in bpe bits. + */ export function carry_(x: BigInt): void; - // void divide_(x,y,q,r) - // divide x by y giving quotient q and remainder r + /** + * void divide_(x,y,q,r) + * divide x by y giving quotient q and remainder r + */ export function divide_(x: BigInt, y: BigInt, q: BigInt, r: BigInt): void; - // int divInt_(x,n) - // do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). + /** + * int divInt_(x,n) + * do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). + */ export function divInt_(x: BigInt, n: number): number; - // void eGCD_(x,y,d,a,b) - // sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y + /** + * void eGCD_(x,y,d,a,b) + * sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y + */ export function eGCD_(x: BigInt, y: BigInt, d: BigInt, a: BigInt, b: BigInt): void; - // void halve_(x) - // do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). + /** + * void halve_(x) + * do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). + */ export function halve_(x: BigInt): void; - // void leftShift_(x,n) - // left shift bigInt x by n bits. n Date: Wed, 6 Aug 2014 15:33:20 -0700 Subject: [PATCH 143/167] d3: Typed Scale interface to remove duplicate code --- d3/d3.d.ts | 199 ++++++++--------------------------------------------- 1 file changed, 29 insertions(+), 170 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 8f66f47a6..619d2bb36 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1648,13 +1648,13 @@ declare module D3 { /** * Gets the x-scale associated with the brush */ - (): D3.Scale.Scale; + (): D3.Scale.UntypedScale; /** * Sets the x-scale associated with the brush * * @param accessor The new Scale */ - (scale: D3.Scale.Scale): Brush; + (scale: D3.Scale.UntypedScale): Brush; }; /** * Gets or sets the x-scale associated with the brush @@ -1663,13 +1663,13 @@ declare module D3 { /** * Gets the x-scale associated with the brush */ - (): D3.Scale.Scale; + (): D3.Scale.UntypedScale; /** * Sets the x-scale associated with the brush * * @param accessor The new Scale */ - (scale: D3.Scale.Scale): Brush; + (scale: D3.Scale.UntypedScale): Brush; }; /** * Gets or sets the current brush extent @@ -2518,21 +2518,23 @@ declare module D3 { threshold(): ThresholdScale; } - export interface Scale { + export interface Scale { (value: any): any; domain: { - (values: any[]): Scale; + (values: any[]): S; (): any[]; }; range: { - (values: any[]): Scale; + (values: any[]): S; (): any[]; }; invertExtent?(y: any): any[]; - copy(): Scale; + copy(): S; } - export interface QuantitativeScale extends Scale { + export interface UntypedScale extends Scale { } + + export interface QuantitativeScale extends Scale { /** * Get the range value corresponding to a given domain value. * @@ -2546,47 +2548,17 @@ declare module D3 { */ invert(value: number): number; /** - * Get or set the scale's input domain. - */ - domain: { - /** - * Set the scale's input domain. - * - * @param value The input domain - */ - (values: any[]): QuantitativeScale; - /** - * Get the scale's input domain. - */ - (): any[]; - }; - /** - * get or set the scale's output range. - */ - range: { - /** - * Set the scale's output range. - * - * @param value The output range. - */ - (values: any[]): QuantitativeScale; - /** - * Get the scale's output range. - */ - (): any[]; - }; - /** * Set the scale's output range, and enable rounding. * * @param value The output range. */ - rangeRound: (values: any[]) => QuantitativeScale; + rangeRound: (values: any[]) => S; /** * get or set the scale's output interpolator. */ interpolate: { (): D3.Transition.Interpolate; - (factory: D3.Transition.Interpolate): QuantitativeScale; + (factory: D3.Transition.Interpolate): S; }; /** * enable or disable clamping of the output range. @@ -2595,14 +2567,14 @@ declare module D3 { */ clamp: { (): boolean; - (clamp: boolean): QuantitativeScale; + (clamp: boolean): S; } /** * extend the scale domain to nice round numbers. * * @param count Optional number of ticks to exactly fit the domain */ - nice(count?: number): QuantitativeScale; + nice(count?: number): S; /** * get representative values from the input domain. * @@ -2615,22 +2587,11 @@ declare module D3 { * @param count Aproximate representative values to return */ tickFormat(count: number, format?: string): (n: number) => string; - /** - * create a new scale from an existing scale.. - */ - copy(): QuantitativeScale; } - export interface LinearScale extends QuantitativeScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface LinearScale extends QuantitativeScale { } - export interface IdentityScale extends Scale { + export interface IdentityScale extends Scale { /** * Get the range value corresponding to a given domain value. * @@ -2657,132 +2618,31 @@ declare module D3 { tickFormat(count: number): (n: number) => string; } - export interface SqrtScale extends QuantitativeScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface SqrtScale extends QuantitativeScale { } - export interface PowScale extends QuantitativeScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface PowScale extends QuantitativeScale { } - export interface LogScale extends QuantitativeScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface LogScale extends QuantitativeScale { } - export interface OrdinalScale extends Scale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: any): any; - /** - * Get or set the scale's input domain. - */ - domain: { - /** - * Set the scale's input domain. - * - * @param value The input domain - */ - (values: any[]): OrdinalScale; - /** - * Get the scale's input domain. - */ - (): any[]; - }; - /** - * get or set the scale's output range. - */ - range: { - /** - * Set the scale's output range. - * - * @param value The output range. - */ - (values: any[]): OrdinalScale; - /** - * Get the scale's output range. - */ - (): any[]; - }; + export interface OrdinalScale extends Scale { rangePoints(interval: any[], padding?: number): OrdinalScale; rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; rangeBand(): number; rangeExtent(): any[]; - /** - * create a new scale from an existing scale.. - */ - copy(): OrdinalScale; } - export interface QuantizeScale extends Scale { - (value: any): any; - domain: { - (values: number[]): QuantizeScale; - (): any[]; - }; - range: { - (values: any[]): QuantizeScale; - (): any[]; - }; - copy(): QuantizeScale; - } + export interface QuantizeScale extends Scale { } - export interface ThresholdScale extends Scale { - (value: any): any; - domain: { - (values: number[]): ThresholdScale; - (): any[]; - }; - range: { - (values: any[]): ThresholdScale; - (): any[]; - }; - copy(): ThresholdScale; - } + export interface ThresholdScale extends Scale { } - export interface QuantileScale extends Scale { - (value: any): any; - domain: { - (values: number[]): QuantileScale; - (): any[]; - }; - range: { - (values: any[]): QuantileScale; - (): any[]; - }; + export interface QuantileScale extends Scale { quantiles(): any[]; - copy(): QuantileScale; } - export interface TimeScale extends Scale { + export interface TimeScale extends Scale { (value: Date): number; invert(value: number): Date; - domain: { - (values: any[]): TimeScale; - (): any[]; - }; - range: { - (values: any[]): TimeScale; - (): any[]; - }; rangeRound: (values: any[]) => TimeScale; interpolate: { (): D3.Transition.Interpolate; @@ -2794,7 +2654,6 @@ declare module D3 { (range: D3.Time.Range, count: number): any[]; }; tickFormat(count: number): (n: number) => string; - copy(): TimeScale; nice(count?: number): TimeScale; } } @@ -2883,13 +2742,13 @@ declare module D3 { /** * Get the X-Scale */ - (): D3.Scale.Scale; + (): D3.Scale.UntypedScale; /** * Set the X-Scale to be adjusted * * @param x The X Scale */ - (x: D3.Scale.Scale): Zoom; + (x: D3.Scale.UntypedScale): Zoom; }; @@ -2900,13 +2759,13 @@ declare module D3 { /** * Get the Y-Scale */ - (): D3.Scale.Scale; + (): D3.Scale.UntypedScale; /** * Set the Y-Scale to be adjusted * * @param y The Y Scale */ - (y: D3.Scale.Scale): Zoom; + (y: D3.Scale.UntypedScale): Zoom; }; } From 435aaa1ddfb734d1a9dd7bf7b1b6e6b018c3bd18 Mon Sep 17 00:00:00 2001 From: Atsushi Kanehara Date: Thu, 7 Aug 2014 15:01:57 +0900 Subject: [PATCH 144/167] Added property upgradeReq --- ws/ws.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/ws/ws.d.ts b/ws/ws.d.ts index d12e2913f..99983df85 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -21,6 +21,7 @@ declare module "ws" { protocolVersion: string; url: string; supports: any; + upgradeReq: http.ServerRequest; CONNECTING: number; OPEN: number; From 9a4229df7e1d20ae547bd37b92d7e961cfbfe4f9 Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 7 Aug 2014 15:50:27 +0900 Subject: [PATCH 145/167] fix -test.ts to -tests.ts --- bucks/{bucks-test.ts => bucks-tests.ts} | 0 .../{http-string-parser-test.ts => http-string-parser-tests.ts} | 0 .../{jquery.notifyBar-test.ts => jquery.notifyBar-tests.ts} | 0 js-git/{js-git-test.ts => js-git-tests.ts} | 0 js-url/{js-url-test.ts => js-url-tests.ts} | 0 .../{passport-facebook-test.ts => passport-facebook-tests.ts} | 0 .../{passport-strategy-test.ts => passport-strategy-tests.ts} | 0 riotjs/{riotjs-test.ts => riotjs-tests.ts} | 0 .../{simple-cw-node-test.ts => simple-cw-node-tests.ts} | 0 tspromise/{tspromise-test.ts => tspromise-tests.ts} | 0 .../{universal-analytics-test.ts => universal-analytics-tests.ts} | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename bucks/{bucks-test.ts => bucks-tests.ts} (100%) rename http-string-parser/{http-string-parser-test.ts => http-string-parser-tests.ts} (100%) rename jquery.notifyBar/{jquery.notifyBar-test.ts => jquery.notifyBar-tests.ts} (100%) rename js-git/{js-git-test.ts => js-git-tests.ts} (100%) rename js-url/{js-url-test.ts => js-url-tests.ts} (100%) rename passport-facebook/{passport-facebook-test.ts => passport-facebook-tests.ts} (100%) rename passport-strategy/{passport-strategy-test.ts => passport-strategy-tests.ts} (100%) rename riotjs/{riotjs-test.ts => riotjs-tests.ts} (100%) rename simple-cw-node/{simple-cw-node-test.ts => simple-cw-node-tests.ts} (100%) rename tspromise/{tspromise-test.ts => tspromise-tests.ts} (100%) rename universal-analytics/{universal-analytics-test.ts => universal-analytics-tests.ts} (100%) diff --git a/bucks/bucks-test.ts b/bucks/bucks-tests.ts similarity index 100% rename from bucks/bucks-test.ts rename to bucks/bucks-tests.ts diff --git a/http-string-parser/http-string-parser-test.ts b/http-string-parser/http-string-parser-tests.ts similarity index 100% rename from http-string-parser/http-string-parser-test.ts rename to http-string-parser/http-string-parser-tests.ts diff --git a/jquery.notifyBar/jquery.notifyBar-test.ts b/jquery.notifyBar/jquery.notifyBar-tests.ts similarity index 100% rename from jquery.notifyBar/jquery.notifyBar-test.ts rename to jquery.notifyBar/jquery.notifyBar-tests.ts diff --git a/js-git/js-git-test.ts b/js-git/js-git-tests.ts similarity index 100% rename from js-git/js-git-test.ts rename to js-git/js-git-tests.ts diff --git a/js-url/js-url-test.ts b/js-url/js-url-tests.ts similarity index 100% rename from js-url/js-url-test.ts rename to js-url/js-url-tests.ts diff --git a/passport-facebook/passport-facebook-test.ts b/passport-facebook/passport-facebook-tests.ts similarity index 100% rename from passport-facebook/passport-facebook-test.ts rename to passport-facebook/passport-facebook-tests.ts diff --git a/passport-strategy/passport-strategy-test.ts b/passport-strategy/passport-strategy-tests.ts similarity index 100% rename from passport-strategy/passport-strategy-test.ts rename to passport-strategy/passport-strategy-tests.ts diff --git a/riotjs/riotjs-test.ts b/riotjs/riotjs-tests.ts similarity index 100% rename from riotjs/riotjs-test.ts rename to riotjs/riotjs-tests.ts diff --git a/simple-cw-node/simple-cw-node-test.ts b/simple-cw-node/simple-cw-node-tests.ts similarity index 100% rename from simple-cw-node/simple-cw-node-test.ts rename to simple-cw-node/simple-cw-node-tests.ts diff --git a/tspromise/tspromise-test.ts b/tspromise/tspromise-tests.ts similarity index 100% rename from tspromise/tspromise-test.ts rename to tspromise/tspromise-tests.ts diff --git a/universal-analytics/universal-analytics-test.ts b/universal-analytics/universal-analytics-tests.ts similarity index 100% rename from universal-analytics/universal-analytics-test.ts rename to universal-analytics/universal-analytics-tests.ts From 54d719d86ed92466b02f3020f0e510145db02f9d Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Thu, 7 Aug 2014 10:42:05 +0200 Subject: [PATCH 146/167] [Leaflet] Optional context argument in L.DomEvent.removeListener --- leaflet/leaflet.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 3332f9000..006d16c1e 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -574,7 +574,7 @@ declare module L { /** * Removes an event listener from the element. */ - static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void): DomEvent; + static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; /** * Stop the given event from propagation to parent elements. Used inside the From c1858577da71e678d994179dbe65c81258e7dc85 Mon Sep 17 00:00:00 2001 From: Antoine Pultier Date: Thu, 7 Aug 2014 10:42:43 +0200 Subject: [PATCH 147/167] [Leaflet] on and off alias for L.DomEvent --- leaflet/leaflet.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 006d16c1e..a1276cbe9 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -570,11 +570,13 @@ declare module L { * inside the listener will point to context, or to the element if not specified. */ static addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + static on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; /** * Removes an event listener from the element. */ static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + static off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; /** * Stop the given event from propagation to parent elements. Used inside the From 5f62479f18b6b2d80e8e213d5afca562a64d735f Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Thu, 7 Aug 2014 21:10:37 +0800 Subject: [PATCH 148/167] Rename htmlparser2tests.ts to htmlparser2-tests.ts --- htmlparser2/{htmlparser2tests.ts => htmlparser2-tests.ts} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename htmlparser2/{htmlparser2tests.ts => htmlparser2-tests.ts} (97%) diff --git a/htmlparser2/htmlparser2tests.ts b/htmlparser2/htmlparser2-tests.ts similarity index 97% rename from htmlparser2/htmlparser2tests.ts rename to htmlparser2/htmlparser2-tests.ts index 7ff887e65..c002da0e2 100644 --- a/htmlparser2/htmlparser2tests.ts +++ b/htmlparser2/htmlparser2-tests.ts @@ -21,4 +21,4 @@ var parser = new htmlparser.Parser({ }); parser.write("Xyz "); -parser.end(); \ No newline at end of file +parser.end(); From fcfe9fee87ea637598c57fe3ed07bb7b33a70359 Mon Sep 17 00:00:00 2001 From: Steven Date: Thu, 7 Aug 2014 18:24:19 -0700 Subject: [PATCH 149/167] Color.brighter has an optional number parameter --- d3/d3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 8f66f47a6..4b7f91ad7 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1492,7 +1492,7 @@ declare module D3 { /** * increase lightness by some exponential factor (gamma) */ - brighter(k: number): Color; + brighter(k?: number): Color; /** * decrease lightness by some exponential factor (gamma) */ From cc05933bbc0b8a7994ff743a33805218226ed5bc Mon Sep 17 00:00:00 2001 From: James Roland Cabresos Date: Fri, 8 Aug 2014 10:22:24 +0800 Subject: [PATCH 150/167] fix htmlparser tests --- htmlparser2/htmlparser2-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htmlparser2/htmlparser2-tests.ts b/htmlparser2/htmlparser2-tests.ts index c002da0e2..53f6ee2aa 100644 --- a/htmlparser2/htmlparser2-tests.ts +++ b/htmlparser2/htmlparser2-tests.ts @@ -6,7 +6,7 @@ import htmlparser = require("htmlparser2"); var parser = new htmlparser.Parser({ onopentag: (name:string, attribs:{[s:string]:string}) => { - if(name === "script" && attribs.type === "text/javascript"){ + if(name === "script" && attribs['type'] === "text/javascript"){ console.log("JS! Hooray!"); } }, From ad0059764af8e64555d9ddecebcbe62c7b1204db Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Fri, 8 Aug 2014 12:05:20 +0800 Subject: [PATCH 151/167] add Q.delay(ms: number) --- q/Q.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/q/Q.d.ts b/q/Q.d.ts index 617bf0140..90ec8b461 100644 --- a/q/Q.d.ts +++ b/q/Q.d.ts @@ -294,7 +294,10 @@ declare module Q { * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. */ export function delay(value: T, ms: number): Promise; - + /** + * Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. + */ + export function delay(ms: number): Promise ; /** * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. */ From fa83d0d39c561d98454f72ffc0e32a741a2c7994 Mon Sep 17 00:00:00 2001 From: Benjamin Cosman Date: Thu, 7 Aug 2014 21:50:52 -0700 Subject: [PATCH 152/167] d3: Changed Scale names for consistency --- d3/d3.d.ts | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 619d2bb36..07f071647 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1648,13 +1648,13 @@ declare module D3 { /** * Gets the x-scale associated with the brush */ - (): D3.Scale.UntypedScale; + (): D3.Scale.Scale; /** * Sets the x-scale associated with the brush * * @param accessor The new Scale */ - (scale: D3.Scale.UntypedScale): Brush; + (scale: D3.Scale.Scale): Brush; }; /** * Gets or sets the x-scale associated with the brush @@ -1663,13 +1663,13 @@ declare module D3 { /** * Gets the x-scale associated with the brush */ - (): D3.Scale.UntypedScale; + (): D3.Scale.Scale; /** * Sets the x-scale associated with the brush * * @param accessor The new Scale */ - (scale: D3.Scale.UntypedScale): Brush; + (scale: D3.Scale.Scale): Brush; }; /** * Gets or sets the current brush extent @@ -2518,7 +2518,7 @@ declare module D3 { threshold(): ThresholdScale; } - export interface Scale { + export interface GenericScale { (value: any): any; domain: { (values: any[]): S; @@ -2532,9 +2532,9 @@ declare module D3 { copy(): S; } - export interface UntypedScale extends Scale { } + export interface Scale extends GenericScale { } - export interface QuantitativeScale extends Scale { + export interface GenericQuantitativeScale extends GenericScale { /** * Get the range value corresponding to a given domain value. * @@ -2589,9 +2589,11 @@ declare module D3 { tickFormat(count: number, format?: string): (n: number) => string; } - export interface LinearScale extends QuantitativeScale { } + export interface QuantitativeScale extends GenericQuantitativeScale { } - export interface IdentityScale extends Scale { + export interface LinearScale extends GenericQuantitativeScale { } + + export interface IdentityScale extends GenericScale { /** * Get the range value corresponding to a given domain value. * @@ -2618,13 +2620,13 @@ declare module D3 { tickFormat(count: number): (n: number) => string; } - export interface SqrtScale extends QuantitativeScale { } + export interface SqrtScale extends GenericQuantitativeScale { } - export interface PowScale extends QuantitativeScale { } + export interface PowScale extends GenericQuantitativeScale { } - export interface LogScale extends QuantitativeScale { } + export interface LogScale extends GenericQuantitativeScale { } - export interface OrdinalScale extends Scale { + export interface OrdinalScale extends GenericScale { rangePoints(interval: any[], padding?: number): OrdinalScale; rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; @@ -2632,15 +2634,15 @@ declare module D3 { rangeExtent(): any[]; } - export interface QuantizeScale extends Scale { } + export interface QuantizeScale extends GenericScale { } - export interface ThresholdScale extends Scale { } + export interface ThresholdScale extends GenericScale { } - export interface QuantileScale extends Scale { + export interface QuantileScale extends GenericScale { quantiles(): any[]; } - export interface TimeScale extends Scale { + export interface TimeScale extends GenericScale { (value: Date): number; invert(value: number): Date; rangeRound: (values: any[]) => TimeScale; @@ -2742,13 +2744,13 @@ declare module D3 { /** * Get the X-Scale */ - (): D3.Scale.UntypedScale; + (): D3.Scale.Scale; /** * Set the X-Scale to be adjusted * * @param x The X Scale */ - (x: D3.Scale.UntypedScale): Zoom; + (x: D3.Scale.Scale): Zoom; }; @@ -2759,13 +2761,13 @@ declare module D3 { /** * Get the Y-Scale */ - (): D3.Scale.UntypedScale; + (): D3.Scale.Scale; /** * Set the Y-Scale to be adjusted * * @param y The Y Scale */ - (y: D3.Scale.UntypedScale): Zoom; + (y: D3.Scale.Scale): Zoom; }; } From 2f1b69b353b7feea498ce886abf059018131ddd3 Mon Sep 17 00:00:00 2001 From: Daniel Mane Date: Thu, 7 Aug 2014 22:36:44 -0700 Subject: [PATCH 153/167] Add missing properties to definitions for D3.set and D3.map. Paramaterize the function type for Set.add --- d3/d3.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 8f66f47a6..e6f26cbd5 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -848,14 +848,18 @@ declare module D3 { values(): Array; entries(): Array; forEach(func: (key: string, value: any) => void ): void; + empty(): boolean; + size(): number; } - export interface Set{ + export interface Set { has(value: any): boolean; - add(value: any): any; + add(value: T): T; remove(value: any): boolean; values(): Array; forEach(func: (value: any) => void ): void; + empty(): boolean; + size(): number; } export interface Random { From 3994e6d6a4da8d0b5c13d5f84653c0e28c4c12dd Mon Sep 17 00:00:00 2001 From: Eraknelo Date: Fri, 8 Aug 2014 15:45:39 +0200 Subject: [PATCH 154/167] Capitalization error http://msdn.microsoft.com/en-us/library/office/jj245318(v=office.15).aspx --- sharepoint/SharePoint.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 1f7a2feaf..0be396fe6 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -4573,7 +4573,7 @@ declare module SP { get_id(): number; get_information(): SP.TimeZoneInformation; localTimeToUTC(date: Date): SP.DateTimeResult; - uTCToLocalTime(date: Date): SP.DateTimeResult; + utcToLocalTime(date: Date): SP.DateTimeResult; } export class TimeZoneCollection extends SP.ClientObjectCollection { itemAt(index: number): SP.TimeZone; From 82447ac01078f1f5d9b25ea27712c3317f94adde Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Fri, 8 Aug 2014 12:24:43 -0300 Subject: [PATCH 155/167] squash! fix tabs directive interface definition and tests --- angularjs/angular-tests.ts | 32 +++++++++++++++++--------------- angularjs/angular.d.ts | 19 ++++++++++--------- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 9c1cc0ab4..220a63dec 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -285,15 +285,17 @@ class SampleDirective implements ng.IDirective { public restrict = 'A'; name = 'doh'; - compile(templateElement: any) { - return this.link; + compile(templateElement: ng.IAugmentedJQuery) { + return { + post: this.link + }; } static instance():ng.IDirective { return new SampleDirective(); } - link(scope: any) { + link(scope: ng.IScope) { } } @@ -301,7 +303,7 @@ class SampleDirective implements ng.IDirective { class SampleDirective2 implements ng.IDirective { public restrict = 'EAC'; - compile(templateElement: any) { + compile(templateElement: ng.IAugmentedJQuery) { return { pre: this.link }; @@ -311,7 +313,7 @@ class SampleDirective2 implements ng.IDirective { return new SampleDirective2(); } - link(scope: any) { + link(scope: ng.IScope) { } } @@ -413,10 +415,10 @@ angular.module('docsTimeDirective', []) .controller('Controller', ['$scope', function($scope: any) { $scope.format = 'M/d/yy h:mm:ss a'; }]) - .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) { return { - link: function(scope: any, element: any, attrs: any) { + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) { var format: any, timeoutId: any; @@ -424,7 +426,7 @@ angular.module('docsTimeDirective', []) element.text(dateFilter(new Date(), format)); } - scope.$watch(attrs.myCurrentTime, function (value: any) { + scope.$watch(attrs['myCurrentTime'], function (value: any) { format = value; updateTime(); }); @@ -463,8 +465,8 @@ angular.module('docsTransclusionExample', []) transclude: true, scope: {}, templateUrl: 'my-dialog.html', - link: function (scope: any, element: any) { - scope.name = 'Jeff'; + link: function (scope: ng.IScope, element: ng.IAugmentedJQuery) { + scope['name'] = 'Jeff'; } }; }); @@ -533,10 +535,10 @@ angular.module('docsTabsExample', []) restrict: 'E', transclude: true, scope: {}, - controller: function($scope: any) { - var panes: any = $scope.panes = []; + controller: function($scope: ng.IScope) { + var panes: any = $scope['panes'] = []; - $scope.select = function(pane: any) { + $scope['select'] = function(pane: any) { angular.forEach(panes, function(pane: any) { pane.selected = false; }); @@ -545,7 +547,7 @@ angular.module('docsTabsExample', []) this.addPane = function(pane: any) { if (panes.length === 0) { - $scope.select(pane); + $scope['select'](pane); } panes.push(pane); }; @@ -561,7 +563,7 @@ angular.module('docsTabsExample', []) scope: { title: '@' }, - link: function(scope: any, element: any, attrs: any, tabsCtrl: any) { + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { tabsCtrl.addPane(scope); }, templateUrl: 'my-pane.html' diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 83dcc151f..282463bcb 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -316,6 +316,7 @@ declare module ng { // see http://docs.angularjs.org/api/ng.$rootScope.Scope /////////////////////////////////////////////////////////////////////////// interface IScope { + [index: string]: any; $apply(): any; $apply(exp: string): any; $apply(exp: (scope: IScope) => any): any; @@ -1033,11 +1034,11 @@ declare module ng { interface IDirectiveLinkFn { ( - scope?: IScope, - instanceElement?: IAugmentedJQuery, - instanceAttributes?: IAttributes, - controller?: any, - transclude?: ITranscludeFunction + scope: IScope, + instanceElement: IAugmentedJQuery, + instanceAttributes: IAttributes, + controller: any, + transclude: ITranscludeFunction ): void; } @@ -1048,13 +1049,13 @@ declare module ng { interface IDirectiveCompileFn { ( - templateElement?: IAugmentedJQuery, - templateAttributes?: IAttributes, - transclude?: ITranscludeFunction + templateElement: IAugmentedJQuery, + templateAttributes: IAttributes, + transclude: ITranscludeFunction ): IDirectivePrePost; } - interface IDirective{ + interface IDirective { compile?: IDirectiveCompileFn; controller?: any; controllerAs?: string; From 3878a37dfad2c3ad01d6be3988aa7d5460519b58 Mon Sep 17 00:00:00 2001 From: Pedro Casaubon Date: Fri, 8 Aug 2014 19:10:43 +0200 Subject: [PATCH 156/167] Added node-webkit definitions --- node-webkit/node-webkit-tests.ts | 203 ++++++++++++++++++++++++++++ node-webkit/node-webkit.d.ts | 221 +++++++++++++++++++++++++++++++ 2 files changed, 424 insertions(+) create mode 100644 node-webkit/node-webkit-tests.ts create mode 100644 node-webkit/node-webkit.d.ts diff --git a/node-webkit/node-webkit-tests.ts b/node-webkit/node-webkit-tests.ts new file mode 100644 index 000000000..da10f2901 --- /dev/null +++ b/node-webkit/node-webkit-tests.ts @@ -0,0 +1,203 @@ +/// +/// +// Load native UI library +var gui: typeof nw.gui; + + +/* WINDOW */ + + // Get the current window + var win = gui.Window.get(); + + // Listen to the minimize event + win.on('minimize', function() { + console.log('Window is minimized'); + }); + + // Minimize the window + win.minimize(); + + // Unlisten the minimize event + win.removeAllListeners('minimize'); + + // Create a new window and get it + var new_win = gui.Window.get( + window.open('https://github.com') + ); + + // And listen to new window's focus event + new_win.on('focus', function() { + console.log('New window is focused'); + }); + + + // Get the current window + var win = gui.Window.get(); + + // Create a new window and get it + var new_win = gui.Window.get( + window.open('https://github.com') + ); + + // png as base64string + win.capturePage(function(base64string:string){ + // do something with the base64string + }, { format : 'png', datatype : 'raw'} ); + + // png as node buffer + win.capturePage(function(buffer:Buffer){ + // do something with the buffer + }, { format : 'png', datatype : 'buffer'} ); + + + // Open a new window. + var win = gui.Window.get( + window.open('popup.html') + ); + + // Release the 'win' object here after the new window is closed. + win.on('closed', function() { + win = null; + }); + + // Listen to main window's close event + gui.Window.get().on('close', function() { + // Hide the window to give user the feeling of closing immediately + this.hide(); + + // If the new window is still open then close it. + if (win != null) + win.close(true); + + // After closing the new window, close the main window. + this.close(true); + }); + + +/* MENU */ + + // Create an empty menu + var menu = new gui.Menu(); + + // Add some items + menu.append(new gui.MenuItem({ label: 'Item A' })); + menu.append(new gui.MenuItem({ label: 'Item B' })); + menu.append(new gui.MenuItem({ type: 'separator' })); + menu.append(new gui.MenuItem({ label: 'Item C' })); + + // Remove one item + menu.removeAt(1); + + // Popup as context menu + menu.popup(10, 10); + + // Iterate menu's items + for (var i = 0; i < menu.items.length; ++i) { + console.log(menu.items[i]); + } + + + var win = gui.Window.get(); + var nativeMenuBar = new gui.Menu({ type: "menubar" }); + nativeMenuBar.createMacBuiltin("My App"); + win.menu = nativeMenuBar; + + nativeMenuBar.createMacBuiltin("My App", { + hideEdit: true, + hideWindow: true + }); + +/* MENU ITEM */ + + var itemc:nw.gui.MenuItem; + + // Create a separator + itemc = new gui.MenuItem({ type: 'separator' }); + + // Create a normal item with label and icon + itemc = new gui.MenuItem({ + type: "normal", + label: "I'm a menu item", + icon: "img/icon.png" + }); + + // Or you can omit the 'type' field for normal items + itemc = new gui.MenuItem({ label: 'Simple item' }); + + // Bind a callback to item + itemc = new gui.MenuItem({ + label: "Click me", + click: function() { + console.log("I'm clicked"); + }, + key: "s", + modifiers: "ctrl-alt", + }); + + // You can have submenu! + var submenu = new gui.Menu(); + submenu.append(new gui.MenuItem({ label: 'Item 1' })); + submenu.append(new gui.MenuItem({ label: 'Item 2' })); + submenu.append(new gui.MenuItem({ label: 'Item 3' })); + itemc.submenu = submenu; + + // And everything can be changed at runtime + itemc.label = 'New label'; + itemc.click = function() { console.log('New click callback'); }; + + +/* APP */ + + // Print arguments + console.log(gui.App.argv); + + // Quit current app + gui.App.quit(); + + // Get the name field in manifest + gui.App.manifest.name + + gui.App.addOriginAccessWhitelistEntry('http://github.com/', 'app', 'myapp', true); + + +/* CLIPBOARD */ + + // We can not create a clipboard, we have to receive the system clipboard + var clipboard = gui.Clipboard.get(); + + // Read from clipboard + var text = clipboard.get('text'); + console.log(text); + + // Or write something + clipboard.set('I love node-webkit :)', 'text'); + + // And clear it! + clipboard.clear(); + + +/* TRAY */ + + // Create a tray icon + var tray = new gui.Tray({ title: 'Tray', icon: 'img/icon.png' }); + + // Give it a menu + var menu = new gui.Menu(); + menu.append(new gui.MenuItem({ type: 'checkbox', label: 'box1' })); + tray.menu = menu; + + // Remove the tray + tray.remove(); + tray = null; + + +/* SHELL */ + + // Open URL with default browser. + gui.Shell.openExternal('https://github.com/rogerwang/node-webkit'); + + // Open a text file with default text editor. + gui.Shell.openItem('test.txt'); + + // Open a file in file explorer. + gui.Shell.showItemInFolder('test.txt'); \ No newline at end of file diff --git a/node-webkit/node-webkit.d.ts b/node-webkit/node-webkit.d.ts new file mode 100644 index 000000000..92afbff2d --- /dev/null +++ b/node-webkit/node-webkit.d.ts @@ -0,0 +1,221 @@ +// Type definitions for node-webkit +// Project: https://github.com/rogerwang/node-webkit +// Definitions by: Pedro Casaubon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module nw.gui { + + interface IEventEmitter { + 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; + } + + class EventEmitter implements IEventEmitter { + 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 interface MenuConfig { + type?: string; + } + + export interface HideMenusOptions { + hideEdit: boolean; + hideWindow: boolean; + } + + export interface MenuItemConfig { + label?: string; + click?: Function; + type?: string; + submenu?: Menu; + icon?: string; + tooltip?: string; + checked?: boolean; + enabled?: boolean; + key?: string; + modifiers?: string; + } + + export class MenuItem extends EventEmitter implements MenuItemConfig { + constructor(config: MenuItemConfig); + label: string; + click: Function; + type: string; + submenu: Menu; + icon: string; + tooltip: string; + checked: boolean; + enabled: boolean; + key: string; + modifiers: string; + } + + export class Menu { + constructor(config?: MenuConfig); + items: MenuItem[]; + append(item: MenuItem): void; + remove(item: MenuItem): void; + insert(item: MenuItem, atPosition: number): void; + removeAt(index: number): void; + popup(x: number, y: number): void; + // since v0.10.0-rc1 + createMacBuiltin(appname: string, options?: HideMenusOptions): void; + + } + + export interface ShortcutOption { + key: string; + active: Function; + failed: Function; + } + + export class Shortcut extends EventEmitter { + constructor(option: ShortcutOption); + key: string; + active: Function; + failed: Function; + } + + export interface WindowManifestOptions { + + title?: string; + icon?: string; + toolbar?: boolean; + frame?: boolean; + width?: number; + height?: number; + position?: string; + min_width?: number; + min_height?: number; + max_width?: number; + max_height?: number; + } + + export class Window extends EventEmitter { + static get(windowObject?: any): Window; + static open(url: string, options?: WindowManifestOptions): Window; + x: number; + y: number; + width: number; + height: number; + title: string; + menu: Menu; + isFullScreen: boolean; + isKioskMode: boolean; + zoomLevel: number; + moveTo(x: number, y: number): void; + moveBy(x: number, y: number): void; + resizeTo(width: number, height: number): void; + resizeBy(width: number, height: number): void; + focus(): void; + blur(): void; + show(): void; + hide(): void; + close(force?: boolean): void; + reload(): void; + reloadIgnoringCache(): void; + maximize(): void; + unmaximize(): void; + minimize(): void; + restore(): void; + enterFullscreen(): void; + leaveFullscreen(): void; + toggleFullscreen(): void; + enterKioskMode(): void; + leaveKioskMode(): void; + toggleKioskMode(): void; + showDevTools(id?: string, headless?: boolean): void; + showDevTools(id: HTMLIFrameElement, headless?: boolean): void; + closeDevTools(): void; + isDevToolsOpen(): boolean; + setMaximumSize(width: number, height: number): void; + setMinimumSize(width: number, height: number): void; + setResizable(resizable: boolean): void; + setAlwaysOnTop(top: boolean): void; + setPosition(position: string): void; + setShowInTaskbar(show: boolean): void; + requestAttention(attention: boolean): void; + requestAttention(attention: number): void; + capturePage(callback: Function, imageformat?: string): void; + capturePage(callback: Function, config_object: { format: string; datatype: string }): void; + setProgressBar(progress: number): void; + setBadgeLabel(label: string): void; + eval(frame: HTMLIFrameElement, script: string): void; + } + + export interface App { + argv: any; + fullArgv: any; + dataPath: string; + manifest: any; + clearCache(): void; + closeAllWindows(): void; + crashBrowser(): void; + crashRenderer(): void; + getProxyForURL(url: string): void; + quit(): void; + setCrashDumpDir(dir: string): void; + addOriginAccessWhitelistEntry( + sourceOrigin: string + , destinationProtocol: string + , destinationHost: string + , allowDestinationSubdomains: boolean + ): void; + removeOriginAccessWhitelistEntry( + sourceOrigin: string + , destinationProtocol: string + , destinationHost: string + , allowDestinationSubdomains: boolean + ): void; + registerGlobalHotKey(shortcut: Shortcut): void; + unregisterGlobalHotKey(shortcut: Shortcut): void; + } + + export class Clipboard { + static get(): Clipboard; + get(type?: string): string; + set(data: string, type?: string): void; + clear(): void; + } + + export interface TrayOption { + title?: string; + tooltip?: string; + icon?: string; + alticon?: string; + menu?: Menu; + } + + export class Tray implements TrayOption { + constructor(option: TrayOption); + title: string; + tooltip: string; + icon: string; + alticon: string; + menu: Menu; + remove(): void; + } + + interface Shell { + openExternal(uri: string): void; + openItem(file_path: string): void; + showItemInFolder(file_path: string): void; + } + + export var App: App; + export var Shell: Shell; + +} From a2c53774bb554ac7f73ab4ff0212ad1eccef48d3 Mon Sep 17 00:00:00 2001 From: nitram509 Date: Fri, 8 Aug 2014 23:11:14 +0200 Subject: [PATCH 157/167] added missing method 'getBoundingRect()' for fabric.js, which is available since ~1.0.4 --- fabricjs/fabricjs.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index eec70c8f6..cfca6c481 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -335,6 +335,7 @@ declare module fabric { drawBorders(context: CanvasRenderingContext2D): IObject; drawCorners(context: CanvasRenderingContext2D): IObject; get (property: string): any; + getBoundingRect(): {left:number; top:number; width:number; height:number}; getBoundingRectHeight(): number; getBoundingRectWidth(): number; getSvgStyles(): string; From c8706caad0a134f84c889381e990454f7791304f Mon Sep 17 00:00:00 2001 From: Anthony Date: Fri, 8 Aug 2014 19:57:23 -0400 Subject: [PATCH 158/167] New definitions for Jasmine data driven tests --- .../jasmine-data_driven_tests-tests.ts | 54 +++++++++++++++++++ .../jasmine-data_driven_tests.d.ts | 7 +++ 2 files changed, 61 insertions(+) create mode 100644 jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts create mode 100644 jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts new file mode 100644 index 000000000..df48df8cf --- /dev/null +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts @@ -0,0 +1,54 @@ +/// +/// + +all("A data driven test is a suite with multiple specs", + ['a', 'b', 'c'], + (value: string) => { + expect(value).not.toBe('d'); + } +); + +all("A data driven test can have many arguments", + [ + [1, 2, 3], + [2, 4, 6] + ], + (a: number, b: number, c: number) => { + expect(c - (a + b)).toBe(0); + } +); + +all("A data driven test can be asynchronous", + [ + [3, 1], + [5, 2] + ], + (a: number, b: number, done: () => void) => { + setTimeout(() => { + expect(a - b > 0).toBe(true); + done(); + }, 50); + } +); + +xall("A data driven test can be pending", + [1, 2, 3], + (value: number) => { + expect(value < 4).toBe(true); + } +); + +describe("A suite", () => { + var a: number; + + beforeEach(() => { + a = 5; + }); + + all("can contain data driven tests", + [1, 2, 3], + (b: number) => { + expect(a - b > 0).toBe(true); + } + ); +}); \ No newline at end of file diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts new file mode 100644 index 000000000..c0936872b --- /dev/null +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts @@ -0,0 +1,7 @@ +// Type definitions for Jasmine Data Driven Tests +// Project: https://github.com/gburghardt/jasmine-data_driven_tests +// Definitions by: Anthony MacKinnon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare function all(description: string, dataset: any[], specDefinitions: (...args: any[]) => void): void; +declare function xall(description: string, dataset: any[], specDefinitions: (...args: any[]) => void): void; \ No newline at end of file From 153b4f3fa354d799090212979ae559ec44dd05c4 Mon Sep 17 00:00:00 2001 From: Anthony Date: Sat, 9 Aug 2014 00:15:18 -0400 Subject: [PATCH 159/167] Renamed callback to assertion to be consistent with Jasmine naming --- jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts index c0936872b..912720e7f 100644 --- a/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests.d.ts @@ -3,5 +3,5 @@ // Definitions by: Anthony MacKinnon // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare function all(description: string, dataset: any[], specDefinitions: (...args: any[]) => void): void; -declare function xall(description: string, dataset: any[], specDefinitions: (...args: any[]) => void): void; \ No newline at end of file +declare function all(description: string, dataset: any[], assertion: (...args: any[]) => void): void; +declare function xall(description: string, dataset: any[], assertion: (...args: any[]) => void): void; \ No newline at end of file From 343cca373bca9e0241911b3cace7c4d303e5fd02 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Sat, 9 Aug 2014 23:17:03 +0800 Subject: [PATCH 160/167] add definitions for q-retry --- CONTRIBUTORS.md | 1 + q-retry/q-retry-tests.ts | 39 +++++++++++++++++++++++++++++++++++++++ q-retry/q-retry.d.ts | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 q-retry/q-retry-tests.ts create mode 100644 q-retry/q-retry.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1b2eda33d..fceb55e98 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -291,6 +291,7 @@ All definitions files include a header with the author and editors, so at some p * [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) * [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [q-retry](https://github.com/vilic/q-retry) (by [VILIC VANE](https://github.com/vilic)) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) * [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo)) * [Recaptcha.js](https://www.google.com/recaptcha) (by [Brent Jenkins](https://github.com/brentj73)) diff --git a/q-retry/q-retry-tests.ts b/q-retry/q-retry-tests.ts new file mode 100644 index 000000000..bf72f8ad7 --- /dev/null +++ b/q-retry/q-retry-tests.ts @@ -0,0 +1,39 @@ +import Q = require('q-retry'); + +Q + .retry(() => { + return ''; + }) + .then(str => { + str.charAt; + return 0; + }) + .retry(num => { + num.toFixed; + }) + .retry(() => { + + }, 5) + .retry(() => { + + }, (reason, retries) => { + retries.toFixed; + }) + .retry(() => { + + }, (reason, retries) => { + retries.toFixed; + }, 10) + .retry(() => { + return ''; + }, (reason, retries) => { + + }, { + limit: 10, + interval: 1000, + maxInterval: 20000, + intervalMultiplier: 1.5 + }) + .then(str => { + str.charAt; + }); \ No newline at end of file diff --git a/q-retry/q-retry.d.ts b/q-retry/q-retry.d.ts new file mode 100644 index 000000000..fe6b42fd8 --- /dev/null +++ b/q-retry/q-retry.d.ts @@ -0,0 +1,39 @@ +// Type definitions for q-retry +// Project: https://github.com/vilic/q-retry +// Definitions by: VILIC VANE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Q { + export interface IRetryOptions { + limit?: number; + interval?: number; + maxInterval?: number; + intervalMultiplier?: number; + } + + export function retry(process: () => IPromise, onFail: (reason: any, retries: number) => void, limit: number): Promise; + export function retry(process: () => IPromise, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + export function retry(process: () => IPromise, limit: number): Promise; + export function retry(process: () => IPromise, options?: IRetryOptions): Promise; + export function retry(process: () => U, onFail: (reason: any, retries: number) => void, limit: number): Promise; + export function retry(process: () => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + export function retry(process: () => U, limit: number): Promise; + export function retry(process: () => U, options?: IRetryOptions): Promise; + + interface Promise { + retry(process: (value: T) => IPromise, onFail: (reason: any, retries: number) => void, limit: number): Promise; + retry(process: (value: T) => IPromise, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + retry(process: (value: T) => IPromise, limit: number): Promise; + retry(process: (value: T) => IPromise, options?: IRetryOptions): Promise; + retry(process: (value: T) => U, onFail: (reason: any, retries: number) => void, limit: number): Promise; + retry(process: (value: T) => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + retry(process: (value: T) => U, limit: number): Promise; + retry(process: (value: T) => U, options?: IRetryOptions): Promise; + } +} + +declare module "q-retry" { + export = Q; +} \ No newline at end of file From f402bb57bdc4cba9132a1498e7dc566b68629b98 Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Sun, 10 Aug 2014 00:55:22 +0800 Subject: [PATCH 161/167] add definitions for promise-pool --- CONTRIBUTORS.md | 1 + promise-pool/promise-pool-tests.ts | 47 +++++++++++ promise-pool/promise-pool.d.ts | 124 +++++++++++++++++++++++++++++ 3 files changed, 172 insertions(+) create mode 100644 promise-pool/promise-pool-tests.ts create mode 100644 promise-pool/promise-pool.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fceb55e98..960b5dff2 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -289,6 +289,7 @@ All definitions files include a header with the author and editors, so at some p * [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/)) * [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) * [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [promise-pool](https://github.com/vilic/promise-pool) (by [VILIC VANE](https://github.com/vilic)) * [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) * [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) * [q-retry](https://github.com/vilic/q-retry) (by [VILIC VANE](https://github.com/vilic)) diff --git a/promise-pool/promise-pool-tests.ts b/promise-pool/promise-pool-tests.ts new file mode 100644 index 000000000..783d571ca --- /dev/null +++ b/promise-pool/promise-pool-tests.ts @@ -0,0 +1,47 @@ +import Q = require('q'); +import promisePool = require('promise-pool'); + +var pool = new promisePool.Pool((taskDataId, index) => { + return Q.delay(Math.floor(Math.random() * 5000)).then(function () { + taskDataId == 0; + index == 0; + }); +}, 20); + +pool + .pause() + .delay(5000) + .then(function () { + pool.resume(); + }); + +pool.retries == 0; +pool.retryInterval == 0; +pool.maxRetryInterval == 0; +pool.retryIntervalMultiplier == 0; + +pool.add(0); + +pool + .start(onProgress) + .then(result => { + result.total == 0; + return pool.reset(); + }) + .then(() => { + return pool.start(onProgress); + }) + .then(result => { + result.total == 0; + return pool.reset(); + }) + .then(() => { + pool.endless == true; + }); + +function onProgress(progress: promisePool.IProgress) { + progress.success == true; + progress.fulfilled == 0; + progress.total == 0; + progress.index == 0; +} \ No newline at end of file diff --git a/promise-pool/promise-pool.d.ts b/promise-pool/promise-pool.d.ts new file mode 100644 index 000000000..b38a54262 --- /dev/null +++ b/promise-pool/promise-pool.d.ts @@ -0,0 +1,124 @@ +// Type definitions for promise-pool +// Project: https://github.com/vilic/promise-pool +// Definitions by: VILIC VANE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "promise-pool" { + /** + * interface for the final result. + */ + export interface IResult { + fulfilled: number; + rejected: number; + total: number; + } + /** + * interface for progress data. + */ + export interface IProgress { + index: number; + success: boolean; + error: any; + retries: number; + fulfilled: number; + rejected: number; + pending: number; + total: number; + } + /** + * tasks pool that manages concurrency. + */ + export class Pool { + /** + * (get/set) the max concurrency of this task pool. + */ + public concurrency: number; + private _tasksData; + /** + * (get/set) the processor function that handles tasks data. + */ + public processor: (data: T, index: number) => Q.Promise; + private _deferred; + private _pauseDeferred; + /** + * (get) the number of successful tasks. + */ + public fulfilled: number; + /** + * (get) the number of failed tasks. + */ + public rejected: number; + /** + * (get) the number of pending tasks. + */ + public pending: number; + /** + * (get) the number of completed tasks and pending tasks in total. + */ + public total: number; + /** + * (get/set) indicates whether this task pool is endless, if so, tasks can still be added even after all previous tasks have been fulfilled. + */ + public endless: boolean; + /** + * (get/set) defaults to 0, the number or retries that this task pool will take for every single task, could be Infinity. + */ + public retries: number; + /** + * (get/set) defaults to 0, interval (milliseconds) between each retries. + */ + public retryInterval: number; + /** + * (get/set) defaults to Infinity, max retry interval when retry interval multiplier applied. + */ + public maxRetryInterval: number; + /** + * (get/set) defaults to 1, the multiplier applies to interval after every retry. + */ + public retryIntervalMultiplier: number; + private _index; + private _currentConcurrency; + public onProgress: (progress: IProgress) => void; + /** + * initialize a task pool. + * @param processor a function takes the data and index as parameters and returns a promise. + * @param concurrency the concurrency of this task pool. + * @param endless defaults to false. indicates whether this task pool is endless, if so, tasks can still be added even after all previous tasks have been fulfilled. + * @param tasksData an initializing array of task data. + */ + constructor(processor: (data: T, index: number) => Q.Promise, concurrency: number, endless?: boolean, tasksData?: T[]); + /** + * add a data item. + * @param taskData task data to add. + */ + public add(taskData: T): void; + /** + * add data items. + * @param tasskData tasks data to add. + */ + public add(tasksData: T[]): void; + /** + * start tasks, return a promise that will be fulfilled after all tasks accomplish if endless is false. + * @param onProgress a callback that will be triggered every time when a single task is fulfilled. + */ + public start(onProgress?: (progress: IProgress) => void): Q.Promise; + private _start(); + private _process(data, index); + private _notifyProgress(index, success, err, retries); + private _next(); + /** + * pause tasks and return a promise that will be fulfilled after the running tasks accomplish. this will wait for running tasks to complete instead of aborting them. + */ + public pause(): Q.Promise; + /** + * resume tasks. + */ + public resume(): void; + /** + * pause tasks, then clear pending tasks data and reset counters. return a promise that will be fulfilled after resetting accomplish. + */ + public reset(): Q.Promise; + } +} \ No newline at end of file From 8ce72b147361bc618129405bd8ccaf5a5ac8e05c Mon Sep 17 00:00:00 2001 From: VILIC VANE Date: Sun, 10 Aug 2014 01:40:01 +0800 Subject: [PATCH 162/167] change processor return type from Q.Promise to Q.IPromise --- promise-pool/promise-pool.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/promise-pool/promise-pool.d.ts b/promise-pool/promise-pool.d.ts index b38a54262..b9214e7f0 100644 --- a/promise-pool/promise-pool.d.ts +++ b/promise-pool/promise-pool.d.ts @@ -39,7 +39,7 @@ declare module "promise-pool" { /** * (get/set) the processor function that handles tasks data. */ - public processor: (data: T, index: number) => Q.Promise; + public processor: (data: T, index: number) => Q.IPromise; private _deferred; private _pauseDeferred; /** @@ -88,7 +88,7 @@ declare module "promise-pool" { * @param endless defaults to false. indicates whether this task pool is endless, if so, tasks can still be added even after all previous tasks have been fulfilled. * @param tasksData an initializing array of task data. */ - constructor(processor: (data: T, index: number) => Q.Promise, concurrency: number, endless?: boolean, tasksData?: T[]); + constructor(processor: (data: T, index: number) => Q.IPromise, concurrency: number, endless?: boolean, tasksData?: T[]); /** * add a data item. * @param taskData task data to add. From 79139ac1702e0089445e2b8f8af4fb3160e2742c Mon Sep 17 00:00:00 2001 From: Anthony Date: Sat, 9 Aug 2014 13:54:31 -0400 Subject: [PATCH 163/167] Added name to contributors --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 5292ba4bf..c53c7559f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -138,6 +138,7 @@ All definitions files include a header with the author and editors, so at some p * [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) * [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) * [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Jasmine-data_driven_tests](https://github.com/gburghardt/jasmine-data_driven_tests) (by [Anthony MacKinnon](https://github.com/AnthonyMacKinnon)) * [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac)) * [jDataView](https://github.com/jDataView/jDataView) (by [Ingvar Stepanyan](https://github.com/RReverser)) * [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel)) From f2de3867de193326103f9a394701efec4b452618 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sat, 9 Aug 2014 18:15:54 -0300 Subject: [PATCH 164/167] squash! squash! fix tabs rootscope <> iscope --- angularjs/angular.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 282463bcb..1c3e96160 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -315,8 +315,7 @@ declare module ng { // Scope // see http://docs.angularjs.org/api/ng.$rootScope.Scope /////////////////////////////////////////////////////////////////////////// - interface IScope { - [index: string]: any; + interface IRootScopeService { $apply(): any; $apply(exp: string): any; $apply(exp: (scope: IScope) => any): any; @@ -353,6 +352,7 @@ declare module ng { $parent: IScope; $root: IRootScopeService; + this: IRootScopeService; $id: string; @@ -967,7 +967,9 @@ declare module ng { // RootScopeService // see http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// - interface IRootScopeService extends IScope {} + interface IScope extends IRootScopeService { + [index: string]: any; + } /////////////////////////////////////////////////////////////////////////// // SCEService From 186c0182cd72798b4aa0ad11b7bf0f47db10ee09 Mon Sep 17 00:00:00 2001 From: Adrien Bustany Date: Sat, 9 Aug 2014 23:44:06 +0200 Subject: [PATCH 165/167] d3: Enable usage as an external module --- d3/d3.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 173603354..2229fa8a4 100755 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -3353,3 +3353,7 @@ declare module D3 { } declare var d3: D3.Base; + +declare module "d3" { + export = d3; +} From 548cb78ce6cd35fba48d31ec693f9dec44af433f Mon Sep 17 00:00:00 2001 From: Adrien Bustany Date: Sat, 9 Aug 2014 23:44:45 +0200 Subject: [PATCH 166/167] d3: Fix file permissions There is no reason to have this file executable. --- d3/d3.d.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 d3/d3.d.ts diff --git a/d3/d3.d.ts b/d3/d3.d.ts old mode 100755 new mode 100644 From 16dffed6f38c4c6f12e42282b4b259336049e4ba Mon Sep 17 00:00:00 2001 From: basarat Date: Sun, 10 Aug 2014 20:59:13 +1000 Subject: [PATCH 167/167] angular: $scope extends $rootScope. closes #2593 --- angularjs/angular.d.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 1c3e96160..cacf7647b 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -312,8 +312,8 @@ declare module ng { } /////////////////////////////////////////////////////////////////////////// - // Scope - // see http://docs.angularjs.org/api/ng.$rootScope.Scope + // Scope and RootScope + // see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// interface IRootScopeService { $apply(): any; @@ -361,6 +361,10 @@ declare module ng { $$phase: any; } + interface IScope extends IRootScopeService { + [index: string]: any; + } + interface IAngularEvent { targetScope: IScope; currentScope: IScope; @@ -963,14 +967,6 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// interface ITemplateCacheService extends ICacheObject {} - /////////////////////////////////////////////////////////////////////////// - // RootScopeService - // see http://docs.angularjs.org/api/ng.$rootScope - /////////////////////////////////////////////////////////////////////////// - interface IScope extends IRootScopeService { - [index: string]: any; - } - /////////////////////////////////////////////////////////////////////////// // SCEService // see http://docs.angularjs.org/api/ng.$sce